问:
Disable "Save Password" action sheet when exiting UIViewController?
My app has a "Create Account" view controller (shown below) that prompts the user to enter a username and password.  Whenever I segue to another view controller, I get a pop-up action sheet prompting to save the password in the keychain.

This is a nifty little freebie IF the user successfully creates the new account.  But I get this same pop-up if the user hits the cancel (back) button in the navigation bar, if they select the option to use Facebook login instead of creating an account, or any other means for leaving this view controller (see figures below).

How can I get this popup to ONLY show up when the user successfully creates a new account?

EDIT: Per request, here is the code that is related to the segues that result in the appearance of the "Save Password" action sheet.

from CreateAccountViewController.swift:

```<code>class CreateAccountViewController : UIViewController
{
  // ... bunch of irrelevant code deleted ...

  // bound to "Connect with Facebook" button (see image below)
  @IBAction func switchToFacebook(_ sender : UIButton)
  {
    performSegue(.SwitchToFacebookLogin, sender: sender)
  }
  // ... bunch of irrelevant code deleted ...
}

extension CreateAccountViewController : GameServerAlertObserver
{
  // callback based on response from GameCenter after
  //  submitting a "create new user" request
  func handleConnectionResponse(_ response:GameServerResponse )
  {
    switch response
    {
    // ... other response cases removed ...
    case .UserCreated:
      self.removeSpinner()
      performSegue(.CreateAccountToStartup, sender: self)

    default:
      response.displayAlert(over: self, observer: self)
      self.removeSpinner()
    }
  }

  // Functions defined in the GameServerAlertObserver protocol
  //   to handle user response to "User Exists Popup" (figure below)
  func ok()
  {
    // user chose to enter new  password... clear the existing username field
    usernameTextField.text = ""
  }

  func cancel()
  {
    // segue back to the startup view controller
    performSegue(.CreateAccountToStartup, sender: self)
  }

  func goToLogin()
  {
    // segue to the login view controller
    performSegue(.SwitchToAccountLogin, sender:self)
  }
}
</code>```

from UIViewController_Segues:

```<code>enum SegueIdentifier : String
{
  case LoserBoard             = "loserBoard"
  case CreateAccount          = "createAccount"
  case AccountLogin           = "accountLogin"
  case FacebookLogin          = "facebookLogin"
  case SwitchToFacebookLogin  = "switchToFacebookLogin"
  case SwitchToAccountLogin   = "switchToAccountLogin"
  case CreateAccountToStartup = "createAccountToStartup"
  case AccountLoginToStartup  = "accountLoginToStartup"
  case FacebookLoginToStartup = "facebookLoginToStartup"
  case UnwindToStartup        = "unwindToStartup"
}

extension UIViewController
{
  func performSegue(_ target:SegueIdentifier, sender:Any?)
  {
    performSegue(withIdentifier: target.rawValue, sender: sender)
  }
}
</code>```

from GameServerAlert.swift:

```<code>protocol GameServerAlertObserver
{
  func ok()
  func cancel()
  func goToLogin()
}

extension GameServerResponse
{
  func displayAlert(over controller:UIViewController, observer:GameServerAlertObserver? = nil)
  {
    var title   : String
    var message : String
    var actions : [UIAlertAction]

    switch self
    {
    // ... deleted cases/default which don't lead to segue ...

    case .UserAlreadyExists:
      title = "User already exists"
      message = "\nIf this is you, please use the login page to reconnect.\n\nIf this is not you, you will need to select a different username."
      actions = [
        UIAlertAction(title: "Go to Login page",   style: .default, handler: { _ in observer?.goToLogin() } ),
        UIAlertAction(title: "Enter new username", style: .default, handler: { _ in observer?.ok() } ),
        UIAlertAction(title: "Cancel",             style: .cancel,  handler: { _ in observer?.cancel() } )
      ]
    }

    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    actions.forEach { (action) in alert.addAction(action) }
    controller.present(alert,animated:true)
  }
}
</code>```

Examples from the simulator:

Create Account - (user enters username and password for new account here.)

Facebook Login

If user decides to use Facebook to log in rather than creating a user account, they are taken to this view (which I still haven't fleshed out).  Note that the "Save Password" action sheet has popped up.

User Exists Popup

If user attempts to create an account with a username that already exists, they will be presented with this popup.  If they select Cancel, they are taken back to the startup screen (see below).  If they select Enter new username, they are kept on the same screen with the username cleared out.  If they select Login, they are taken to the login screen.

Startup Screen

If the user selects Cancel above, they are brought back here.  Again, note that the "Save Password" action sheet has popped up.

答:
What I do to avoid the automatic Password saving action sheet when the user :

dismiss the login view controller ;

pop the view controller ;

use interactive pop gesture.

=>

```<code>  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
      passwordTextField.textContentType = .password
    }
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    if isMovingFromParent || isBeingDismissed || parent?.isBeingDismissed == true {
      passwordTextField.textContentType = nil
    }
  }
</code>```

Body:
My app has a "Create Account" view controller (shown below) that prompts the user to enter a username and password.  Whenever I segue to another view controller, I get a pop-up action sheet prompting to save the password in the keychain.

This is a nifty little freebie IF the user successfully creates the new account.  But I get this same pop-up if the user hits the cancel (back) button in the navigation bar, if they select the option to use Facebook login instead of creating an account, or any other means for leaving this view controller (see figures below).

How can I get this popup to ONLY show up when the user successfully creates a new account?

EDIT: Per request, here is the code that is related to the segues that result in the appearance of the "Save Password" action sheet.

from CreateAccountViewController.swift:

class CreateAccountViewController : UIViewController
{
  // ... bunch of irrelevant code deleted ...

  // bound to "Connect with Facebook" button (see image below)
  @IBAction func switchToFacebook(_ sender : UIButton)
  {
    performSegue(.SwitchToFacebookLogin, sender: sender)
  }
  // ... bunch of irrelevant code deleted ...
}

extension CreateAccountViewController : GameServerAlertObserver
{
  // callback based on response from GameCenter after
  //  submitting a "create new user" request
  func handleConnectionResponse(_ response:GameServerResponse )
  {
    switch response
    {
    // ... other response cases removed ...
    case .UserCreated:
      self.removeSpinner()
      performSegue(.CreateAccountToStartup, sender: self)

    default:
      response.displayAlert(over: self, observer: self)
      self.removeSpinner()
    }
  }

  // Functions defined in the GameServerAlertObserver protocol
  //   to handle user response to "User Exists Popup" (figure below)
  func ok()
  {
    // user chose to enter new  password... clear the existing username field
    usernameTextField.text = ""
  }

  func cancel()
  {
    // segue back to the startup view controller
    performSegue(.CreateAccountToStartup, sender: self)
  }

  func goToLogin()
  {
    // segue to the login view controller
    performSegue(.SwitchToAccountLogin, sender:self)
  }
}

from UIViewController_Segues:

enum SegueIdentifier : String
{
  case LoserBoard             = "loserBoard"
  case CreateAccount          = "createAccount"
  case AccountLogin           = "accountLogin"
  case FacebookLogin          = "facebookLogin"
  case SwitchToFacebookLogin  = "switchToFacebookLogin"
  case SwitchToAccountLogin   = "switchToAccountLogin"
  case CreateAccountToStartup = "createAccountToStartup"
  case AccountLoginToStartup  = "accountLoginToStartup"
  case FacebookLoginToStartup = "facebookLoginToStartup"
  case UnwindToStartup        = "unwindToStartup"
}

extension UIViewController
{
  func performSegue(_ target:SegueIdentifier, sender:Any?)
  {
    performSegue(withIdentifier: target.rawValue, sender: sender)
  }
}

from GameServerAlert.swift:

protocol GameServerAlertObserver
{
  func ok()
  func cancel()
  func goToLogin()
}

extension GameServerResponse
{
  func displayAlert(over controller:UIViewController, observer:GameServerAlertObserver? = nil)
  {
    var title   : String
    var message : String
    var actions : [UIAlertAction]

    switch self
    {
    // ... deleted cases/default which don't lead to segue ...

    case .UserAlreadyExists:
      title = "User already exists"
      message = "\nIf this is you, please use the login page to reconnect.\n\nIf this is not you, you will need to select a different username."
      actions = [
        UIAlertAction(title: "Go to Login page",   style: .default, handler: { _ in observer?.goToLogin() } ),
        UIAlertAction(title: "Enter new username", style: .default, handler: { _ in observer?.ok() } ),
        UIAlertAction(title: "Cancel",             style: .cancel,  handler: { _ in observer?.cancel() } )
      ]
    }

    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    actions.forEach { (action) in alert.addAction(action) }
    controller.present(alert,animated:true)
  }
}

Examples from the simulator:

Create Account - (user enters username and password for new account here.)

Facebook Login

If user decides to use Facebook to log in rather than creating a user account, they are taken to this view (which I still haven't fleshed out).  Note that the "Save Password" action sheet has popped up.

User Exists Popup

If user attempts to create an account with a username that already exists, they will be presented with this popup.  If they select Cancel, they are taken back to the startup screen (see below).  If they select Enter new username, they are kept on the same screen with the username cleared out.  If they select Login, they are taken to the login screen.

Startup Screen

If the user selects Cancel above, they are brought back here.  Again, note that the "Save Password" action sheet has popped up.

Body:
What I do to avoid the automatic Password saving action sheet when the user :

dismiss the login view controller ;

pop the view controller ;

use interactive pop gesture.

=>

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
      passwordTextField.textContentType = .password
    }
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    if isMovingFromParent || isBeingDismissed || parent?.isBeingDismissed == true {
      passwordTextField.textContentType = nil
    }
  }


来源: stackexchange

问:
variable visibility from calling function
I have 2 classes. In one class i have 4 variables. I instantiate another class and use methods which use these variables. I dont want to pass them as parameters. They are set to public. Both classes are in the default package with each other. heres my code:

```<code>public class c1 {
     public int x, y, x1, y1;
     public static void main(String args[]) {
          c1 a = new c1();
     }
     public c1() {
          c2 b = new c2();
          b.getSlope();
     }
}

public class c2 {
     public c2() {}
     public int getSlope() {
          return (y-y1)/(x-x1);
     }
}
</code>```

i get an error which says: cannot find symbol

答:
You instantiate objects (of a class). Your 'variables' are fields of that class. If the fields are not static (as in your code), they belong to the object and you have to pass the corresponding object to the method of the other class to access the fields.

So it should be

```<code>b.getSlope(a)
</code>```

when calling the method and the implementation has to have that argument

```<code> public int getSlope(c1 c) {
      return (c.y-c.y1)/(c.x-c.x1);
 }
</code>```

If you like to have the fields belong to the class, they have to be static.

(Note that in Java - by convention - class names should start with a Capital letter).

ContentLicense: CC BY-SA 4.0

Body:
I have 2 classes. In one class i have 4 variables. I instantiate another class and use methods which use these variables. I dont want to pass them as parameters. They are set to public. Both classes are in the default package with each other. heres my code:

public class c1 {
     public int x, y, x1, y1;
     public static void main(String args[]) {
          c1 a = new c1();
     }
     public c1() {
          c2 b = new c2();
          b.getSlope();
     }
}

public class c2 {
     public c2() {}
     public int getSlope() {
          return (y-y1)/(x-x1);
     }
}

i get an error which says: cannot find symbol

Body:
You instantiate objects (of a class). Your 'variables' are fields of that class. If the fields are not static (as in your code), they belong to the object and you have to pass the corresponding object to the method of the other class to access the fields.

So it should be

b.getSlope(a)

when calling the method and the implementation has to have that argument

 public int getSlope(c1 c) {
      return (c.y-c.y1)/(c.x-c.x1);
 }

If you like to have the fields belong to the class, they have to be static.

(Note that in Java - by convention - class names should start with a Capital letter).


问:
InternalViewResolver in spring boot is unable to find the view
I don't know I have tried multiple times but never really understood how the InternalViewResolver or any view resolver work under the hood. I have configured the view resolution using WebMvcConfigurer. like this one.

```<code>@Configuration
public class WebViewConfigurer implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/register").setViewName("registration");
    }
}
</code>```

I have put my html file registration.html in the location: src/main/resources/templates.

Whenever I try to access the page localhost:8080/register I get the whitelabel error page

```<code>There was an unexpected error (type=Not Found, status=404).
</code>```

I have configured view like this many times before and I have always faced problem in the beginning but I always get on top of it after some tweak and this time also I know I would get it. So the problem is not just how I solve my current problem but how can I stop this repetitive mistakes. Has any one faced these problems with ViewResolvers in spring or is it just me.

答:
How logical names are resolved in spring?

Logical names are resolved by DispatcherServelet. And is helped by various view Resolvers . One of which is Internal View Resolver which is a Url based View Resolver.

Follow the stack:

```<code>getResource:154, PathResourceResolver (org.springframework.web.servlet.resource)
resolveResourceInternal:137, PathResourceResolver (org.springframework.web.servlet.resource)
resolveResource:46, AbstractResourceResolver (org.springframework.web.servlet.resource)
resolveResource:75, DefaultResourceResolverChain (org.springframework.web.servlet.resource)
getResource:560, ResourceHttpRequestHandler (org.springframework.web.servlet.resource)
handleRequest:485, ResourceHttpRequestHandler (org.springframework.web.servlet.resource)
handle:53, HttpRequestHandlerAdapter (org.springframework.web.servlet.mvc)
doDispatch:1040, DispatcherServlet (org.springframework.web.servlet)
doService:943, DispatcherServlet (org.springframework.web.servlet)
processRequest:1006, FrameworkServlet (org.springframework.web.servlet)
doGet:898, FrameworkServlet (org.springframework.web.servlet)
service:634, HttpServlet (javax.servlet.http)
service:883, FrameworkServlet (org.springframework.web.servlet)
service:741, HttpServlet (javax.servlet.http)
internalDoFilter:231, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:53, WsFilter (org.apache.tomcat.websocket.server)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:113, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:113, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:113, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
invoke:712, ApplicationDispatcher (org.apache.catalina.core)
processRequest:459, ApplicationDispatcher (org.apache.catalina.core)
doForward:384, ApplicationDispatcher (org.apache.catalina.core)
forward:312, ApplicationDispatcher (org.apache.catalina.core)
renderMergedOutputModel:171, InternalResourceView (org.springframework.web.servlet.view)
render:316, AbstractView (org.springframework.web.servlet.view)
render:1373, DispatcherServlet (org.springframework.web.servlet)
processDispatchResult:1118, DispatcherServlet (org.springframework.web.servlet)
doDispatch:1057, DispatcherServlet (org.springframework.web.servlet)
doService:943, DispatcherServlet (org.springframework.web.servlet)
processRequest:1006, FrameworkServlet (org.springframework.web.servlet)
doGet:898, FrameworkServlet (org.springframework.web.servlet)
service:634, HttpServlet (javax.servlet.http)
service:883, FrameworkServlet (org.springframework.web.servlet)
service:741, HttpServlet (javax.servlet.http)
internalDoFilter:231, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:53, WsFilter (org.apache.tomcat.websocket.server)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilterInternal:100, RequestContextFilter (org.springframework.web.filter)
doFilter:119, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilterInternal:93, FormContentFilter (org.springframework.web.filter)
doFilter:119, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilterInternal:201, CharacterEncodingFilter (org.springframework.web.filter)
doFilter:119, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
invoke:202, StandardWrapperValve (org.apache.catalina.core)
invoke:96, StandardContextValve (org.apache.catalina.core)
invoke:541, AuthenticatorBase (org.apache.catalina.authenticator)
invoke:139, StandardHostValve (org.apache.catalina.core)
invoke:92, ErrorReportValve (org.apache.catalina.valves)
invoke:74, StandardEngineValve (org.apache.catalina.core)
service:343, CoyoteAdapter (org.apache.catalina.connector)
service:373, Http11Processor (org.apache.coyote.http11)
process:65, AbstractProcessorLight (org.apache.coyote)
process:868, AbstractProtocol$ConnectionHandler (org.apache.coyote)
doRun:1590, NioEndpoint$SocketProcessor (org.apache.tomcat.util.net)
run:49, SocketProcessorBase (org.apache.tomcat.util.net)
runWorker:1149, ThreadPoolExecutor (java.util.concurrent)
run:624, ThreadPoolExecutor$Worker (java.util.concurrent)
run:61, TaskThread$WrappingRunnable (org.apache.tomcat.util.threads)
run:748, Thread (java.lang)
</code>```

PathResourceResolver has a resource variable passed by ResourceHttpRequestHandler which tries to resolve the resource . The resource could be of different types like: ClasspathResource or ServletContextResource.

You can debug the PathResourceResolver.getResource() method to find if in case your resource is not resolved.

Body:
I don't know I have tried multiple times but never really understood how the InternalViewResolver or any view resolver work under the hood. I have configured the view resolution using WebMvcConfigurer. like this one.

@Configuration
public class WebViewConfigurer implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/register").setViewName("registration");
    }
}

I have put my html file registration.html in the location: src/main/resources/templates.

Whenever I try to access the page localhost:8080/register I get the whitelabel error page

There was an unexpected error (type=Not Found, status=404).

I have configured view like this many times before and I have always faced problem in the beginning but I always get on top of it after some tweak and this time also I know I would get it. So the problem is not just how I solve my current problem but how can I stop this repetitive mistakes. Has any one faced these problems with ViewResolvers in spring or is it just me.

Body:
How logical names are resolved in spring?

Logical names are resolved by DispatcherServelet. And is helped by various view Resolvers . One of which is Internal View Resolver which is a Url based View Resolver.

Follow the stack:

getResource:154, PathResourceResolver (org.springframework.web.servlet.resource)
resolveResourceInternal:137, PathResourceResolver (org.springframework.web.servlet.resource)
resolveResource:46, AbstractResourceResolver (org.springframework.web.servlet.resource)
resolveResource:75, DefaultResourceResolverChain (org.springframework.web.servlet.resource)
getResource:560, ResourceHttpRequestHandler (org.springframework.web.servlet.resource)
handleRequest:485, ResourceHttpRequestHandler (org.springframework.web.servlet.resource)
handle:53, HttpRequestHandlerAdapter (org.springframework.web.servlet.mvc)
doDispatch:1040, DispatcherServlet (org.springframework.web.servlet)
doService:943, DispatcherServlet (org.springframework.web.servlet)
processRequest:1006, FrameworkServlet (org.springframework.web.servlet)
doGet:898, FrameworkServlet (org.springframework.web.servlet)
service:634, HttpServlet (javax.servlet.http)
service:883, FrameworkServlet (org.springframework.web.servlet)
service:741, HttpServlet (javax.servlet.http)
internalDoFilter:231, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:53, WsFilter (org.apache.tomcat.websocket.server)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:113, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:113, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:113, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
invoke:712, ApplicationDispatcher (org.apache.catalina.core)
processRequest:459, ApplicationDispatcher (org.apache.catalina.core)
doForward:384, ApplicationDispatcher (org.apache.catalina.core)
forward:312, ApplicationDispatcher (org.apache.catalina.core)
renderMergedOutputModel:171, InternalResourceView (org.springframework.web.servlet.view)
render:316, AbstractView (org.springframework.web.servlet.view)
render:1373, DispatcherServlet (org.springframework.web.servlet)
processDispatchResult:1118, DispatcherServlet (org.springframework.web.servlet)
doDispatch:1057, DispatcherServlet (org.springframework.web.servlet)
doService:943, DispatcherServlet (org.springframework.web.servlet)
processRequest:1006, FrameworkServlet (org.springframework.web.servlet)
doGet:898, FrameworkServlet (org.springframework.web.servlet)
service:634, HttpServlet (javax.servlet.http)
service:883, FrameworkServlet (org.springframework.web.servlet)
service:741, HttpServlet (javax.servlet.http)
internalDoFilter:231, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:53, WsFilter (org.apache.tomcat.websocket.server)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilterInternal:100, RequestContextFilter (org.springframework.web.filter)
doFilter:119, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilterInternal:93, FormContentFilter (org.springframework.web.filter)
doFilter:119, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilterInternal:201, CharacterEncodingFilter (org.springframework.web.filter)
doFilter:119, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
invoke:202, StandardWrapperValve (org.apache.catalina.core)
invoke:96, StandardContextValve (org.apache.catalina.core)
invoke:541, AuthenticatorBase (org.apache.catalina.authenticator)
invoke:139, StandardHostValve (org.apache.catalina.core)
invoke:92, ErrorReportValve (org.apache.catalina.valves)
invoke:74, StandardEngineValve (org.apache.catalina.core)
service:343, CoyoteAdapter (org.apache.catalina.connector)
service:373, Http11Processor (org.apache.coyote.http11)
process:65, AbstractProcessorLight (org.apache.coyote)
process:868, AbstractProtocol$ConnectionHandler (org.apache.coyote)
doRun:1590, NioEndpoint$SocketProcessor (org.apache.tomcat.util.net)
run:49, SocketProcessorBase (org.apache.tomcat.util.net)
runWorker:1149, ThreadPoolExecutor (java.util.concurrent)
run:624, ThreadPoolExecutor$Worker (java.util.concurrent)
run:61, TaskThread$WrappingRunnable (org.apache.tomcat.util.threads)
run:748, Thread (java.lang)

PathResourceResolver has a resource variable passed by ResourceHttpRequestHandler which tries to resolve the resource . The resource could be of different types like: ClasspathResource or ServletContextResource.

You can debug the PathResourceResolver.getResource() method to find if in case your resource is not resolved.


问:
Printing out values of different rows and column in 2d array using for loops
I have this 2d array of the first row being first names and the second being last names.

String[][] ladrones2 = {
        {"Phil", "Kim", "Phil", "Perry"},
        {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};
```
<p>the prefered out come of this would be to have them printend out like e.g</p>
```Phill Garcia
Kim Gimena
etc...
```
<p>Now I was able to do this by catching the ArrayIndexOutOfBoundsException exception and it works and the output is:</p>
```name Phil Garcia
name Kim Gimena
name Phil Basinger
name Perry Ornitorrinco
```
<p>Which is great but I wondered if there was a way to do this without having to catch the exception? I've been searching to make this cleaner but wasn't able to do so.</p>
<p>Code at the moment:</p>
<pre class="lang-java prettyprint-override"><code>public static void robo2() {
    String[][] ladrones2 = {
            {"Phil", "Kim", "Phil", "Perry"},
            {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

    try {
        for (int i = 0; i < ladrones2.length; i++) {
            for (int j = 0; j < ladrones2[i].length; j++) {
                System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("");
    }
}
</code>```

as you can see I used in the inner for loop a +1 on the i variable which in turn throws the exception.

Any ideas? I would like just to keep this way of working at the moment with 2 forloops due to being new to Java.

答:
On this line :

```<code>System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
</code>```

You are taking an element from the first and second array at the same time but you are looping over all the elements in the sequence on this line :

```<code>for (int i = 0; i < ladrones2.length; i++)
</code>```

To correct this problem, you simply have to reduce the range of i to ladrones.length-1, otherwise you will reach the end of the array and try to access the next element which doesn't exist here.

You'll end up with this line instead :

```<code>for (int i = 0; i < ladrones2.length-1; i++) {
</code>```

Body:
I have this 2d array of the first row being first names and the second being last names.

String[][] ladrones2 = {
        {"Phil", "Kim", "Phil", "Perry"},
        {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

the prefered out come of this would be to have them printend out like e.g

Phill Garcia
Kim Gimena
etc...

Now I was able to do this by catching the ArrayIndexOutOfBoundsException exception and it works and the output is:

name Phil Garcia
name Kim Gimena
name Phil Basinger
name Perry Ornitorrinco

Which is great but I wondered if there was a way to do this without having to catch the exception? I've been searching to make this cleaner but wasn't able to do so.

Code at the moment:

public static void robo2() {
    String[][] ladrones2 = {
            {"Phil", "Kim", "Phil", "Perry"},
            {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

    try {
        for (int i = 0; i < ladrones2.length; i++) {
            for (int j = 0; j < ladrones2[i].length; j++) {
                System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("");
    }
}

as you can see I used in the inner for loop a +1 on the i variable which in turn throws the exception.

Any ideas? I would like just to keep this way of working at the moment with 2 forloops due to being new to Java.

Body:
On this line :

System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);

You are taking an element from the first and second array at the same time but you are looping over all the elements in the sequence on this line :

for (int i = 0; i < ladrones2.length; i++)

To correct this problem, you simply have to reduce the range of i to ladrones.length-1, otherwise you will reach the end of the array and try to access the next element which doesn't exist here.

You'll end up with this line instead :

for (int i = 0; i < ladrones2.length-1; i++) {


问:
Horizontal Row View : A RenderFlex overflowed by 66 pixels on the right
I put ListView to show tabs scrolling horizontally, but the problem is that they are displayed in the middle of screen and I want it to be shown at the top of screen.

Is there any way to solve this and show this list at top of screen?

Here is how I did it:

```<code>      body: Container(
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
            itemCount: 1,
            itemBuilder: (BuildContext context, int index){
            return  Row(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'All',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Cars',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Buildings',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Assorted Devices',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
              ],
            );
          }),
      ),
    );
</code>```

答:
You don't need Container, ListView.builder and Row, simply use:

```<code>ListView(
  scrollDirection: Axis.horizontal,
  children: [
    _buildInkWell('All'),
    _buildInkWell('Cars'),
    _buildInkWell('Building'),
    _buildInkWell('Assorted Devices'),
  ],
)

Widget _buildInkWell(String text) {
  return Padding(
    padding: const EdgeInsets.only(
      left: 20.0,
      right: 20,
      top: 10,
    ),
    child: InkWell(
      child: Text(
        text,
        style: TextStyle(fontSize: 20, color: Colors.grey),
      ),
    ),
  );
}
</code>```

Body:
I put ListView to show tabs scrolling horizontally, but the problem is that they are displayed in the middle of screen and I want it to be shown at the top of screen.

Is there any way to solve this and show this list at top of screen?

Here is how I did it:

      body: Container(
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
            itemCount: 1,
            itemBuilder: (BuildContext context, int index){
            return  Row(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'All',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Cars',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Buildings',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Assorted Devices',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
              ],
            );
          }),
      ),
    );

Body:
You don't need Container, ListView.builder and Row, simply use:

ListView(
  scrollDirection: Axis.horizontal,
  children: [
    _buildInkWell('All'),
    _buildInkWell('Cars'),
    _buildInkWell('Building'),
    _buildInkWell('Assorted Devices'),
  ],
)

Widget _buildInkWell(String text) {
  return Padding(
    padding: const EdgeInsets.only(
      left: 20.0,
      right: 20,
      top: 10,
    ),
    child: InkWell(
      child: Text(
        text,
        style: TextStyle(fontSize: 20, color: Colors.grey),
      ),
    ),
  );
}


问:
How do i align react-native buttons in a horizontal row
I have 8 buttons which i would like to align in  horizontal row, side by side. everything i have tried hasn't worked and the just display one on top of another.

Here's what i have at the mo.
Thanks

```<code>               categories: ['art', 'funny', 'inspire', 'life', 'love', 'management', 'sports', 'students'],

render() {
let cat = this.state.categories.map((value, key) => {
                return (
                     <View style={styles.catButtons}>
                          <TouchableOpacity
                               style={styles.buttonContainer}
                               key={key}
                               activeOpacity={0.7}
                          >
                               <Button style={styles.button}
                                    color={'darkslategrey'}
                                    key={key}
                                    title={value}
                                    onPress={() => { this.getCategoryQuote(value) }}
                               />
                          </TouchableOpacity>
                     </View>
                )
           })
           return (
                <View>
                     {cat}
                </View>
           )
}
const styles = StyleSheet.create({

 catButtons: {
      flexWrap: 'wrap'
 },
 buttonContainer: {
         width: 125,
          margin: 10
     },
});
</code>```

答:
I think, in this case, the flex items are the buttons. But the problems lies in the flex container: TouchableOpacity.

As your code suggest, there is one flex container for one button, and that is repeated by the map function.

It should be one flex container for all flex items (buttons). That means, the flex container should be outside of your map function and the items directly as its children (that are mapped by the map function).

Body:
I have 8 buttons which i would like to align in  horizontal row, side by side. everything i have tried hasn't worked and the just display one on top of another.

Here's what i have at the mo.
Thanks

               categories: ['art', 'funny', 'inspire', 'life', 'love', 'management', 'sports', 'students'],

render() {
let cat = this.state.categories.map((value, key) => {
                return (
                     <View style={styles.catButtons}>
                          <TouchableOpacity
                               style={styles.buttonContainer}
                               key={key}
                               activeOpacity={0.7}
                          >
                               <Button style={styles.button}
                                    color={'darkslategrey'}
                                    key={key}
                                    title={value}
                                    onPress={() => { this.getCategoryQuote(value) }}
                               />
                          </TouchableOpacity>
                     </View>
                )
           })
           return (
                <View>
                     {cat}
                </View>
           )
}
const styles = StyleSheet.create({

 catButtons: {
      flexWrap: 'wrap'
 },
 buttonContainer: {
         width: 125,
          margin: 10
     },
});


问:
State machine workflow in VS 2010
I have a simple web application (non sharepoint) in which i want to add window workflow. I am using VS 2010 (.Net 4.0). I have done that in VS 2008 but dont know how to create a state machine workflow in VS 2010. The only option i get in creating are
1. Activity Designer
2. Activity Library
3. WCF Worflow
4. Console

I want that workflow application to be added in my solution so that i can integrate it. Any idea or tutorial would be of great help

答:
The .Net 4.0 product update 1 has state machine. Check the below link

http://support.microsoft.com/kb/2478063

ContentLicense: CC BY-SA 2.5

Title: State machine workflow in VS 2010

ContentLicense: CC BY-SA 3.0


问:
How to pass template arguments via constructor?
I'm looking for a way to pass the template arguments of a template-based class (the main class of the FastLED library on Arduino, to be specific) via the constructor of my own class (which should basically wrap the FastLED library). I want to specify the template arguments necessary to initialize FastLED in the main function, so that all pre-configuration before compiling (i.e. the #defines in the third code block below) works via constants in the main file. How can I achieve this?

Currently, my class looks like this:

LEDState.h:

```<code>#pragma once
#include "FastLED.h"
FASTLED_USING_NAMESPACE

class LEDState {
  private:
    CRGB* _leds;
    CRGB* _pixels;
    const uint16_t _pixel_count;
    const uint16_t _led_count;
    const uint8_t _mapmode;

  public:
    LEDState(const uint16_t pixel_count, const uint8_t mapmode);
    void show();
};
</code>```

LEDState.cpp:

```<code>#include "LEDState.h"

LEDState::LEDState(const uint16_t pixel_count, const uint8_t mapmode)
: _pixel_count(pixel_count), _mapmode(mapmode), _led_count(_pixel_count * (_mapmode & 0x0f))
{
  _leds = (CRGB*)malloc(_led_count * sizeof(CRGB));
  _pixels = (CRGB*)malloc(_pixel_count * sizeof(CRGB));
  FastLED.addLeds<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER>(_leds, _led_count);
}

void LEDState::show() {
  for( int p = 0; p < _pixel_count; p++ ) {
    _leds[p] = _pixels[p];
  }
  FastLED.show();
}
</code>```

My problem is that I did not find a way to pass the template arguments <CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER> via the constructor of LEDState.

Is there a way to initialize my wrapper class and the wrapped FastLED library from my main file? I'm imagining my main.ino file like this:

```<code>#include "LEDState.h"

#define CHIPSET APA102
#define DATA_PIN 23
#define CLOCK_PIN 18
#define COLOR_ORDER GRB

LEDState state = LEDState<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER>(led_count, map_mode);

void setup() {
}

void loop() {
  LEDState.show();
}
</code>```

(with APA102 and GRB being constants from the FastLED library.)

Is something like this possible at all?

(I'm not confident that I know the right vocabulary to search for a solution, leave alone using the right terminology in this question. Everything I found either wasn't a solution to my problem or I didn't understand that it was a solution. I'm coming from "plain Arduino C"; and my knowledge about C++ templates is roughly at: I can work my way through patching existing template code, but I don't know how to create a template.)

EDIT: With the comments and first answers, I guess that I need my class to also be templated. I tried copying the template argument list from the FastLED library (see link above), resulting in this class definition:

```<code>template<ESPIChipsets CHIPSET, uint8_t DATA_PIN, uint8_t CLOCK_PIN, EOrder COLOR_ORDER>
class LEDState {
  ...
}
</code>```

(ESPIChipsets and EOrder are defined by FastLED)

Now the compiler complains with

```<code>LEDState.cpp:3:1: error: invalid use of template-name 'LEDState' without an argument list
 LEDState::LEDState(const uint16_t pixel_count, const uint8_t mapmode)
 ^
</code>```

What else do I need to make it compile?

答:
I suggest you look into the FastLED implementation, it is written exactly how you want to use your wrapper class. I am missing some libraries so I cannot tell if everything compiles, but the solution must be close to this</p>

```<code>template <ESPIChipsets chipset, uint8_t data_pin, uint8_t clock_pin, EOrder rgb_order = RGB>
class LEDState {
private:
  std::unique_ptr<CRGB[]> _leds;
  std::unique_ptr<CRGB[]> _pixels;
  const uint16_t _pixel_count = 0;
  const uint16_t _led_count = 0;
  const uint8_t _mapmode = 0;

public:
  LEDState(const uint16_t pixel_count, const uint8_t mapmode)
    : _pixel_count(pixel_count), _mapmode(mapmode), _led_count(_pixel_count* (_mapmode & 0x0f))
  {
    if (_pixel_count > 0)
    {
      _leds = std::make_unique(new CRGB[_led_count]);
      _pixels = std::make_unique(new CRGB[_pixel_count]);
      FastLED.addLeds<chipset, data_pin, clock_pin, rgb_order>(_leds, _led_count, RGB_ORDER);
    }
  }
  void show() {
  }
};

#define CHIPSET APA102
#define DATA_PIN 23
#define CLOCK_PIN 18
#define COLOR_ORDER GRB

int main()
{
  const uint16_t pixel_count = 3;
  const uint8_t map_mode = 0;
  LEDState<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER> state(pixel_count, map_mode);
}
</code>```

Body:
I'm looking for a way to pass the template arguments of a template-based class (the main class of the FastLED library on Arduino, to be specific) via the constructor of my own class (which should basically wrap the FastLED library). I want to specify the template arguments necessary to initialize FastLED in the main function, so that all pre-configuration before compiling (i.e. the #defines in the third code block below) works via constants in the main file. How can I achieve this?

Currently, my class looks like this:

LEDState.h:

#pragma once
#include "FastLED.h"
FASTLED_USING_NAMESPACE

class LEDState {
  private:
    CRGB* _leds;
    CRGB* _pixels;
    const uint16_t _pixel_count;
    const uint16_t _led_count;
    const uint8_t _mapmode;

  public:
    LEDState(const uint16_t pixel_count, const uint8_t mapmode);
    void show();
};

LEDState.cpp:

#include "LEDState.h"

LEDState::LEDState(const uint16_t pixel_count, const uint8_t mapmode)
: _pixel_count(pixel_count), _mapmode(mapmode), _led_count(_pixel_count * (_mapmode & 0x0f))
{
  _leds = (CRGB*)malloc(_led_count * sizeof(CRGB));
  _pixels = (CRGB*)malloc(_pixel_count * sizeof(CRGB));
  FastLED.addLeds<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER>(_leds, _led_count);
}

void LEDState::show() {
  for( int p = 0; p < _pixel_count; p++ ) {
    _leds[p] = _pixels[p];
  }
  FastLED.show();
}

My problem is that I did not find a way to pass the template arguments <CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER> via the constructor of LEDState.

Is there a way to initialize my wrapper class and the wrapped FastLED library from my main file? I'm imagining my main.ino file like this:

#include "LEDState.h"

#define CHIPSET APA102
#define DATA_PIN 23
#define CLOCK_PIN 18
#define COLOR_ORDER GRB

LEDState state = LEDState<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER>(led_count, map_mode);

void setup() {
}

void loop() {
  LEDState.show();
}

(with APA102 and GRB being constants from the FastLED library.)

Is something like this possible at all?

(I'm not confident that I know the right vocabulary to search for a solution, leave alone using the right terminology in this question. Everything I found either wasn't a solution to my problem or I didn't understand that it was a solution. I'm coming from "plain Arduino C"; and my knowledge about C++ templates is roughly at: I can work my way through patching existing template code, but I don't know how to create a template.)

EDIT: With the comments and first answers, I guess that I need my class to also be templated. I tried copying the template argument list from the FastLED library (see link above), resulting in this class definition:

template<ESPIChipsets CHIPSET, uint8_t DATA_PIN, uint8_t CLOCK_PIN, EOrder COLOR_ORDER>
class LEDState {
  ...
}

(ESPIChipsets and EOrder are defined by FastLED)

Now the compiler complains with

LEDState.cpp:3:1: error: invalid use of template-name 'LEDState' without an argument list
 LEDState::LEDState(const uint16_t pixel_count, const uint8_t mapmode)
 ^

What else do I need to make it compile?

Body:
I suggest you look into the FastLED implementation, it is written exactly how you want to use your wrapper class. I am missing some libraries so I cannot tell if everything compiles, but the solution must be close to this

template <ESPIChipsets chipset, uint8_t data_pin, uint8_t clock_pin, EOrder rgb_order = RGB>
class LEDState {
private:
  std::unique_ptr<CRGB[]> _leds;
  std::unique_ptr<CRGB[]> _pixels;
  const uint16_t _pixel_count = 0;
  const uint16_t _led_count = 0;
  const uint8_t _mapmode = 0;

public:
  LEDState(const uint16_t pixel_count, const uint8_t mapmode)
    : _pixel_count(pixel_count), _mapmode(mapmode), _led_count(_pixel_count* (_mapmode & 0x0f))
  {
    if (_pixel_count > 0)
    {
      _leds = std::make_unique(new CRGB[_led_count]);
      _pixels = std::make_unique(new CRGB[_pixel_count]);
      FastLED.addLeds<chipset, data_pin, clock_pin, rgb_order>(_leds, _led_count, RGB_ORDER);
    }
  }
  void show() {
  }
};

#define CHIPSET APA102
#define DATA_PIN 23
#define CLOCK_PIN 18
#define COLOR_ORDER GRB

int main()
{
  const uint16_t pixel_count = 3;
  const uint8_t map_mode = 0;
  LEDState<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER> state(pixel_count, map_mode);
}


问:
Pie chart with non labelled data?
How can I produce a pie chart when the data is not labelled as usual? See the example  dataframe below:

```<code>             First_Half Second_Half
Div
Bundesliga      0.438       0.562
EPL             0.434       0.566
La Liga         0.441       0.559

</code>```

This just shows the proportion of first half goals vs second half goals for the divisions listed. I want to create a separate pie chart for each division with the proportion of First Half vs Second Half goals, how do I do this with this data?

答:
You can do something like this:

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"Bundesliga":[0.438, 0.562],
                  "EPL": [0.434, 0.566],
                  "La Liga": [0.441, 0.559]}, index=["1st_Half", "2nd_Half"])

df.plot.pie(subplots=True, , figsize=(10, 5), legend=False,
            title="Goals Ratio between first and second halves")
plt.show()
</code>```

which will produce this graph:

Title: Pie chart with non labelled data?

Body:
How can I produce a pie chart when the data is not labelled as usual? See the example  dataframe below:

             First_Half Second_Half
Div
Bundesliga      0.438       0.562
EPL             0.434       0.566
La Liga         0.441       0.559

This just shows the proportion of first half goals vs second half goals for the divisions listed. I want to create a separate pie chart for each division with the proportion of First Half vs Second Half goals, how do I do this with this data?

Body:
You can do something like this:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"Bundesliga":[0.438, 0.562],
                  "EPL": [0.434, 0.566],
                  "La Liga": [0.441, 0.559]}, index=["1st_Half", "2nd_Half"])

df.plot.pie(subplots=True, , figsize=(10, 5), legend=False,
            title="Goals Ratio between first and second halves")
plt.show()

which will produce this graph:


问:
How to migrate applications from Classic ASP to ASP.NET MVC?
Currently, we have many web applications (external & internal) developed using Classic ASP through .NET 2.0 technologies. Each of those web applications have their own login screen authenticating against their own custom database or using Windows authentication. Users have access to one or more of these applications, meaning they have to log out and log back into applications that they would like to access. All applications share some part of the back-end data sources. Also, the business logic is embedded in the UI in addition to being duplicated across applications because there is no code/business logic sharing.  Screenshot #1 gives a brief idea of the existing architecture.

Screenshot #2 shows the suggested architecture, which I hope will help in faster development, code/business re-usability and may be simpler maintenance. Users will access either external or internal url. In external, users will provide credentials and will be authenticated against custom database. In internal site, users will be automatically logged in using Windows authentication. After creating some samples, I have begun to like ASP.NET MVC 3. It keeps business logic separate from UI and I also like the unit testing capabilities.

Here are my questions:

Based on what I have found on the web so far, multiple authentications are not feasible within a single website. My understanding is that I have to host one website for each type of authentication (Forms and Windows). How do I redirect users to common landing page after they are authenticated so they can see the modules (links/menus) that they are authorized to access? Should I have to publish the same code set (dlls and content) to both the websites?

Has anyone faced a similar architecture problem? If yes, could you please share the challenges that you faced and how you tackled them? What are the industry standards in designing applications of this sort?

Does the suggested architecture make any sense or is it a really bad design? Are there any drawbacks in doing this in ASP.NET MVC 3?

I would really appreciate your inputs.

Thanks in advance.

答: Keep in mind the difference between Authentication and Authorization.  You presumably want a single authentication mechanism (or maybe two, one for internal and one for external users).  There is a similar post here that lays out some pretty good guidelines: How to allow multiple authentication methods in ASP.NET?</p>


问:
using Django crispy forms, how do you shrink the text box for a TextField?
The text boxes that crispy forms lay out for TextField columns are too tall for my app, they are taking up too much screen space.  The user can make them taller if desired by dragging the bottom frame line, but the minimum size is too tall.  I would like the default height to be 4 rows or so.

I tried some ideas I got off related posts, but nothing  worked -- the text boxes were still the same height and too tall.

Here is the model I am working on at the moment:

```<code>class Brand(models.Model):
    cTitle          = models.CharField(
                        'brand name', max_length = 48, db_index = True)
    bWanted         = models.BooleanField(
                        'want anything from this brand?', default = True )
    bAllOfInterest  = models.BooleanField(
                        'want everything from this brand?', default = True )
    cLookFor        = models.TextField(
                        'Considered a hit if this text is found '
                        '(each line evaluated separately, '
                        'put different look for tests on different lines)',
                        null=True, blank = True )
    iStars          = IntegerRangeField(
                        'desireability, 10 star brand is most desireable',
                        min_value = 0, max_value = 10, default = 5 )
    cComment        = models.TextField( 'comments', null = True, blank = True )
    cNationality    = CountryField( "nationality", null = True )
    cExcludeIf      = models.TextField(
                        'Not a hit if this text is found '
                        '(each line evaluated separately, '
                        'put different exclude tests on different lines)',
                        null=True, blank = True )
    iLegacyKey      = models.PositiveIntegerField('legacy key', null = True )
    tLegacyCreate   = models.DateTimeField( 'legacy row created on',
                        null=True, blank = True )
    tLegacyModify   = models.DateTimeField( 'legacy row updated on',
                        null=True, blank = True )
    iUser           = models.ForeignKey( User, verbose_name = 'Owner',
                        on_delete=models.CASCADE )
    tCreate         = models.DateTimeField( 'created on', auto_now_add= True )
    tModify         = models.DateTimeField( 'updated on', auto_now    = True )
    #

    def __str__(self):
        return self.cTitle

    class Meta():
        verbose_name_plural = 'brands'
        ordering            = ('cTitle',)
        db_table            = verbose_name_plural
</code>```

But only these fields are on the form:

```<code>tModelFields = (
    'cTitle',
    'bWanted',
    'bAllOfInterest',
    'cLookFor',
    'iStars',
    'cComment',
    'cNationality',
    'cExcludeIf' )
</code>```

Guidance would be appreciated.

答:
Change

```<code>cExcludeIf      = models.TextField(
                    'Not a hit if this text is found '
                    '(each line evaluated separately, '
                    'put different exclude tests on different lines)',
                    null=True, blank = True )
</code>```

to

```<code>cExcludeIf      = models.forms.CharField(
                    'Not a hit if this text is found '
                    '(each line evaluated separately, '
                    'put different exclude tests on different lines)',
                    null=True, blank = True,
                    widget = forms.Textarea(attrs={
                                        'rows': 2})) )
</code>```

Body:
The text boxes that crispy forms lay out for TextField columns are too tall for my app, they are taking up too much screen space.  The user can make them taller if desired by dragging the bottom frame line, but the minimum size is too tall.  I would like the default height to be 4 rows or so.

I tried some ideas I got off related posts, but nothing  worked -- the text boxes were still the same height and too tall.

Here is the model I am working on at the moment:

class Brand(models.Model):
    cTitle          = models.CharField(
                        'brand name', max_length = 48, db_index = True)
    bWanted         = models.BooleanField(
                        'want anything from this brand?', default = True )
    bAllOfInterest  = models.BooleanField(
                        'want everything from this brand?', default = True )
    cLookFor        = models.TextField(
                        'Considered a hit if this text is found '
                        '(each line evaluated separately, '
                        'put different look for tests on different lines)',
                        null=True, blank = True )
    iStars          = IntegerRangeField(
                        'desireability, 10 star brand is most desireable',
                        min_value = 0, max_value = 10, default = 5 )
    cComment        = models.TextField( 'comments', null = True, blank = True )
    cNationality    = CountryField( "nationality", null = True )
    cExcludeIf      = models.TextField(
                        'Not a hit if this text is found '
                        '(each line evaluated separately, '
                        'put different exclude tests on different lines)',
                        null=True, blank = True )
    iLegacyKey      = models.PositiveIntegerField('legacy key', null = True )
    tLegacyCreate   = models.DateTimeField( 'legacy row created on',
                        null=True, blank = True )
    tLegacyModify   = models.DateTimeField( 'legacy row updated on',
                        null=True, blank = True )
    iUser           = models.ForeignKey( User, verbose_name = 'Owner',
                        on_delete=models.CASCADE )
    tCreate         = models.DateTimeField( 'created on', auto_now_add= True )
    tModify         = models.DateTimeField( 'updated on', auto_now    = True )
    #

    def __str__(self):
        return self.cTitle

    class Meta():
        verbose_name_plural = 'brands'
        ordering            = ('cTitle',)
        db_table            = verbose_name_plural

But only these fields are on the form:

tModelFields = (
    'cTitle',
    'bWanted',
    'bAllOfInterest',
    'cLookFor',
    'iStars',
    'cComment',
    'cNationality',
    'cExcludeIf' )

Guidance would be appreciated.

Body:
Change

cExcludeIf      = models.TextField(
                    'Not a hit if this text is found '
                    '(each line evaluated separately, '
                    'put different exclude tests on different lines)',
                    null=True, blank = True )

to

cExcludeIf      = models.forms.CharField(
                    'Not a hit if this text is found '
                    '(each line evaluated separately, '
                    'put different exclude tests on different lines)',
                    null=True, blank = True,
                    widget = forms.Textarea(attrs={
                                        'rows': 2})) )


问:
How to get the output of javap to multiple text files
I know this is a simple question but I am quite new to programming and I want to know if there is a way to get the output of a javap file to multiple different named text files. Eg. In the case of one output file it would be javap -c abc.class > nameOfTheFileYouWant.txt what about in the event that where I want it to output more than one uniquely named text file.</p>

答:
If you are using bash, then you can use tee command as shown below

```<code>javap -c abc.class | tee file1.txt file2.txt file3.txt
</code>```

In this specific example same output will be written to three files file1.txt, file2.txt and file3.txt

Body:
If you are using bash, then you can use tee command as shown below

javap -c abc.class | tee file1.txt file2.txt file3.txt

In this specific example same output will be written to three files file1.txt, file2.txt and file3.txt


问:
Postgresql function has unsupported return type
I got an error while trying to update specific column values in my table

ERROR:  function "my_function" in FROM has unsupported return type trigger

I tried to run the update script manually but it gave me an error to write an after trigger because the database is being used in production. Basically what i want to do is to update one table columns values from another table and i named that table as "table_name_temp".
The script to me looks fine but I am not sure what exact the problem could be with it because the error response seems to be very opaque.

```<code> Create or REPLACE FUNCTION my_function() RETURNS TRIGGER AS $$
      BEGIN
    update schema_name.table_name set category = schema_name.table_name_temp.category
        FROM schema_name.table_name_temp
        WHERE (some where clauses for first check)
        and schema_name.table_name.name = schema_name.table_name_temp.name
        returning null;
      END;
   $$ LANGUAGE plpgsql;

 DROP TRIGGER IF EXISTS trigger_name on schema_name.table_name;

   CREATE TRIGGER trigger_name AFTER UPDATE ON schema_name.table_name
    FOR EACH ROW EXECUTE PROCEDURE my_function();

select * from my_function();
</code>```

答:
You can't call a trigger function directly, it has to be called by the trigger.

Usually, trigger functions contains a NEW and and OLD record. These variables are set by the trigger and are readily available in the trigger function. If you call the trigger function directly, nothing is setting these values.

To use the same piece of code from a trigger and from a query, it has to be in a separate function:

CREATE or REPLACE FUNCTION my_function_that_do_something() RETURNS VOID AS $$
      BEGIN
          update ...;  --no need to return anything
      END;
   $$ LANGUAGE plpgsql;

CREATE or REPLACE FUNCTION my_trigger_function() RETURNS TRIGGER AS $$
      BEGIN
          PERFORM my_function_that_do_something();
          return null;
      END;
   $$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_name AFTER UPDATE ON schema_name.table_name
    FOR EACH ROW EXECUTE PROCEDURE my_trigger_function();

SELECT my_function_that_do_something();
```

Body:
I got an error while trying to update specific column values in my table

ERROR:  function "my_function" in FROM has unsupported return type trigger

I tried to run the update script manually but it gave me an error to write an after trigger because the database is being used in production. Basically what i want to do is to update one table columns values from another table and i named that table as "table_name_temp".
The script to me looks fine but I am not sure what exact the problem could be with it because the error response seems to be very opaque.

 Create or REPLACE FUNCTION my_function() RETURNS TRIGGER AS $$
      BEGIN
    update schema_name.table_name set category = schema_name.table_name_temp.category
        FROM schema_name.table_name_temp
        WHERE (some where clauses for first check)
        and schema_name.table_name.name = schema_name.table_name_temp.name
        returning null;
      END;
   $$ LANGUAGE plpgsql;

 DROP TRIGGER IF EXISTS trigger_name on schema_name.table_name;

   CREATE TRIGGER trigger_name AFTER UPDATE ON schema_name.table_name
    FOR EACH ROW EXECUTE PROCEDURE my_function();

select * from my_function();


问:
Python/Pandas newbie - Extract value within column with semi-consistant value to another column
Apologise if I don't make sense in advance as I'm still working out 100% of the terminology, but am pretty good at Excel and am on my Python/Numpy journey.

Currently working with CSVs out of what I would compare to an IT Ticket system which has various columns which are fairly consistent to groupby, that part I'm ok with.

One column, in particular, is free-text to explain the issue but users may include a Error code; in this example, we will say its format is always in the format of "ERR#####" Aka ERR54321. "ERR" being the constant and always followed by 5 numerals.

Is there a best method / way to somehow extract that particular value and then create it into its own column in the dataframe for that row?

Goal is to be able to do this so I can quantify the volume/frequency of the errors being provided.

Thanks in Advance!

答:
You can use the power of regular expression on the dataframe:

```<code>import pandas as pd

# prepare demo df
data = ["got ERR12345 today", "ERR 0815", "to ERR or not to ERR", "no ERR11111 now"]
df = pd.DataFrame({"code" : data})

# use regex to extract stuff and create a new column
df["ERR"] = df["code"].str.extract(r"(ERR\d{5})")

print(df)
</code>```

and create a new column by it:

```<code>                   code       ERR
0    got ERR12345 today  ERR12345
1              ERR 0815       NaN
2  to ERR or not to ERR       NaN
3       no ERR11111 now  ERR11111
</code>```

Related links:

https://kanoki.org/2019/11/12/how-to-use-regex-in-pandas/

Pandas extract numbers from column into new columns - the problem is much more complex though and the answers are as well

http://regex101.com to experiment with regexes

Body:
You can use the power of regular expression on the dataframe:

import pandas as pd

# prepare demo df
data = ["got ERR12345 today", "ERR 0815", "to ERR or not to ERR", "no ERR11111 now"]
df = pd.DataFrame({"code" : data})

# use regex to extract stuff and create a new column
df["ERR"] = df["code"].str.extract(r"(ERR\d{5})")

print(df)

and create a new column by it:

                   code       ERR
0    got ERR12345 today  ERR12345
1              ERR 0815       NaN
2  to ERR or not to ERR       NaN
3       no ERR11111 now  ERR11111

Related links:

https://kanoki.org/2019/11/12/how-to-use-regex-in-pandas/

Pandas extract numbers from column into new columns - the problem is much more complex though and the answers are as well

http://regex101.com to experiment with regexes


问:
function only works when clicked twice
i'm quite new when it comes to programming, so i do have some basic issues. one of them, that i can't really solve is the following:

i wrote a javascript code to change a div's content on a button click. it works fine, but only on the second click.

the buttons html:

```<code> <li class="navli"><a class="navbutton" id="home" onclick="navClick(this.id)">Home</a></li>
</code>```

the javascript:

```<code>var buttonId = "";
var contentText = "";

function navClick(clicked_id)
{
    buttonId = clicked_id;
    changeContent();
}

function changeContent(){
    fetch("./pages/"+buttonId+".txt")
    .then(function(response){
        return response.text()
        })
        .then(function(data){
            contentText = data;
        })
        document.getElementById("content").innerHTML = contentText;
}
</code>```

答:
It looks like an async mishap. Try it like this:

var buttonId = "";
var contentText = "";

function navClick(clicked_id)
{
    buttonId = clicked_id;
    changeContent();
}

function changeContent(){
    fetch("./pages/"+buttonId+".txt")
    .then(function(response){
        return response.text()
    })
    .then(function(data){
        contentText = data;
        document.getElementById("content").innerHTML = contentText;
    })
}
```

The innerHMTML needs to be updated inside the then, otherwise it will probably run before the fetch completes. My best guess.

Title: function only works when clicked twice

Body:
i'm quite new when it comes to programming, so i do have some basic issues. one of them, that i can't really solve is the following:

i wrote a javascript code to change a div's content on a button click. it works fine, but only on the second click.

the buttons html:

Home

the javascript:

var buttonId = "";
var contentText = "";

function navClick(clicked_id)
{
    buttonId = clicked_id;
    changeContent();
}

function changeContent(){
    fetch("./pages/"+buttonId+".txt")
    .then(function(response){
        return response.text()
        })
        .then(function(data){
            contentText = data;
        })
        document.getElementById("content").innerHTML = contentText;
}

Body:
It looks like an async mishap. Try it like this:

var buttonId = "";
var contentText = "";

function navClick(clicked_id)
{
    buttonId = clicked_id;
    changeContent();
}

function changeContent(){
    fetch("./pages/"+buttonId+".txt")
    .then(function(response){
        return response.text()
    })
    .then(function(data){
        contentText = data;
        document.getElementById("content").innerHTML = contentText;
    })
}

The innerHMTML needs to be updated inside the then, otherwise it will probably run before the fetch completes. My best guess.


问:
why Notification Color different in Dark and Light mode?
We use FCM Notification and set color in AndroidManifest.xml by com.google.firebase.messaging.default_notification_color metadata but It have issue for us why Android Notification shows two different colors in Dark and Light mode.
Is there a requirement for color for that? I reed about Notification color in Android Doc but I did not catch.

答: I got it. Android OS changes color bit when change mode.</p>


问:
convert php script to javascript
I'm having this script in PHP and I'm trying to convert it to JavaScript and I got some issues,
I did the most of the conversation I guess but I'm note sure if its the right way.

Here is the code:

```<code>var nums = [1,2,3,4];

function getsum(nums,sMinCount){
    var arry_point=[];
    var temp=[];
    var temp_mul=[];

    getarrayset(nums,arry_point,sMinCount,temp);

        arry_point.forEach( function(data)
        {
            var k=1;
            data.forEach( function(value)
            {
                k *= value;
            });

            temp_mul.push(k);
        });

        const reducer = (accumulator, currentValue) => accumulator + currentValue;
        return temp_mul.reduce(reducer);
}

function getarrayset(nums,arry_point,sMinCount,temp)
{
    if(nums.length >= sMinCount){
        if(nums.length ==1 && sMinCount==1 && !nums.includes(arry_point) ){
            arry_point.push(nums);
        }
        else{
            if(nums.length == sMinCount){
                sort(nums);
                if (!nums.includes(arry_point)) {
                    arry_point.push(nums);
                }
            }
            for(i=0; i<nums.length; i++){
                var copy_array = nums;

                delete copy_array[i];
                copy_array.sort();

                if(copy_array.length >=sMinCount && !copy_array.includes(temp)){
                    temp.push(copy_array);
                    getarrayset(copy_array,arry_point,sMinCount,temp);
                }

            }
        }
    }

}

console.log(getsum(nums,2));
</code>```

the error im geting is :
copy_array.sort();
result should be : 50

the php code can be found https://3v4l.org/uqip5

<?php
$array = [1,2,3,4];
echo (getsum($array,3));

function getsum($array,$size){
    $arry_point=array();
    $temp=array();
    $temp_mul=array();
    getarrayset($array,$arry_point,$size,$temp);
    foreach ($arry_point as $data) {
        $k=1;
        foreach ($data as $value) {
            $k *= $value;
        }
        array_push($temp_mul, $k);
    }
    return array_sum($temp_mul);
}

function getarrayset($array,&$arry_point,$size,&$temp)
{
    if(sizeof($array)>=$size){
        if(sizeof($array)==1 && $size==1 && (!in_array($array,$arry_point))){
            array_push($arry_point, $array);
        }
        else{
            if(sizeof($array)==$size){
                sort($array);
                if (!in_array($array, $arry_point)) {
                    array_push($arry_point, $array);
                }
            }
            for($i=0;$i<sizeof($array);$i++){
                $copy_array=$array;
                unset($copy_array[$i]);
                sort($copy_array);
                if(sizeof($copy_array)>=$size && (!in_array($copy_array, $temp))){
                    array_push($temp, $copy_array);
                    getarrayset($copy_array,$arry_point,$size,$temp);
                }

            }
        }
    }

}
```

thanks

答:
finally solved by me :)</p>

```<code>var keys = [1,2,3,4];

function recursive(cross, s, a) {
    for( var i=s; i < keys.length; i++ ){
        if( !cross ){
            var b = a.slice(0);
            b.push( keys[i] );
            set.push( b );
        }
        else{
            a.push(keys[i]);
            recursive(cross-1, i+1, a);
            a.splice(-1, 1);
        }
    }
}

var set = [];
recursive(2, 0, []);

const arr1 = set;

const multiply = (a, b) => a * b;

const product = arr => arr.reduce(multiply, 1);

const sumArr = arr1.map(product);

console.log(sumArr.reduce((a, b) => a + b, 0));
</code>```

Title: convert php script to javascript

Body:
I'm having this script in PHP and I'm trying to convert it to JavaScript and I got some issues,
I did the most of the conversation I guess but I'm note sure if its the right way.

Here is the code:

var nums = [1,2,3,4];

function getsum(nums,sMinCount){
    var arry_point=[];
    var temp=[];
    var temp_mul=[];

    getarrayset(nums,arry_point,sMinCount,temp);

        arry_point.forEach( function(data)
        {
            var k=1;
            data.forEach( function(value)
            {
                k *= value;
            });

            temp_mul.push(k);
        });

        const reducer = (accumulator, currentValue) => accumulator + currentValue;
        return temp_mul.reduce(reducer);
}

function getarrayset(nums,arry_point,sMinCount,temp)
{
    if(nums.length >= sMinCount){
        if(nums.length ==1 && sMinCount==1 && !nums.includes(arry_point) ){
            arry_point.push(nums);
        }
        else{
            if(nums.length == sMinCount){
                sort(nums);
                if (!nums.includes(arry_point)) {
                    arry_point.push(nums);
                }
            }
            for(i=0; i<nums.length; i++){
                var copy_array = nums;

                delete copy_array[i];
                copy_array.sort();

                if(copy_array.length >=sMinCount && !copy_array.includes(temp)){
                    temp.push(copy_array);
                    getarrayset(copy_array,arry_point,sMinCount,temp);
                }

            }
        }
    }

}

console.log(getsum(nums,2));

the error im geting is :
copy_array.sort();
result should be : 50

the php code can be found https://3v4l.org/uqip5

<?php
$array = [1,2,3,4];
echo (getsum($array,3));

function getsum($array,$size){
    $arry_point=array();
    $temp=array();
    $temp_mul=array();
    getarrayset($array,$arry_point,$size,$temp);
    foreach ($arry_point as $data) {
        $k=1;
        foreach ($data as $value) {
            $k *= $value;
        }
        array_push($temp_mul, $k);
    }
    return array_sum($temp_mul);
}

function getarrayset($array,&$arry_point,$size,&$temp)
{
    if(sizeof($array)>=$size){
        if(sizeof($array)==1 && $size==1 && (!in_array($array,$arry_point))){
            array_push($arry_point, $array);
        }
        else{
            if(sizeof($array)==$size){
                sort($array);
                if (!in_array($array, $arry_point)) {
                    array_push($arry_point, $array);
                }
            }
            for($i=0;$i<sizeof($array);$i++){
                $copy_array=$array;
                unset($copy_array[$i]);
                sort($copy_array);
                if(sizeof($copy_array)>=$size && (!in_array($copy_array, $temp))){
                    array_push($temp, $copy_array);
                    getarrayset($copy_array,$arry_point,$size,$temp);
                }

            }
        }
    }

}

thanks

Body:
finally solved by me :)

var keys = [1,2,3,4];

function recursive(cross, s, a) {
    for( var i=s; i < keys.length; i++ ){
        if( !cross ){
            var b = a.slice(0);
            b.push( keys[i] );
            set.push( b );
        }
        else{
            a.push(keys[i]);
            recursive(cross-1, i+1, a);
            a.splice(-1, 1);
        }
    }
}

var set = [];
recursive(2, 0, []);

const arr1 = set;

const multiply = (a, b) => a * b;

const product = arr => arr.reduce(multiply, 1);

const sumArr = arr1.map(product);

console.log(sumArr.reduce((a, b) => a + b, 0));


问:
Firebase handling multiple custom claims
So i have a use case where a user may need multiple custom claims but added at seperate points of the app i.e a user can be both a shop keeper and a shop owner or they may just be a shop keeper or just a user.

I understand via the doc's that when you assign a new custom claim it writes over the original claims therefore i need to read what claims the user currently has.   This is where i'm stuck...after i've recieved the claims how do I re-write them back to the user?

```<code>exports.onGameManagement = functions.database.ref("Core/CoreGames/{game}/teams/committee").onCreate((snapshot,context)=>{
    const position = snapshot.key;
    const uid = snapshot.val();
    const game = context.params.game;
    if(position=="gLead"||position=="depGameLead"){
        //NEEDS ADMIN RIGHTS
        //ADD TOKEN WRITE RIGHTS. - check for current claims
        admin.auth().getUser(uid).then((userRecord)=>{
            //got the users claims
            console.log(userRecord.customClaims);
            //how do i add this array of claims to the setCustomUserClaims() method?
            admin.auth().setCustomUserClaims(uid, {gameAdmin: true, userRecord.customClaims}).then(() => {
                // The new custom claims will propagate to the user's ID token the
                // next time a new one is issued.
              });
        })

    }else{

    }

})
</code>```

I suspect this is a pretty simple fix but i can't seem to find any examples anywhere of how to handle adding multiple claims at seperate times...stacking so to speak. Many thanks for your help in advance.

答:
You're pretty close: you can use the spread operator (...) to add the existing claims and new claim into a single object:

```<code>admin.auth().getUser(uid).then((userRecord)=>{
    admin.auth().setCustomUserClaims(uid, {gameAdmin: true, ...userRecord.customClaims});
})
</code>```

Alternatively, you can simply extract the claims object from the user record and add your new claim to it before passing it back to setCustomUserClaims:

```<code>admin.auth().getUser(uid).then((userRecord)=>{
    let claims = userRecord.customClaims;
    claims.gameAdmin = true;
    admin.auth().setCustomUserClaims(uid, claims);
})
</code>```

To delete a claim, you'd replace claims.gameAdmin = true; with delete claims.gameAdmin; in that previous snippet.

Body:
So i have a use case where a user may need multiple custom claims but added at seperate points of the app i.e a user can be both a shop keeper and a shop owner or they may just be a shop keeper or just a user.

I understand via the doc's that when you assign a new custom claim it writes over the original claims therefore i need to read what claims the user currently has.   This is where i'm stuck...after i've recieved the claims how do I re-write them back to the user?

exports.onGameManagement = functions.database.ref("Core/CoreGames/{game}/teams/committee").onCreate((snapshot,context)=>{
    const position = snapshot.key;
    const uid = snapshot.val();
    const game = context.params.game;
    if(position=="gLead"||position=="depGameLead"){
        //NEEDS ADMIN RIGHTS
        //ADD TOKEN WRITE RIGHTS. - check for current claims
        admin.auth().getUser(uid).then((userRecord)=>{
            //got the users claims
            console.log(userRecord.customClaims);
            //how do i add this array of claims to the setCustomUserClaims() method?
            admin.auth().setCustomUserClaims(uid, {gameAdmin: true, userRecord.customClaims}).then(() => {
                // The new custom claims will propagate to the user's ID token the
                // next time a new one is issued.
              });
        })

    }else{

    }

})

I suspect this is a pretty simple fix but i can't seem to find any examples anywhere of how to handle adding multiple claims at seperate times...stacking so to speak. Many thanks for your help in advance.

Body:
You're pretty close: you can use the spread operator (...) to add the existing claims and new claim into a single object:

admin.auth().getUser(uid).then((userRecord)=>{
    admin.auth().setCustomUserClaims(uid, {gameAdmin: true, ...userRecord.customClaims});
})

Alternatively, you can simply extract the claims object from the user record and add your new claim to it before passing it back to setCustomUserClaims:

admin.auth().getUser(uid).then((userRecord)=>{
    let claims = userRecord.customClaims;
    claims.gameAdmin = true;
    admin.auth().setCustomUserClaims(uid, claims);
})

To delete a claim, you'd replace claims.gameAdmin = true; with delete claims.gameAdmin; in that previous snippet.


问:
Importing default value from each file in specified folder
Lets say in my project i have a folder models and i dont know how many js-files are within it? Is there way to import all default values from each file with sintax like this or something

```<code>import * as models from './models'
</code>```

so variable models would have an object where keys are files' names and values are default values or i should import from each file separately?

Thank you

答:
I assume you might have following structure:

```<code>models
|------> model1.js
|------> model2.js
</code>```

So now Add another file called index.js as like as given below:

```<code>models
|------> model1.js
|------> model2.js
|------> index.js
</code>```

And index.js file will be like:

```<code>import * as model1 from "./model1.js"
import * as model2 from "./model2.js"

export { model1, model2 };
</code>```

Now you can call models/index.js file from anywhere as like as given below:

```<code>import * as models from "./models";

// models.model1
// models.model2
</code>```

Hope it might solve your problem.

Body:
Lets say in my project i have a folder models and i dont know how many js-files are within it? Is there way to import all default values from each file with sintax like this or something

import * as models from './models'

so variable models would have an object where keys are files' names and values are default values or i should import from each file separately?

Thank you

Body:
I assume you might have following structure:

models
|------> model1.js
|------> model2.js

So now Add another file called index.js as like as given below:

models
|------> model1.js
|------> model2.js
|------> index.js

And index.js file will be like:

import * as model1 from "./model1.js"
import * as model2 from "./model2.js"

export { model1, model2 };

Now you can call models/index.js file from anywhere as like as given below:

import * as models from "./models";

// models.model1
// models.model2

Hope it might solve your problem.


问:
how to handle extra parameters on the swift model class
I am new to swift. I create a codable model class and when the back end team added extra parameters on it my model class is not supporting. Can someone please explain how to achieve this.

```<code> public struct Posts : Codable {
        let`internal` : Bool?
        let documents : [Document]?
        let entityID : String?
      enum CodingKeys: String, CodingKey {
          case `internal` = "internal"
            case documents = "documents"
            case entityID = "entityID"
}
init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            `internal` = try (values.decodeIfPresent(Bool.self, forKey: .internal) ?? false)
            documents = try values.decodeIfPresent([Document].self, forKey: .documents)
            entityID = try (values.decodeIfPresent(String.self, forKey: .entityID) ?? "")
} }
</code>```

My codable look like this anything goes wrong on this.

答:
You can use the basic stuct I've given without a custom init(decoder:) method, and it would still work even if new parameters are added later on. You can add them as you require them.

public struct Posts: Codable {
    let`internal`: Bool?
    let documents: [Document]?
    let entityID: String?
}
```

<p>Note: You need to add new keys to the <code>struct</code> manually if you want to access them. This struct only gives what's already been parsed by the <code>struct</code>. This won't break unless the backend decides to provide a different value type for one of these keys. If new keys are added that you would like to access modify the <code>struct</code> to this:</p>

<pre class="lang-swift prettyprint-override"><code>public struct Posts: Codable {
    let`internal`: Bool?
    let documents: [Document]?
    let entityID: String?
    let newPropertyName: NewPropertyType
}
</code>```

Body:
I am new to swift. I create a codable model class and when the back end team added extra parameters on it my model class is not supporting. Can someone please explain how to achieve this.

 public struct Posts : Codable {
        let`internal` : Bool?
        let documents : [Document]?
        let entityID : String?
      enum CodingKeys: String, CodingKey {
          case `internal` = "internal"
            case documents = "documents"
            case entityID = "entityID"
}
init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            `internal` = try (values.decodeIfPresent(Bool.self, forKey: .internal) ?? false)
            documents = try values.decodeIfPresent([Document].self, forKey: .documents)
            entityID = try (values.decodeIfPresent(String.self, forKey: .entityID) ?? "")
} }

My codable look like this anything goes wrong on this.

Body:
You can use the basic stuct I've given without a custom init(decoder:) method, and it would still work even if new parameters are added later on. You can add them as you require them.

public struct Posts: Codable {
    let`internal`: Bool?
    let documents: [Document]?
    let entityID: String?
}

Note: You need to add new keys to the struct manually if you want to access them. This struct only gives what's already been parsed by the struct. This won't break unless the backend decides to provide a different value type for one of these keys. If new keys are added that you would like to access modify the struct to this:

public struct Posts: Codable {
    let`internal`: Bool?
    let documents: [Document]?
    let entityID: String?
    let newPropertyName: NewPropertyType
}


问:
Designing an XML structure
XYZ school wants to store the details of students and staff in an XML file. The following scenario helps in designing the XML document:

persons will be the root tag.

persons will have the entry of each person with name, age, gender, address.

A person can be either a student or staff.

student will have rollno, standard and section.

If staff, then staffid and subject.

Every person must have an address with the following entry- doorno, street,city and state.

I am getting this error:

Exception: cvc-complex-type.2.4.a: Invalid content was found starting with element 'student'. One of '{name}' is expected.

答:
One of the names may not be of valid type. Try the following code.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<persons>
    <person>
        <name>Sam</name>
        <age>11</age>
        <gender>M</gender>
        <address>
            <doorno>20</doorno>
            <street>Gandhi Colony</street>
            <city>Hyderabad</city>
            <state>Telangana</state>
        </address>
        <student>
            <rollno>39</rollno>
            <standard>6</standard>
            <section>A</section>
        </student>
    </person>
    <person>
        <name>Sally</name>
        <age>30</age>
        <gender>F</gender>
        <address>
            <doorno>17</doorno>
            <street>Ambedkar Road</street>
            <city>Hyderabad</city>
            <state>Telangana</state>
        </address>
        <staff>
            <staffid>120</staffid>
            <subject>English</subject>
        </staff>
    </person>
</persons>
</code>```

Title: Designing an XML structure

Body:
One of the names may not be of valid type. Try the following code.

<?xml version="1.0" encoding="utf-8"?>
<persons>
    <person>
        <name>Sam</name>
        <age>11</age>
        <gender>M</gender>
        <address>
            <doorno>20</doorno>
            <street>Gandhi Colony</street>
            <city>Hyderabad</city>
            <state>Telangana</state>
        </address>
        <student>
            <rollno>39</rollno>
            <standard>6</standard>
            <section>A</section>
        </student>
    </person>
    <person>
        <name>Sally</name>
        <age>30</age>
        <gender>F</gender>
        <address>
            <doorno>17</doorno>
            <street>Ambedkar Road</street>
            <city>Hyderabad</city>
            <state>Telangana</state>
        </address>
        <staff>
            <staffid>120</staffid>
            <subject>English</subject>
        </staff>
    </person>
</persons>


问:
Scrapy: How to insert data into SQLite
I'm trying to write a dictionary into sql database, but without success giving me:

```<code>cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES("%s", "%s")' % (url, First_and_Last_Name))
NameError: name 'url' is not defined
</code>```

spider:

```<code>from scrapy.crawler import CrawlerProcess
import scrapy
import sqlite3

class Wellness(scrapy.Spider):
name = "wellness"
start_urls = ['https://www.wellness.com/dir/6022571/acupuncturist/ri/east-greenwich/hwasook-lee-phoenix-fertility-center-dac']

def parse(self, response):
    item = {
            'url' : response.request.url,
            'First_and_Last_Name' : response.css('h1::text').get(),
    }
    directions_link = response.css('#directions_tab a::attr(href)').get()
    yield scrapy.Request(response.urljoin(directions_link), callback=self.parse_directions, meta={'item': item})

def parse_directions(self, response):
    item = response.meta['item']
    item['Phone'] = response.css('.tel::text').get()
    yield item

    db = sqlite3.connect('posts.db')
    db.execute('''CREATE TABLE IF NOT EXISTS posts(id INTEGER PRIMARY KEY AUTOINCREMENT,url TEXT, First_and_Last_Name TEXT);''')
    db.commit()

    cursor = db.cursor()
    cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES("%s", "%s")' % (url, First_and_Last_Name))

    db.commit()
    db.close()

if __name__ == '__main__':
    process = CrawlerProcess()
    process.crawl(Wellness)
    process.start()
</code>```

What am I doing wrong here. Any and all help is appreciated. Thanks!

答:
You want to use item['url'] instead of url, same for First_and_Last_Name:

cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES("%s", "%s")' % (item['url'], item['First_and_Last_Name']))
```

<p>Also, don't use string formatting with SQL statements, as it makes your code vulnerable to SQL injection attacks. Let the <code>cursor.execute</code> method do the escaping for you:</p>

<pre class="lang-py prettyprint-override"><code>cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES(?, ?)', (item['url'], item['First_and_Last_Name']))
</code>```

Title: Scrapy: How to insert data into SQLite

Body:
I'm trying to write a dictionary into sql database, but without success giving me:

cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES("%s", "%s")' % (url, First_and_Last_Name))
NameError: name 'url' is not defined

spider:

from scrapy.crawler import CrawlerProcess
import scrapy
import sqlite3

class Wellness(scrapy.Spider):
name = "wellness"
start_urls = ['https://www.wellness.com/dir/6022571/acupuncturist/ri/east-greenwich/hwasook-lee-phoenix-fertility-center-dac']

def parse(self, response):
    item = {
            'url' : response.request.url,
            'First_and_Last_Name' : response.css('h1::text').get(),
    }
    directions_link = response.css('#directions_tab a::attr(href)').get()
    yield scrapy.Request(response.urljoin(directions_link), callback=self.parse_directions, meta={'item': item})

def parse_directions(self, response):
    item = response.meta['item']
    item['Phone'] = response.css('.tel::text').get()
    yield item

    db = sqlite3.connect('posts.db')
    db.execute('''CREATE TABLE IF NOT EXISTS posts(id INTEGER PRIMARY KEY AUTOINCREMENT,url TEXT, First_and_Last_Name TEXT);''')
    db.commit()

    cursor = db.cursor()
    cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES("%s", "%s")' % (url, First_and_Last_Name))

    db.commit()
    db.close()

if __name__ == '__main__':
    process = CrawlerProcess()
    process.crawl(Wellness)
    process.start()

What am I doing wrong here. Any and all help is appreciated. Thanks!

Body:
You want to use item['url'] instead of url, same for First_and_Last_Name:

cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES("%s", "%s")' % (item['url'], item['First_and_Last_Name']))

Also, don't use string formatting with SQL statements, as it makes your code vulnerable to SQL injection attacks. Let the cursor.execute method do the escaping for you:

cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES(?, ?)', (item['url'], item['First_and_Last_Name']))


问:
Adding a textbox and a combobox in a webpage using Django CMS
I've just started using Django CMS so my understanding of the tool is very limited, but I've been trying to do something that I assumed would be very simple, yet, I couldn't find a way of doing it.

I'm currently looking to add some textboxes and comboboxes on a webpage. I couldn't find these controls in the content section of the CMS. There are many choices like buttons, maps, videos, pictures, etc. but I didn't find textbox or combobox. How can I create these?

Thanks!

答: I downloaded the Aldryn package which seems to do the trick.</p>


问:
How to select all values that a not a number using SQL?
Due to an earlier error, I ended up with letters and symbols in places where I should have had integers and floars. At this time, I don't know the extent of the problem and working to correct the code as we move forward.

As of right now when I run SELECT distinct col1 from table; I get integers, floats, symbols and letters. A few million of them.

How can I update the SQL to exclude all numbers? In other words, show me only letters and symbols.

答:
Hmmm . . . SQLite doesn't have regular expressions built-in, making this a bit of a pain.  If the column actually contains numbers and strings (because that is possible in SQLite), you can use

```<code>where typeof(col) = 'text'
</code>```

If the types are all text (so '1.23' rather than 1.23), then this may do what you want:

```<code>where cast( (col + 0) as text) = col
</code>```

Body:
Hmmm . . . SQLite doesn't have regular expressions built-in, making this a bit of a pain.  If the column actually contains numbers and strings (because that is possible in SQLite), you can use

where typeof(col) = 'text'

If the types are all text (so '1.23' rather than 1.23), then this may do what you want:

where cast( (col + 0) as text) = col


问:
strange python dictionary?
new to python here. Been trying this for quite a while now; would really appreciate some help.

I thought to try my hand at pulling data from an api, and what i got is a very long dictionary ( or at least i think its an dictionary )

```<code>response = requests.get('https://api.coingecko.com/api/v3/finance_products')
print(response.content)
</code>```

can anyone give me any pointers on how to manipulate the results ?

I can't call the dictionary.

First few characters of it :

b'[{"platform":"Binance Savings","identifier":"CCOCOS30DAYSS001","supply_rate_percentage":"6.0","borrow_rate_percentage":null,"number_duration":null,"length_duration":null,"start_at":0,"end_at":0,"value_at":0,"redeem_at":0},{"platform":"DDEX Lending","identifier": etc etc

i'm not sure why there is a b' at the front.

Sorry if this isn't a clear question.

答:
You can use

```<code>response.json()
</code>```

which decodes it immediatly to a json object. Documentation here

Title: strange python dictionary?

Body:
new to python here. Been trying this for quite a while now; would really appreciate some help.

I thought to try my hand at pulling data from an api, and what i got is a very long dictionary ( or at least i think its an dictionary )

response = requests.get('https://api.coingecko.com/api/v3/finance_products')
print(response.content)

can anyone give me any pointers on how to manipulate the results ?

I can't call the dictionary.

First few characters of it :

b'[{"platform":"Binance Savings","identifier":"CCOCOS30DAYSS001","supply_rate_percentage":"6.0","borrow_rate_percentage":null,"number_duration":null,"length_duration":null,"start_at":0,"end_at":0,"value_at":0,"redeem_at":0},{"platform":"DDEX Lending","identifier": etc etc

i'm not sure why there is a b' at the front.

Sorry if this isn't a clear question.

Body:
You can use

response.json()

which decodes it immediatly to a json object. Documentation here