问:
Is there a better way to pass in components using hooks? My solution is provided
I'm not sure how to phrase this question without it being multiple problems per this being closed.

This is my solution to passing in components via hooks and rendering them based on what link the user presses on. I'm putting the components as objects into an array and then using that array to map through the index which then makes this all very dynamic.

My only question is if there is a more effective way of achieving this and why? I'm still intermediate with Javascript so I'm trying to learn the most effective way to do something.

```<code>const switchArray = [
      {
        name: 'Step 1',
        Component: <Step1 />
      },
      {
        name: 'Step 2',
        Component: <Step2 />
      },
      {
        name: 'Step 3',
        Component: <Step3 />
      },
      {
        name: 'Step 4',
        Component: <Step4 />
      }
    ]

const Home = () => {
  const classes = useStyles();
  const [activeIndex, setActiveIndex] = useState(0); // setting the state to 0
  const handleIndex = val => setActiveIndex(val);

  return (
    <div className={classes.container}>
      <div className={classes.contentBox}>
        <h3 className={classes.heading}>Heading</h3>
        <p className={classes.paragraph}>
        </p>
      </div>
      <div className={classes.wrapper}>
        <div className={classes.breadcrumbs}>
          <Breadcrumbs separator=">" aria-label="breadcrumb">
            {switchArray.map((item, index) => (
                <Link
                  key={index}
                  className={classes.link}
                  color="inherit"
                  onClick={() => handleIndex(index)}
                  style={{color: index === activeIndex ? 'black' : 'inherit'}}
                >
                {item.name}
                </Link>

            ))}
          </Breadcrumbs>
        </div>
      </div>
      <div>
        <div className={classes.component}>{switchArray[activeIndex].Component}</div>
      </div>
    </div>
  );
};
</code>```

答:
1) Instead of using array, Object makes it easy.

2) Avoid using index for React component key value

```<code>const steps = {
  "Step 1": <Step1 />,
  "Step 2": <Step2 />,
  "Step 3": <Step3 />,
  "Step 4": <Step4 />
};

const Home = () => {
  const classes = useStyles();
  const [activeItem, setActiveItem] = useState("Step 1");

  return (
    <div className={classes.container}>
      <div className={classes.contentBox}>
        <h3 className={classes.heading}>Heading</h3>
        <p className={classes.paragraph}></p>
      </div>
      <div className={classes.wrapper}>
        <div className={classes.breadcrumbs}>
          <Breadcrumbs separator=">" aria-label="breadcrumb">
            {Object.keys(steps).map(item => (
              <Link
                key={item}
                className={classes.link}
                color="inherit"
                onClick={() => setActiveItem(item)}
                style={{ color: item === activeItem ? "black" : "inherit" }}
              >
                {item}
              </Link>
            ))}
          </Breadcrumbs>
        </div>
      </div>
      <div>
        <div className={classes.component}>{steps[activeItem]}</div>
      </div>
    </div>
  );
};
</code>```

Body:
I'm not sure how to phrase this question without it being multiple problems per this being closed.

This is my solution to passing in components via hooks and rendering them based on what link the user presses on. I'm putting the components as objects into an array and then using that array to map through the index which then makes this all very dynamic.

My only question is if there is a more effective way of achieving this and why? I'm still intermediate with Javascript so I'm trying to learn the most effective way to do something.

const switchArray = [
      {
        name: 'Step 1',
        Component: <Step1 />
      },
      {
        name: 'Step 2',
        Component: <Step2 />
      },
      {
        name: 'Step 3',
        Component: <Step3 />
      },
      {
        name: 'Step 4',
        Component: <Step4 />
      }
    ]

const Home = () => {
  const classes = useStyles();
  const [activeIndex, setActiveIndex] = useState(0); // setting the state to 0
  const handleIndex = val => setActiveIndex(val);

  return (

Heading

          <Breadcrumbs separator=">" aria-label="breadcrumb">
            {switchArray.map((item, index) => (
                <Link
                  key={index}
                  className={classes.link}
                  color="inherit"
                  onClick={() => handleIndex(index)}
                  style={{color: index === activeIndex ? 'black' : 'inherit'}}
                >
                {item.name}
                </Link>

            ))}
          </Breadcrumbs>

{switchArray[activeIndex].Component}

  );
};

Body:
1) Instead of using array, Object makes it easy.

2) Avoid using index for React component key value

const steps = {
  "Step 1": <Step1 />,
  "Step 2": <Step2 />,
  "Step 3": <Step3 />,
  "Step 4": <Step4 />
};

const Home = () => {
  const classes = useStyles();
  const [activeItem, setActiveItem] = useState("Step 1");

  return (
    <div className={classes.container}>
      <div className={classes.contentBox}>
        <h3 className={classes.heading}>Heading</h3>
        <p className={classes.paragraph}></p>
      </div>
      <div className={classes.wrapper}>
        <div className={classes.breadcrumbs}>
          <Breadcrumbs separator=">" aria-label="breadcrumb">
            {Object.keys(steps).map(item => (
              <Link
                key={item}
                className={classes.link}
                color="inherit"
                onClick={() => setActiveItem(item)}
                style={{ color: item === activeItem ? "black" : "inherit" }}
              >
                {item}
              </Link>
            ))}
          </Breadcrumbs>
        </div>
      </div>
      <div>
        <div className={classes.component}>{steps[activeItem]}</div>
      </div>
    </div>
  );
};


来源: stackexchange

问:
How to perform segue ONLY if token not nil swift 5
As the title is saying, im working on a login. The tokenHandler is already working and im using a KeychainAccess.
Here my tokenHandler class:

```<code>import KeychainAccess

class TokenHandler {

    func saveUsernameToKeyChain(username: String) {
        do {
            try keychain.set(username, key: "myUsername")
        } catch let error {
            print(error)
        }
    }

    func getUsernameFromKeyChain() -> String? {
        return keychain[string: "myUsername" ]
    }

    func saveUserPasswordToKeyChain(password: String) {
        do {
            try keychain.set(password, key: "UserPassword")
        } catch let error   {
            print(error)
        }
    }

    func getUserPasswordFromKeyChain() -> String? {
        return keychain[string: "UserPassword"]
    }

    let keychain = Keychain(service: "com.mybackendpage")

    func getTokenFromKeyChain() -> String? {
        return keychain[string: "myToken"]
    }

    func saveTokenToKeyChain(token: String) {
        do {
            try keychain.set(token, key: "myToken")
        }
        catch let error {
            print(error)
        }
    }

    func saveRefreshTokenToKeyChain(refreshToken: String) {
        do {
            try keychain.set(refreshToken, key: "myRefreshToken")
        }
        catch let error {
            print(error)
        }
    }

    func loginToAPI(username: String, password: String) -> Any {
        guard let url = URL(string: "https:mypage.com") else
        {
            return ""
        }

        let jsonData = try? JSONSerialization.data(withJSONObject: [
            "email": username,
            "password": password
        ])

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        // insert json data to the request
        request.httpBody = jsonData

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard error == nil else { print(error!.localizedDescription); return }
            guard let data = data else { print("Empty data"); return }

            if let str = String(data: data, encoding: .utf8) {
                print(str)
            }
        }.resume()

        return "TOKENSTRING"
    }

}
</code>```

And here my LoginVC class:

```<code>class LoginViewController: UIViewController {

    let tokenHandler = TokenHandler()

    @IBOutlet weak var usernameTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let username = tokenHandler.getUsernameFromKeyChain()

        let userPassword = tokenHandler.getUserPasswordFromKeyChain()

    @IBAction func unwindToLogin(_ unwindSegue: UIStoryboardSegue) {
        print("-unwinding success-")

    }

    // func for the login button:
    @IBAction func loginButton(_ sender: UIButton) {
        activityIndicator.startAnimating()
        loginWithCredentials()

        let token = tokenHandler.getTokenFromKeyChain()

        if token != nil {
            performSegue(withIdentifier: "segueToNavigation", sender: self)
        } else if ( token == nil ){
            // create the alert:
            let alert = UIAlertController(title: "Wrong login data", message: "Please try again.", preferredStyle: UIAlertController.Style.alert)

            // add an action to the button:
            alert.addAction(UIAlertAction( title: "Ok", style: UIAlertAction.Style.default, handler: nil ))

            // show the alert:
            self.presentingViewController

            print("-Token could not be created.-")
        }

        else {
            // create the alert:
            let alert = UIAlertController(title: "Wrong login data", message: "Please try again.", preferredStyle: UIAlertController.Style.alert)

            // add an action to the button:
            alert.addAction(UIAlertAction( title: "Ok", style: UIAlertAction.Style.default, handler: nil ))

            // show the alert:
            self.presentingViewController

            print("-Token could not be created.-")
        }

    }

    func loginWithCredentials() {
        let username: String = usernameTextField.text!
        let password: String = passwordTextField.text!

        let authResponse = tokenHandler.loginToAPI(username: username, password: password)

    }

}
</code>```

Im still not skilled swift programmer, so I will be happy if any of you could give me some good advices. I was reading and trying to work with the delegate principle, but frankly, my guts are telling me, that this is not what I need.
I was reading about

```<code>PerformSegueWithIdentifier
</code>```

but not really understand how to transform it into my code...

The segues which I have included storyboardwise are working, but unfortunately also, if the test user didn't do the login. So, im pressing the login button w/o any username and userpwd and im getting anyway to the next View. Not cool, so help me please :)

EDIT: I changed performSegue to shouldPerformSegue but im still getting access to the next View w/o any permission.

EDIT: Im getting:

```<code>-Token could not be created.-
{"message":"The given data was invalid.","errors":{"email":["The email field is required."],"password":["The password field is required."]}}
</code>```

So the error is correct, but by pressing on the "Login" Button im still getting to the next View.

EDIT:
Ive tried a few changes, now I have for eg:

```<code>if tokenHandler.getTokenFromKeyChain() != nil
</code>```

instead of

```<code>let token = tokenHandler.getTokenFromKeyChain()

        if token != nil
</code>```

Apparently, nothing what im doing in this IBAction for the LoginButton does anything different. What am I missing?

答:
Well, it looks to me, that if you did once call saveTokenToKeyChain() ever since you've been running the app on your device/simulator, then the KeyChain will hold some string there, as I can't see where you set it to nil (I can't see where you set it at all, but let's suppose that you deleted the code that saves the token). So what your current logic does is that it performs the segue if you have some string saved as token (no matter if it's empty string, random string or an expired token). Whatever was left there, getTokenFromKeyChain() will return you a string so your if token != nil will always evaluate to true.

On the other hand, if you clear the KeyChain data, as I can't find any piece of code that saves the token, the UI will always say that the login fails, even if it actually succeeds.

So you should handle the login success/failure with properly writing/deleting the token to/from KeyChain.

ContentLicense: CC BY-SA 4.0

Body:
As the title is saying, im working on a login. The tokenHandler is already working and im using a KeychainAccess.
Here my tokenHandler class:

import KeychainAccess

class TokenHandler {

    func saveUsernameToKeyChain(username: String) {
        do {
            try keychain.set(username, key: "myUsername")
        } catch let error {
            print(error)
        }
    }

    func getUsernameFromKeyChain() -> String? {
        return keychain[string: "myUsername" ]
    }

    func saveUserPasswordToKeyChain(password: String) {
        do {
            try keychain.set(password, key: "UserPassword")
        } catch let error   {
            print(error)
        }
    }

    func getUserPasswordFromKeyChain() -> String? {
        return keychain[string: "UserPassword"]
    }

    let keychain = Keychain(service: "com.mybackendpage")

    func getTokenFromKeyChain() -> String? {
        return keychain[string: "myToken"]
    }

    func saveTokenToKeyChain(token: String) {
        do {
            try keychain.set(token, key: "myToken")
        }
        catch let error {
            print(error)
        }
    }

    func saveRefreshTokenToKeyChain(refreshToken: String) {
        do {
            try keychain.set(refreshToken, key: "myRefreshToken")
        }
        catch let error {
            print(error)
        }
    }

    func loginToAPI(username: String, password: String) -> Any {
        guard let url = URL(string: "https:mypage.com") else
        {
            return ""
        }

        let jsonData = try? JSONSerialization.data(withJSONObject: [
            "email": username,
            "password": password
        ])

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        // insert json data to the request
        request.httpBody = jsonData

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard error == nil else { print(error!.localizedDescription); return }
            guard let data = data else { print("Empty data"); return }

            if let str = String(data: data, encoding: .utf8) {
                print(str)
            }
        }.resume()

        return "TOKENSTRING"
    }

}

And here my LoginVC class:

class LoginViewController: UIViewController {

    let tokenHandler = TokenHandler()

    @IBOutlet weak var usernameTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let username = tokenHandler.getUsernameFromKeyChain()

        let userPassword = tokenHandler.getUserPasswordFromKeyChain()

    @IBAction func unwindToLogin(_ unwindSegue: UIStoryboardSegue) {
        print("-unwinding success-")

    }

    // func for the login button:
    @IBAction func loginButton(_ sender: UIButton) {
        activityIndicator.startAnimating()
        loginWithCredentials()

        let token = tokenHandler.getTokenFromKeyChain()

        if token != nil {
            performSegue(withIdentifier: "segueToNavigation", sender: self)
        } else if ( token == nil ){
            // create the alert:
            let alert = UIAlertController(title: "Wrong login data", message: "Please try again.", preferredStyle: UIAlertController.Style.alert)

            // add an action to the button:
            alert.addAction(UIAlertAction( title: "Ok", style: UIAlertAction.Style.default, handler: nil ))

            // show the alert:
            self.presentingViewController

            print("-Token could not be created.-")
        }

        else {
            // create the alert:
            let alert = UIAlertController(title: "Wrong login data", message: "Please try again.", preferredStyle: UIAlertController.Style.alert)

            // add an action to the button:
            alert.addAction(UIAlertAction( title: "Ok", style: UIAlertAction.Style.default, handler: nil ))

            // show the alert:
            self.presentingViewController

            print("-Token could not be created.-")
        }

    }

    func loginWithCredentials() {
        let username: String = usernameTextField.text!
        let password: String = passwordTextField.text!

        let authResponse = tokenHandler.loginToAPI(username: username, password: password)

    }

}

Im still not skilled swift programmer, so I will be happy if any of you could give me some good advices. I was reading and trying to work with the delegate principle, but frankly, my guts are telling me, that this is not what I need.
I was reading about

PerformSegueWithIdentifier

but not really understand how to transform it into my code...

The segues which I have included storyboardwise are working, but unfortunately also, if the test user didn't do the login. So, im pressing the login button w/o any username and userpwd and im getting anyway to the next View. Not cool, so help me please :)

EDIT: I changed performSegue to shouldPerformSegue but im still getting access to the next View w/o any permission.

EDIT: Im getting:

-Token could not be created.-
{"message":"The given data was invalid.","errors":{"email":["The email field is required."],"password":["The password field is required."]}}

So the error is correct, but by pressing on the "Login" Button im still getting to the next View.

EDIT:
Ive tried a few changes, now I have for eg:

if tokenHandler.getTokenFromKeyChain() != nil

instead of

let token = tokenHandler.getTokenFromKeyChain()

        if token != nil

Apparently, nothing what im doing in this IBAction for the LoginButton does anything different. What am I missing?


问:
Just started learning C this semester, but I can't seem to understand what the professor wants from us in this question
Original question:

A positive number has the same representation in one’s complement and in two’s complement. Suppose its representation is interpreted as two’s complement, and its additive  inverse  is determined.  Now  this  representation  is  interpreted  as  one’s complement, and the  additive inverse is determined. Whether interpreted as one’s complement or two’s complement, the result will be the same, since it is a positive number. What is the relationship between this result and the original number?

I don't know what he means by "what is the relationship between this result and the original number". I think I understand the process of what he wants us to do:

First take a binary (0101) then take the two's complement (1011) and then the one's complement of the two's complement (0100). What next?

答:
If I posted more than this, I'd be giving you the answer....

The resulting number will not be the same as the original number, but the difference between them will be consistent regardless of the value chosen as the original number. Work through several examples until you see the relationship. You've shown an example in binary, which may make it more difficult to see the relationship. Work through several examples in decimal format (convert to binary if that helps, but then convert back to decimal). Choose examples that start with even numbers, and other examples that start with odd numbers, so you don't come to the wrong conclusion about the relationship.

Then, as a bonus, see if you can figure out why that relationship exists. It has to do with the fact that the negation of a value in one of the formats is performed differently than the negation of a value in the other format.


问:
Returning lambda with function vs with macro in common lisp
What is the difference between using a macro and a function to return a lambda in common lisp?

(defun f ()
  (lambda () (format t "hello world")))

(defmacro m ()
  (lambda () (format t "hello world")))

; is (f) equal to (m) ?
```

do they return the exact same thing?

And what if the returned lambda forms were quoted? ('(lambda ...))

I'm asking this because in chapter 3 of Practical Common Lisp there is a macro (where) that returns a (back)quoted lambda, and I don't get why it could not be just a simple function that returns the same lambda.

答:
It's not the same.

Literal Functions in code vs. compiling a file

For example see this file example.lisp:

```<code>(defmacro fm ()
  (lambda () (print "hi")))

(defun foo ()
  (fm))
</code>```

Now compile the file with (compile-file "example.lisp").

Chances are high that it will not work. SBCL says:

```<code>; in: DEFUN FOO
;     (FM)
; ==>
;   #<FUNCTION (LAMBDA () :IN FM) {226680AB}>
;
; caught ERROR:
;   Objects of type FUNCTION can't be dumped into fasl files.
;
; compilation unit finished
;   caught 1 ERROR condition
</code>```

Why is that?

Your function f returns a function at runtime.

Your macro m returns a function at macro expansion time. That means a literal object will be included in the code. Literal functions usually can't be dumped by the file compiler.

Next Example: function and two macros

```<code>(defun f ()
  (lambda () (format t "hello world")))

(defmacro m0 ()
  (lambda () (format t "hello world")))

(defmacro m1 ()
  `(lambda () (format t "hello world")))

(defun foo ()
  (list
    (f)         ; returns a function at runtime

    (m0)        ; a literal function, created at macro expansion time
                ;   thus can't be dumped by a file compiler

    (m1)        ; a function form, (function (lambda () ...))
  ))
</code>```

Examples in REPL, with variables

Now let's look with variables:

```<code>(defun f (a)
  (lambda (b) (list a b)))   ; A is a lexical reference to above A

(defmacro m0 (a)
  (lambda (b) (list a b)))   ; A is a lexical reference to above A (!)

(defmacro m1 (a)             ; A is unused
  `(lambda (b) (list a b)))  ; A is not a reference to above A (!)
</code>```

now at the REPL:

```<code>* (defun foo (c)
    (list

     (ignore-errors (funcall (f  c) 2))
     (ignore-errors (funcall (m0 c) 2))
     (ignore-errors (funcall (m1 c) 2))

    ))
; in: DEFUN FOO
;     (M1 C)
; --> LAMBDA FUNCTION
; ==>
;   (LIST A B)
;
; caught WARNING:
;   undefined variable: COMMON-LISP-USER::A
;
; compilation unit finished
;   Undefined variable:
;     A
;   caught 1 WARNING condition

* (foo 3)
((3 2)    ; <- runtime values
 (C 2)    ; <- C is source code
 NIL)     ; <- error, since A is undefined
</code>```

Body:
What is the difference between using a macro and a function to return a lambda in common lisp?

(defun f ()
  (lambda () (format t "hello world")))

(defmacro m ()
  (lambda () (format t "hello world")))

; is (f) equal to (m) ?

do they return the exact same thing?

And what if the returned lambda forms were quoted? ('(lambda ...))

I'm asking this because in chapter 3 of Practical Common Lisp there is a macro (where) that returns a (back)quoted lambda, and I don't get why it could not be just a simple function that returns the same lambda.

Body:
It's not the same.

Literal Functions in code vs. compiling a file

For example see this file example.lisp:

(defmacro fm ()
  (lambda () (print "hi")))

(defun foo ()
  (fm))

Now compile the file with (compile-file "example.lisp").

Chances are high that it will not work. SBCL says:

; in: DEFUN FOO
;     (FM)
; ==>
;   #<FUNCTION (LAMBDA () :IN FM) {226680AB}>
;
; caught ERROR:
;   Objects of type FUNCTION can't be dumped into fasl files.
;
; compilation unit finished
;   caught 1 ERROR condition

Why is that?

Your function f returns a function at runtime.

Your macro m returns a function at macro expansion time. That means a literal object will be included in the code. Literal functions usually can't be dumped by the file compiler.

Next Example: function and two macros

(defun f ()
  (lambda () (format t "hello world")))

(defmacro m0 ()
  (lambda () (format t "hello world")))

(defmacro m1 ()
  `(lambda () (format t "hello world")))

(defun foo ()
  (list
    (f)         ; returns a function at runtime

    (m0)        ; a literal function, created at macro expansion time
                ;   thus can't be dumped by a file compiler

    (m1)        ; a function form, (function (lambda () ...))
  ))

Examples in REPL, with variables

Now let's look with variables:

(defun f (a)
  (lambda (b) (list a b)))   ; A is a lexical reference to above A

(defmacro m0 (a)
  (lambda (b) (list a b)))   ; A is a lexical reference to above A (!)

(defmacro m1 (a)             ; A is unused
  `(lambda (b) (list a b)))  ; A is not a reference to above A (!)

now at the REPL:

* (defun foo (c)
    (list

     (ignore-errors (funcall (f  c) 2))
     (ignore-errors (funcall (m0 c) 2))
     (ignore-errors (funcall (m1 c) 2))

    ))
; in: DEFUN FOO
;     (M1 C)
; --> LAMBDA FUNCTION
; ==>
;   (LIST A B)
;
; caught WARNING:
;   undefined variable: COMMON-LISP-USER::A
;
; compilation unit finished
;   Undefined variable:
;     A
;   caught 1 WARNING condition

* (foo 3)
((3 2)    ; <- runtime values
 (C 2)    ; <- C is source code
 NIL)     ; <- error, since A is undefined


问:
Firebase null object reference "long java.lang.Long.longValue()"
I'm creating an app that has different user levels (e.g admin, general user). Depending on the level of the user, a different activity will be launched. 1 is admin and 2 is a general user. The AdminMenuActivity launches by the MenuActivity won't.
The error I'm getting is as follows.

java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference at com.example.login.MainActivity$1.onDataChange(MainActivity.java:63)

I've been working on this for the past few days and I can't solve the problem. The code and database are as follows.

Code

```<code>public void selectUser(){

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference uidRef = rootRef.child("Users").child(uid);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

                if (dataSnapshot.child("role").getValue(Long.class) == 1) {
                    startActivity(new Intent(MainActivity.this , AdminMenuActivity.class));
                }
                else if (dataSnapshot.child("role").getValue(Long.class) == 2) {
                    startActivity(new Intent(MainActivity.this , MenuActivity.class));
                }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            throw databaseError.toException();

        }
    };
    uidRef.addListenerForSingleValueEvent(valueEventListener);

}
</code>```

Updated Database

{     "Users" : {
    "H7BKqKwLGTP0qTlL1p2JqFezjWu2" : {
      "email" : "hello@hotmail.com",
      "preference" : "rugby",
      "role" : 2
    },
    "WSBNdlu7ngbyMo2jILR2qE1ZUR32" : {
      "email" : "1234@gmail.com",
      "preference" : "rugby",
      "role" : 1
    }
  },
  "roles" : {
    "uid1" : "admin",
    "uid2" : "general"
  }
}```

答: getValue(Long.class) is returning null, which means there is no data at the location of the database that you're looking for.  You're going to have to check for this case and decide what to do when your query doesn't find what you're looking for.

Body:
I'm creating an app that has different user levels (e.g admin, general user). Depending on the level of the user, a different activity will be launched. 1 is admin and 2 is a general user. The AdminMenuActivity launches by the MenuActivity won't.
The error I'm getting is as follows.

java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference at com.example.login.MainActivity$1.onDataChange(MainActivity.java:63)

I've been working on this for the past few days and I can't solve the problem. The code and database are as follows.

Code

public void selectUser(){

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference uidRef = rootRef.child("Users").child(uid);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

                if (dataSnapshot.child("role").getValue(Long.class) == 1) {
                    startActivity(new Intent(MainActivity.this , AdminMenuActivity.class));
                }
                else if (dataSnapshot.child("role").getValue(Long.class) == 2) {
                    startActivity(new Intent(MainActivity.this , MenuActivity.class));
                }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            throw databaseError.toException();

        }
    };
    uidRef.addListenerForSingleValueEvent(valueEventListener);

}

Updated Database

{     "Users" : {
    "H7BKqKwLGTP0qTlL1p2JqFezjWu2" : {
      "email" : "hello@hotmail.com",
      "preference" : "rugby",
      "role" : 2
    },
    "WSBNdlu7ngbyMo2jILR2qE1ZUR32" : {
      "email" : "1234@gmail.com",
      "preference" : "rugby",
      "role" : 1
    }
  },
  "roles" : {
    "uid1" : "admin",
    "uid2" : "general"
  }
}


问:
Measuring running time of program with clock
We are studying the performance of various sorting algorithms and implemented our version of mergesort. We are trying to measure the running time with different input, but when we run the main() program shown below, we are getting different time results.

For example, clock() function output below can show 30 seconds with large input, but when we use the actual timer using our phones, the main program takes about 2 minutes.

What are we missing here? Are we not using the clock() function in a right way? Why is there such a big difference (1.5 minutes)?

Thank you

int n;
cout << "Enter n - lenght of array" << endl;
cin >> n;

vector<int> v(n);

for(int i = 0; i < n; ++i)
{
    v[i] = i;
}

auto rng = default_random_engine {};
std::shuffle(std::begin(v), std::end(v), rng);

clock_t begin = clock();

sort(v);

cout << "done";

clock_t end = clock();

cout <<"total time : " << (double)(end-begin) / CLOCKS_PER_SEC<<endl;

return 0;
```

答:
I ran your code by replacing the sort function with the std::sort, for n=5000000 it showed 11.744s then I moved the line clock_t begin = clock(); before the declaration of vector v and the time was 13.818s

So it seems memory allocation, O(N) initialization and shuffling can take a good amount of time and if you choose a much bigger number for n, depending on the efficiency of your sort function for a random inputset, initialization can take more time than the sort.


问:
Kivy, using functions and getting random info to textinput and random image?
I think I am lost for solution. I didn't get how works the function with .kv pages.
My  sample codes are below. Problem is when I clicked to "Good Luck" button I get an error such as "AttributeError: 'Button' object has no attribute 'app'" I tried replace my function lines to different places such as under class but keep get different errors, Am I missing something obvious or just my whole way is wrong?

main.py

```<code># -*- coding: utf8 -*-
from trakt.users import User
import random
import imdb
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
import kivy.app
kivy.require('1.9.1')

moviesDB = imdb.IMDb()
myuser = User(str('lunedor'))
watchlist = myuser.watchlist_movies

def dataget():
    global myline
    myline = str(random.choice(watchlist))[9:1000]
    movies = moviesDB.search_movie(str(myline))
    id = movies[0].getID()
    global movie
    movie = moviesDB.get_movie(id)
    global posterurl
    posterurl = movie["full-size cover url"]
    global title
    title = movie['title']
    global year
    year = movie["year"]
    global rating
    rating = movie["rating"]
    global runtime
    runtimes = movie["runtimes"]
    runtime = ' '.join(map(str, runtimes))
    global directStr
    directors = movie["directors"]
    directStr = ' '.join(map(str, directors))
    global writerStr
    writers = movie["writers"]
    writerStr = ', '.join(map(str, writers))
    global casting
    casting = movie["cast"]
    global actors
    actors = ', '.join(map(str, casting))
    global summary
    summary = movie["plot outline"]
    genres = movie["genres"]
    global genre
    genre = ', '.join(map(str, genres))
    print(movie)
    print(id)
    posterurl = movie["full-size cover url"]
    showline1 = title + "\n" + str(year) + " - " + str(rating) + "\n" + str(runtime) + " minutes" + " - " + genre
    showline2 = "Director: " + directStr + "\n" + "\n" + "Writers: " + writerStr
    showline3 = "Cast: " + actors
    showline4 = "Summary: " + "\n" + str(summary)

class RootWidget(GridLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
    try:
        dataget()
    except:
        print('Error')
        dataget()

    posterurl = movie["full-size cover url"]
    showline1 = title + "\n" + str(year) + " - " + str(rating) + "\n" + str(runtime) + " minutes" + " - " + genre
    showline2 = "Director: " + directStr + "\n" + "\n" + "Writers: " + writerStr
    showline3 = "Cast: " + actors
    showline4 = "Summary: " + "\n" + str(summary)

class MyApp(App):
    def build(self):
        return RootWidget()

    def clk(self):
        try:
            dataget()
        except:
            print('Error')
            dataget()

    def clk2(self):
        exit()

if __name__ == '__main__':
    App=MyApp()
    App.run()
</code>```

My.kv

```<code><RootWidget>:
    cols: 2
    rows: 1
    orientation: 'horizontal'
    GridLayout:
        cols: 1
        rows: 1
        orientation: 'horizontal'
        AsyncImage:
            id: poster
            source: root.posterurl
            nocache: True
    GridLayout:
        cols: 1
        rows: 5
        orientation: 'vertical'
        spacing: 10
        Label:
            text: root.showline1
            markup: True
            bold: True
            size: self.texture_size
            halign: 'center'
            valign: 'middle'
            id: self.lbl
        TextInput:
            text: root.showline2
            id: self.lbl2
        TextInput:
            text: root.showline3
            id: self.lbl3
            multiline: True
        TextInput:
            text: root.showline4
            id: self.lbl4
            multiline: True
        BoxLayout:
            cols: 2
            rows: 1
            spacing: 5
            padding: 50, 10, 10, 10
            size_hint_max_y: 40
            orientation: 'horizontal'
            Button:
                text: "Good Luck!"
                font_size: 14
                size_hint: None, None
                size: 95, 30
                on_press: root.app.clk()
            Button:
                text: "Exit"
                font_size: 14
                size_hint: None, None
                size: 75, 30
                on_press: root.app.clk2()
</code>```

solved version:

```<code># -*- coding: utf8 -*-
from trakt.users import User
import random
import imdb
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import StringProperty, ObjectProperty
import kivy.app
kivy.require('1.9.1')

moviesDB = imdb.IMDb()
myuser = User(str('lunedor'))
watchlist = myuser.watchlist_movies

def dataget():
    global myline
    myline = str(random.choice(watchlist))[9:1000]
    movies = moviesDB.search_movie(str(myline))
    id = movies[0].getID()
    global movie
    movie = moviesDB.get_movie(id)
    global posterurl
    posterurl = movie["full-size cover url"]
    global title
    title = movie['title']
    global year
    year = movie["year"]
    global rating
    rating = movie["rating"]
    global runtime
    runtimes = movie["runtimes"]
    runtime = ' '.join(map(str, runtimes))
    global directStr
    directors = movie["directors"]
    directStr = ' '.join(map(str, directors))
    global writerStr
    writers = movie["writers"]
    writerStr = ', '.join(map(str, writers))
    global casting
    casting = movie["cast"]
    global actors
    actors = ', '.join(map(str, casting))
    global summary
    summary = movie["plot outline"]
    genres = movie["genres"]
    global genre
    genre = ', '.join(map(str, genres))
    print(movie)
    print(id)

class RootWidget(GridLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
    try:
        dataget()
    except:
        print('Error')
        dataget()

    posterurl = ObjectProperty()
    showline1 = StringProperty()
    showline2 = StringProperty()
    showline3 = StringProperty()
    showline4 = StringProperty()

    # make a function to be able to call it
    def update_values(self):
        self.posterurl = movie["full-size cover url"]
        self.showline1 = title + "\n" + str(year) + " - " + str(rating) + "\n" + str(runtime) + " minutes" + " - " + genre
        self.showline2 = "Director: " + directStr + "\n" + "\n" + "Writers: " + writerStr
        self.showline3 = "Cast: " + actors
        self.showline4 = "Summary: " + "\n" + str(summary)

class MyApp(App):
    def build(self):
        # you will need that object later so put in into variable
        self.rw = RootWidget()
        # call update function
        self.rw.update_values()
        return self.rw

    def clk(self):
        try:
            dataget()
            # after you get new values update the variables connected to widgets
            self.rw.update_values()
        except:
            print('Error')
            dataget()

    def clk2(self):
        exit()

if __name__ == '__main__':
    App=MyApp()
    App.run()
</code>```

答:
You should use root or app, not both together. In your case it would be app because your functions are in App class:

```<code>on_press: app.clk()
</code>```

Of course it won't update by itself, you update global variables but don't update local ones. Try this:

```<code>class RootWidget(GridLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
    try:
        dataget()
    except:
        print('Error')
        dataget()

    # make a function to be able to call it
    def update_values(self):
        self.posterurl = movie["full-size cover url"]
        self.showline1 = title + "\n" + str(year) + " - " + str(rating) + "\n" + str(runtime) + " minutes" + " - " + genre
        self.showline2 = "Director: " + directStr + "\n" + "\n" + "Writers: " + writerStr
        self.showline3 = "Cast: " + actors
        self.showline4 = "Summary: " + "\n" + str(summary)

class MyApp(App):
    def build(self):
        # you will need that object later so put in into variable
        self.rw = RootWidget()
        # call update function
        self.rw.update_values()
        return self.rw

    def clk(self):
        try:
            dataget()
            # after you get new values update the variables connected to widgets
            self.rw.update_values()
        except:
            print('Error')
            dataget()
</code>```

This should work. If it won't I'll tell you the hard way.

Body:
I think I am lost for solution. I didn't get how works the function with .kv pages.
My  sample codes are below. Problem is when I clicked to "Good Luck" button I get an error such as "AttributeError: 'Button' object has no attribute 'app'" I tried replace my function lines to different places such as under class but keep get different errors, Am I missing something obvious or just my whole way is wrong?

main.py

# -*- coding: utf8 -*-
from trakt.users import User
import random
import imdb
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
import kivy.app
kivy.require('1.9.1')

moviesDB = imdb.IMDb()
myuser = User(str('lunedor'))
watchlist = myuser.watchlist_movies

def dataget():
    global myline
    myline = str(random.choice(watchlist))[9:1000]
    movies = moviesDB.search_movie(str(myline))
    id = movies[0].getID()
    global movie
    movie = moviesDB.get_movie(id)
    global posterurl
    posterurl = movie["full-size cover url"]
    global title
    title = movie['title']
    global year
    year = movie["year"]
    global rating
    rating = movie["rating"]
    global runtime
    runtimes = movie["runtimes"]
    runtime = ' '.join(map(str, runtimes))
    global directStr
    directors = movie["directors"]
    directStr = ' '.join(map(str, directors))
    global writerStr
    writers = movie["writers"]
    writerStr = ', '.join(map(str, writers))
    global casting
    casting = movie["cast"]
    global actors
    actors = ', '.join(map(str, casting))
    global summary
    summary = movie["plot outline"]
    genres = movie["genres"]
    global genre
    genre = ', '.join(map(str, genres))
    print(movie)
    print(id)
    posterurl = movie["full-size cover url"]
    showline1 = title + "\n" + str(year) + " - " + str(rating) + "\n" + str(runtime) + " minutes" + " - " + genre
    showline2 = "Director: " + directStr + "\n" + "\n" + "Writers: " + writerStr
    showline3 = "Cast: " + actors
    showline4 = "Summary: " + "\n" + str(summary)

class RootWidget(GridLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
    try:
        dataget()
    except:
        print('Error')
        dataget()

    posterurl = movie["full-size cover url"]
    showline1 = title + "\n" + str(year) + " - " + str(rating) + "\n" + str(runtime) + " minutes" + " - " + genre
    showline2 = "Director: " + directStr + "\n" + "\n" + "Writers: " + writerStr
    showline3 = "Cast: " + actors
    showline4 = "Summary: " + "\n" + str(summary)

class MyApp(App):
    def build(self):
        return RootWidget()

    def clk(self):
        try:
            dataget()
        except:
            print('Error')
            dataget()

    def clk2(self):
        exit()

if __name__ == '__main__':
    App=MyApp()
    App.run()

My.kv

<RootWidget>:
    cols: 2
    rows: 1
    orientation: 'horizontal'
    GridLayout:
        cols: 1
        rows: 1
        orientation: 'horizontal'
        AsyncImage:
            id: poster
            source: root.posterurl
            nocache: True
    GridLayout:
        cols: 1
        rows: 5
        orientation: 'vertical'
        spacing: 10
        Label:
            text: root.showline1
            markup: True
            bold: True
            size: self.texture_size
            halign: 'center'
            valign: 'middle'
            id: self.lbl
        TextInput:
            text: root.showline2
            id: self.lbl2
        TextInput:
            text: root.showline3
            id: self.lbl3
            multiline: True
        TextInput:
            text: root.showline4
            id: self.lbl4
            multiline: True
        BoxLayout:
            cols: 2
            rows: 1
            spacing: 5
            padding: 50, 10, 10, 10
            size_hint_max_y: 40
            orientation: 'horizontal'
            Button:
                text: "Good Luck!"
                font_size: 14
                size_hint: None, None
                size: 95, 30
                on_press: root.app.clk()
            Button:
                text: "Exit"
                font_size: 14
                size_hint: None, None
                size: 75, 30
                on_press: root.app.clk2()

solved version:

# -*- coding: utf8 -*-
from trakt.users import User
import random
import imdb
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import StringProperty, ObjectProperty
import kivy.app
kivy.require('1.9.1')

moviesDB = imdb.IMDb()
myuser = User(str('lunedor'))
watchlist = myuser.watchlist_movies

def dataget():
    global myline
    myline = str(random.choice(watchlist))[9:1000]
    movies = moviesDB.search_movie(str(myline))
    id = movies[0].getID()
    global movie
    movie = moviesDB.get_movie(id)
    global posterurl
    posterurl = movie["full-size cover url"]
    global title
    title = movie['title']
    global year
    year = movie["year"]
    global rating
    rating = movie["rating"]
    global runtime
    runtimes = movie["runtimes"]
    runtime = ' '.join(map(str, runtimes))
    global directStr
    directors = movie["directors"]
    directStr = ' '.join(map(str, directors))
    global writerStr
    writers = movie["writers"]
    writerStr = ', '.join(map(str, writers))
    global casting
    casting = movie["cast"]
    global actors
    actors = ', '.join(map(str, casting))
    global summary
    summary = movie["plot outline"]
    genres = movie["genres"]
    global genre
    genre = ', '.join(map(str, genres))
    print(movie)
    print(id)

class RootWidget(GridLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
    try:
        dataget()
    except:
        print('Error')
        dataget()

    posterurl = ObjectProperty()
    showline1 = StringProperty()
    showline2 = StringProperty()
    showline3 = StringProperty()
    showline4 = StringProperty()

    # make a function to be able to call it
    def update_values(self):
        self.posterurl = movie["full-size cover url"]
        self.showline1 = title + "\n" + str(year) + " - " + str(rating) + "\n" + str(runtime) + " minutes" + " - " + genre
        self.showline2 = "Director: " + directStr + "\n" + "\n" + "Writers: " + writerStr
        self.showline3 = "Cast: " + actors
        self.showline4 = "Summary: " + "\n" + str(summary)

class MyApp(App):
    def build(self):
        # you will need that object later so put in into variable
        self.rw = RootWidget()
        # call update function
        self.rw.update_values()
        return self.rw

    def clk(self):
        try:
            dataget()
            # after you get new values update the variables connected to widgets
            self.rw.update_values()
        except:
            print('Error')
            dataget()

    def clk2(self):
        exit()

if __name__ == '__main__':
    App=MyApp()
    App.run()

Body:
You should use root or app, not both together. In your case it would be app because your functions are in App class:

on_press: app.clk()

Of course it won't update by itself, you update global variables but don't update local ones. Try this:

class RootWidget(GridLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
    try:
        dataget()
    except:
        print('Error')
        dataget()

    # make a function to be able to call it
    def update_values(self):
        self.posterurl = movie["full-size cover url"]
        self.showline1 = title + "\n" + str(year) + " - " + str(rating) + "\n" + str(runtime) + " minutes" + " - " + genre
        self.showline2 = "Director: " + directStr + "\n" + "\n" + "Writers: " + writerStr
        self.showline3 = "Cast: " + actors
        self.showline4 = "Summary: " + "\n" + str(summary)

class MyApp(App):
    def build(self):
        # you will need that object later so put in into variable
        self.rw = RootWidget()
        # call update function
        self.rw.update_values()
        return self.rw

    def clk(self):
        try:
            dataget()
            # after you get new values update the variables connected to widgets
            self.rw.update_values()
        except:
            print('Error')
            dataget()

This should work. If it won't I'll tell you the hard way.


问:
How to retrieving data as customized format

I retrieved some data as below (image 01).

i used this query:

```<code>SELECT TOP (3) no, co, cdate, year
FROM main_backup
WHERE (no = 41505)
ORDER BY cdate DESC
</code>```

But I want that, like this type as below (image 02)

答:
You can use conditional aggregation and window functions:</p>

```<code>select no,
       max(case when seqnum = 1 then total end) as total_1,
       max(case when seqnum = 1 then cdate end) as date_1,
       max(case when seqnum = 2 then total end) as total_2,
       max(case when seqnum = 2 then cdate end) as date_2,
       max(case when seqnum = 3 then total end) as total_3,
       max(case when seqnum = 3 then cdate end) as date_3
from (select t.*,
             row_number() over (partition by no order by cdate desc) as seqnum
      from t
     ) t
group by no
</code>```

Body:
I retrieved some data as below (image 01).

i used this query:

SELECT TOP (3) no, co, cdate, year
FROM main_backup
WHERE (no = 41505)
ORDER BY cdate DESC

But I want that, like this type as below (image 02)

Body:
You can use conditional aggregation and window functions:

select no,
       max(case when seqnum = 1 then total end) as total_1,
       max(case when seqnum = 1 then cdate end) as date_1,
       max(case when seqnum = 2 then total end) as total_2,
       max(case when seqnum = 2 then cdate end) as date_2,
       max(case when seqnum = 3 then total end) as total_3,
       max(case when seqnum = 3 then cdate end) as date_3
from (select t.*,
             row_number() over (partition by no order by cdate desc) as seqnum
      from t
     ) t
group by no


问:
How do I group "or" in pl/sql
I have legacy sql query that selects bit masks (among other data), something like:

```<code>1
2
1
</code>```

How do I group this output like:

```<code>1 or 2 or 1
</code>```

That should be 3

答:
As of Oracle 20c, you can do bitwise aggregates using the following functions:

BIT_AND_AGG

BIT_OR_AGG

BIT_XOR_AGG

ContentLicense: CC BY-SA 3.0

Title: How do I group "or" in pl/sql

Body:
I have legacy sql query that selects bit masks (among other data), something like:

1
2
1

How do I group this output like:

1 or 2 or 1

That should be 3


问:
std::find_if gives "conditional expression of type 'void' is illegal" error
I have the following function:

```<code>float Mesh::getTerrainHeight(Vector3f playerPos) {
    auto testIterator = std::find_if(meshVerticesFloats.begin(), meshVerticesFloats.end(), [&](Vector3f pos)
    {
        //check the X axis
        if (abs(playerPos.GetX() - pos.GetX()) < playerScale + vertexScale / 1.0f) {
            //check the Z axis
            if (abs(playerPos.GetZ() - pos.GetZ()) < playerScale + vertexScale / 1.0f) {
                return;
            }
        }
    });
    if (testIterator != meshVerticesFloats.end()) {
        int testIndex = std::distance(meshVerticesFloats.begin(), testIterator);
        return meshVerticesFloats[testIndex].GetY();
    }
    else {
        return 10000.0f;//test value - no mesh vertex y value is ever 10000
    }
}
</code>```

When I run I get the following error message:

```<code>2>c:\visual_studio_2017\vc\tools\msvc\14.16.27023\include\algorithm(174): error C2451: conditional expression of type 'void' is illegal
</code>```

Is there something wrong with my std::find_if logic?

答:
The predicate should return something that can be converted to bool. More precisely (cppreference):

p - unary predicate which returns true for the required element.

The expression p(v) must be convertible to bool for every argument v of type (possibly const) VT, where VT is the value type of InputIt, regardless of value category, and must not modify v. Thus, a parameter type of VT&is not allowed, nor is VT unless for VT a move is equivalent to a copy (since C++11).

Yours returns nothing:

```<code>return;
</code>```

You probably wanted this instead:

```<code> if (abs(playerPos.GetX() - pos.GetX()) < playerScale + vertexScale / 1.0f) {
     //check the Z axis
     if (abs(playerPos.GetZ() - pos.GetZ()) < playerScale + vertexScale / 1.0f) {
         return true;
     }
 }
 return false;
</code>```

I don't know if this will give the correct result, thats up to you, but it "fixes" the error.

PS I suppose Vector3f is not your type, hence you should pass a const Vector3f& to the predicate, because std::find_if requires that a move should be equivalent to a copy when you use Vector3f as parameter for the predicate (see above).

Body:
I have the following function:

float Mesh::getTerrainHeight(Vector3f playerPos) {
    auto testIterator = std::find_if(meshVerticesFloats.begin(), meshVerticesFloats.end(), [&](Vector3f pos)
    {
        //check the X axis
        if (abs(playerPos.GetX() - pos.GetX()) < playerScale + vertexScale / 1.0f) {
            //check the Z axis
            if (abs(playerPos.GetZ() - pos.GetZ()) < playerScale + vertexScale / 1.0f) {
                return;
            }
        }
    });
    if (testIterator != meshVerticesFloats.end()) {
        int testIndex = std::distance(meshVerticesFloats.begin(), testIterator);
        return meshVerticesFloats[testIndex].GetY();
    }
    else {
        return 10000.0f;//test value - no mesh vertex y value is ever 10000
    }
}

When I run I get the following error message:

2>c:\visual_studio_2017\vc\tools\msvc\14.16.27023\include\algorithm(174): error C2451: conditional expression of type 'void' is illegal

Is there something wrong with my std::find_if logic?

Body:
The predicate should return something that can be converted to bool. More precisely (cppreference):

p - unary predicate which returns true for the required element.

The expression p(v) must be convertible to bool for every argument v of type (possibly const) VT, where VT is the value type of InputIt, regardless of value category, and must not modify v. Thus, a parameter type of VT&is not allowed, nor is VT unless for VT a move is equivalent to a copy (since C++11).

Yours returns nothing:

return;

You probably wanted this instead:

 if (abs(playerPos.GetX() - pos.GetX()) < playerScale + vertexScale / 1.0f) {
     //check the Z axis
     if (abs(playerPos.GetZ() - pos.GetZ()) < playerScale + vertexScale / 1.0f) {
         return true;
     }
 }
 return false;

I don't know if this will give the correct result, thats up to you, but it "fixes" the error.

PS I suppose Vector3f is not your type, hence you should pass a const Vector3f& to the predicate, because std::find_if requires that a move should be equivalent to a copy when you use Vector3f as parameter for the predicate (see above).


问:
Ansible Playbook issue
I am using win_choclateyfor windows application deployment, but the job keeps running I think it expecting a password to install application, so where can I declare in my Playbook ?

答: Use the expect module in your playbook. There are examples in the documentations of how to do it. </p>

Title: Ansible Playbook issue


问:
How to programmatically disable page scrolling with jQuery
Using jQuery, I would like to disable scrolling of the body:

My idea is to:

Set body{ overflow: hidden;}

Capture the current scrollTop();/scrollLeft()

Bind to the body scroll event, set scrollTop/scrollLeft to the captured value.

Is there a better way?

Update:

Please see my example, and a reason why, at http://jsbin.com/ikuma4/2/edit

I am aware someone will be thinking "why does he not just use position: fixed on the panel?".

Please do not suggest this as I have other reasons.

答:
This may or may not work for your purposes, but you can extend jScrollPane to fire other functionality before it does its scrolling. I've only just tested this a little bit, but I can confirm that you can jump in and prevent the scrolling entirely. All I did was:

Download the demo zip: http://github.com/vitch/jScrollPane/archives/master

Open the "Events" demo (events.html)

Edit it to use the non-minified script source:

Within jquery.jscrollpane.js, insert a "return;" at line 666 (auspicious line number! but in case your version differs slightly, this is the first line of the positionDragY(destY, animate) function

Fire up events.html, and you'll see a normally scrolling box which due to your coding intervention won't scroll.

You can control the entire browser's scrollbars this way (see fullpage_scroll.html).

So, presumably the next step is to add a call to some other function that goes off and does your anchoring magic, then decides whether to continue with the scroll or not. You've also got API calls to set scrollTop and scrollLeft.

If you want more help, post where you get up to!

Hope this has helped.

Body:
This may or may not work for your purposes, but you can extend jScrollPane to fire other functionality before it does its scrolling. I've only just tested this a little bit, but I can confirm that you can jump in and prevent the scrolling entirely. All I did was:

Download the demo zip: http://github.com/vitch/jScrollPane/archives/master

Open the "Events" demo (events.html)

Edit it to use the non-minified script source: <script type="text/javascript" src="script/jquery.jscrollpane.js"></script>

Within jquery.jscrollpane.js, insert a "return;" at line 666 (auspicious line number! but in case your version differs slightly, this is the first line of the positionDragY(destY, animate) function

Fire up events.html, and you'll see a normally scrolling box which due to your coding intervention won't scroll.

You can control the entire browser's scrollbars this way (see fullpage_scroll.html).

So, presumably the next step is to add a call to some other function that goes off and does your anchoring magic, then decides whether to continue with the scroll or not. You've also got API calls to set scrollTop and scrollLeft.

If you want more help, post where you get up to!

Hope this has helped.


问:
BigQuery request, generate combinations and calculate intersection
I have a table looking like this in BigQuery:

The first field is id, the second field is url.
One line represents someone (an ID) who visited a URL.
Let's say my URLs are url1, url2, url3. I would like to know how many unique IDs visited at least once the following tuples of URLs:

```<code>(url1, url2)
(url1, url3)
(url2, url3)
(url1, url2, url3)
</code>```

Basically, get the number of ids linked to all combinations of url from the urls list, but only when the number of urls visited is not 0.
I expect it to give a very big output for a big list of urls. Is there a request I can write in BigQuery that would help with this problem ?
May be an operator that can generate all combinations for my input ?

Thank you for your help

答:
May be an operator that can generate all combinations for my input ?

Yes, you can use ML.NGRAMS function as in below simplified example

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 id, 'url1' url UNION ALL
  SELECT 2, 'url2' UNION ALL
  SELECT 3, 'url2' UNION ALL
  SELECT 2, 'url1' UNION ALL
  SELECT 3, 'url2' UNION ALL
  SELECT 2, 'url3'
)
SELECT tuple FROM (
  SELECT ARRAY_AGG(DISTINCT url) urls
  FROM `project.dataset.table`
), UNNEST(ML.NGRAMS(urls, [1,3], ',')) tuple
</code>```

with output

```<code>Row tuple
1   url1
2   url1,url2
3   url1,url2,url3
4   url2
5   url2,url3
6   url3
</code>```

which you can then use as a input into final calculation

Body:
I have a table looking like this in BigQuery:

The first field is id, the second field is url.
One line represents someone (an ID) who visited a URL.
Let's say my URLs are url1, url2, url3. I would like to know how many unique IDs visited at least once the following tuples of URLs:

(url1, url2)
(url1, url3)
(url2, url3)
(url1, url2, url3)

Basically, get the number of ids linked to all combinations of url from the urls list, but only when the number of urls visited is not 0.
I expect it to give a very big output for a big list of urls. Is there a request I can write in BigQuery that would help with this problem ?
May be an operator that can generate all combinations for my input ?

Thank you for your help

Body:
May be an operator that can generate all combinations for my input ?

Yes, you can use ML.NGRAMS function as in below simplified example

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 id, 'url1' url UNION ALL
  SELECT 2, 'url2' UNION ALL
  SELECT 3, 'url2' UNION ALL
  SELECT 2, 'url1' UNION ALL
  SELECT 3, 'url2' UNION ALL
  SELECT 2, 'url3'
)
SELECT tuple FROM (
  SELECT ARRAY_AGG(DISTINCT url) urls
  FROM `project.dataset.table`
), UNNEST(ML.NGRAMS(urls, [1,3], ',')) tuple

with output

Row tuple
1   url1
2   url1,url2
3   url1,url2,url3
4   url2
5   url2,url3
6   url3

which you can then use as a input into final calculation


问:
Efficiently removing `NAs` in repeated measures designs using `tidyverse`
This is not so much question about how to do something but more about how to do it efficiently. In particular, I would like to drop NAs in a repeated measures design in such a way that each group has all complete observations.

In the bugs_long dataframe below, the same participant takes part in four condition and report their desire to kill bugs in each condition. Now if I wanted to carry out some repeated measures analysis with this dataset, this typically doesn't work in the long format because a different number of observations are found for each group after the pairwise exclusion of NAs. So the final dataframe should leave out the following five subjects.

# setup
set.seed(123)
library(ipmisc)
library(tidyverse)

# looking at the NAs
dplyr::filter(bugs_long, is.na(desire))
#> # A tibble: 5 x 6
#>   subject gender region        education condition desire
#>     <int> <fct>  <fct>         <fct>     <chr>      <dbl>
#> 1       2 Female North America advance   LDHF          NA
#> 2      80 Female North America less      LDHF          NA
#> 3      42 Female North America high      HDLF          NA
#> 4      64 Female Europe        some      HDLF          NA
#> 5      10 Female Other         high      HDHF          NA
```

<p>Here is the current roundabout way I am hacking this and getting it to work:</p>

<pre class="lang-r prettyprint-override"><code># figuring out the number of levels in the grouping factor
x_n_levels <- nlevels(as.factor(bugs_long$condition))[[1]]

# removing observations that don't have all repeated values
df <-
  bugs_long %>%
  filter(!is.na(condition)) %>%
  group_by(condition) %>%
  mutate(id = dplyr::row_number()) %>%
  ungroup(.) %>%
  filter(!is.na(desire)) %>%
  group_by(id) %>%
  mutate(n = dplyr::n()) %>%
  ungroup(.) %>%
  filter(n == x_n_levels) %>%
  select(-n)

# did this work? yes
df %>%
  group_by(condition) %>%
  count()
#> # A tibble: 4 x 2
#> # Groups:   condition [4]
#>   condition     n
#>   <chr>     <int>
#> 1 HDHF         88
#> 2 HDLF         88
#> 3 LDHF         88
#> 4 LDLF         88
</code>```

But I would be surprised if the tidyverse (dplyr + tidyr) doesn't have a more efficient way to achieve this and I would really appreciate it if anyone else has a better refactoring this.

答:
You're actually making this much more complicated than it needs to be. Once you find the cases to exclude, it's just a simple task of removing rows in your data that match those subjects, i.e. an anti-join. Some useful discussions here and here.

set.seed(123)
library(ipmisc)
library(dplyr)

exclude <- filter(bugs_long, is.na(desire))
full_cases <- bugs_long %>%
  anti_join(exclude, by = "subject")
```

<p>Or do the filtering and anti-joining in one go, similar to what you might do in SQL:</p>

<pre class="lang-r prettyprint-override"><code>bugs_long %>%
  anti_join(filter(., is.na(desire)), by = "subject")
</code>```

For either way, the number of cases kept checks out:

count(full_cases, condition)
#> # A tibble: 4 x 2
#>   condition     n
#>   <chr>     <int>
#> 1 HDHF         88
#> 2 HDLF         88
#> 3 LDHF         88
#> 4 LDLF         88
```

Body:
This is not so much question about how to do something but more about how to do it efficiently. In particular, I would like to drop NAs in a repeated measures design in such a way that each group has all complete observations.

In the bugs_long dataframe below, the same participant takes part in four condition and report their desire to kill bugs in each condition. Now if I wanted to carry out some repeated measures analysis with this dataset, this typically doesn't work in the long format because a different number of observations are found for each group after the pairwise exclusion of NAs. So the final dataframe should leave out the following five subjects.

# setup
set.seed(123)
library(ipmisc)
library(tidyverse)

# looking at the NAs
dplyr::filter(bugs_long, is.na(desire))
#> # A tibble: 5 x 6
#>   subject gender region        education condition desire
#>     <int> <fct>  <fct>         <fct>     <chr>      <dbl>
#> 1       2 Female North America advance   LDHF          NA
#> 2      80 Female North America less      LDHF          NA
#> 3      42 Female North America high      HDLF          NA
#> 4      64 Female Europe        some      HDLF          NA
#> 5      10 Female Other         high      HDHF          NA

Here is the current roundabout way I am hacking this and getting it to work:

# figuring out the number of levels in the grouping factor
x_n_levels <- nlevels(as.factor(bugs_long$condition))[[1]]

# removing observations that don't have all repeated values
df <-
  bugs_long %>%
  filter(!is.na(condition)) %>%
  group_by(condition) %>%
  mutate(id = dplyr::row_number()) %>%
  ungroup(.) %>%
  filter(!is.na(desire)) %>%
  group_by(id) %>%
  mutate(n = dplyr::n()) %>%
  ungroup(.) %>%
  filter(n == x_n_levels) %>%
  select(-n)

# did this work? yes
df %>%
  group_by(condition) %>%
  count()
#> # A tibble: 4 x 2
#> # Groups:   condition [4]
#>   condition     n
#>   <chr>     <int>
#> 1 HDHF         88
#> 2 HDLF         88
#> 3 LDHF         88
#> 4 LDLF         88

But I would be surprised if the tidyverse (dplyr + tidyr) doesn't have a more efficient way to achieve this and I would really appreciate it if anyone else has a better refactoring this.

Body:
You're actually making this much more complicated than it needs to be. Once you find the cases to exclude, it's just a simple task of removing rows in your data that match those subjects, i.e. an anti-join. Some useful discussions here and here.

set.seed(123)
library(ipmisc)
library(dplyr)

exclude <- filter(bugs_long, is.na(desire))
full_cases <- bugs_long %>%
  anti_join(exclude, by = "subject")

Or do the filtering and anti-joining in one go, similar to what you might do in SQL:

bugs_long %>%
  anti_join(filter(., is.na(desire)), by = "subject")

For either way, the number of cases kept checks out:

count(full_cases, condition)
#> # A tibble: 4 x 2
#>   condition     n
#>   <chr>     <int>
#> 1 HDHF         88
#> 2 HDLF         88
#> 3 LDHF         88
#> 4 LDLF         88


问:
Query plan or execution plan specifies cost in percentagewise. What is the percentagewise according to?
What is the cost, percentage-wise, in query plan execution?</p>

```<code>SELECT a.au_fname + ''+ a.au_lname AS 'Author Name',
t.title
FROM authors a INNER JOIN titleauthor ta
ON (a.au_id = ta.au_id) INNER JOIN titles t
ON (ta.title_id = t.title_id)

select * from authors
</code>```

答:
In SQL Server:

Cost percentage is the relative percentage to the whole batch of queries executing. If you are executing a single query, the percentage for that would be always 100%.

Each query in the batch that is
  analyzed is displayed, including the
  cost of each query as a percentage of
  the total cost of the batch.

http://msdn.microsoft.com/en-us/library/ms178071.aspx

Body:
What is the cost, percentage-wise, in query plan execution?

SELECT a.au_fname + ''+ a.au_lname AS 'Author Name',
t.title
FROM authors a INNER JOIN titleauthor ta
ON (a.au_id = ta.au_id) INNER JOIN titles t
ON (ta.title_id = t.title_id)

select * from authors


问:
How to use composer with phpbrew?
I installed phpbrew to use php 5.4 in Ubuntu 14.04. It works fine, except when I try to use composer, which ignores phpbrew and installs dependencies related to php 5.5.

Is there a way to force composer to be compatible with phpbrew config?
I trying to add: php: "5.4" in my composer.json, but it says that this requirement is not possible with my php version.

答: I was getting an error as app is not a valid command. To fix this, I used brew install composer.

Title: How to use composer with phpbrew?


问:
String to enum in C++
Is there a way to associate a string from a text file with an enum value?

The problem is: I have a few enum values stored as string in a text file which I read on the fly on meeting some condition... Now I want to assign the read value to an enum.

What is the most effective way to do so?  It doesn't need to be the simplest approach.

答:
Using C++ reflection library from here: https://github.com/tapika/cppreflect

You can - include library like this:

```<code>#include "cppreflect/cppreflect.h"
</code>```

Basic usage:

Declare enumeration:

```<code>DECLARE_ENUM( enumName,
    // Prefix for all enums, "" if no prefix used.
    "myenum_",

    myenum_enumValue1,
    myenum_enumValue2,
    myenum_enumValue3 = 5,

    // comment
    myenum_enumValue4
);
</code>```

Conversion logic:

From enumeration to string:

```<code>printf( EnumToString(myenum_enumValue3).c_str() );

=> "enumValue3"
</code>```

From string to enumeration:

```<code>enumName value;

if( !StringToEnum("enumValue4", value) )
    printf("Conversion failed...");

=>

value == myenum_enumValue4
</code>```

Main / core functionality resides in here:

https://github.com/tapika/cppreflect/blob/master/cppreflect/enumreflect.h

Title: String to enum in C++

Body:
Using C++ reflection library from here: https://github.com/tapika/cppreflect

You can - include library like this:

#include "cppreflect/cppreflect.h"

Basic usage:

Declare enumeration:

DECLARE_ENUM( enumName,
    // Prefix for all enums, "" if no prefix used.
    "myenum_",

    myenum_enumValue1,
    myenum_enumValue2,
    myenum_enumValue3 = 5,

    // comment
    myenum_enumValue4
);

Conversion logic:

From enumeration to string:

printf( EnumToString(myenum_enumValue3).c_str() );

=> "enumValue3"

From string to enumeration:

enumName value;

if( !StringToEnum("enumValue4", value) )
    printf("Conversion failed...");

=>

value == myenum_enumValue4

Main / core functionality resides in here:

https://github.com/tapika/cppreflect/blob/master/cppreflect/enumreflect.h


问:
dotenv file is not loading environment variables
I have .env file at root folder file

```<code>NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user
</code>```

And server.js file in the root/app/config/server.js folder.
The first line of server.js file is

require('dotenv').config();

I also tried following:

require('dotenv').config({path: '../.env'});

require('dotenv').config({path: '../../.env'});

However, my env variable are not loaded when I run the server.js file
from command prompt

node root/app/config/server.js

If I use the visual studio and press F5, it loads!!

I'm not sure what I'm doing wrong, what I'm missing.
Any suggestion is highly appreciate. Thanks.

答: One time I have got the same problem. Dotenv did not load .env file. I tried to fix this problem with a path config, to put .env file in a root folder, to put .env in the folder where the file is running and nothing helps me. Then I just trashed Node_modules folder, reinstall all dependencies and it works correctly</p>

Body:
I have .env file at root folder file

NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user

And server.js file in the root/app/config/server.js folder.
The first line of server.js file is

require('dotenv').config();

I also tried following:

require('dotenv').config({path: '../.env'});

require('dotenv').config({path: '../../.env'});

However, my env variable are not loaded when I run the server.js file
from command prompt

node root/app/config/server.js

If I use the visual studio and press F5, it loads!!

I'm not sure what I'm doing wrong, what I'm missing.
Any suggestion is highly appreciate. Thanks.


问:
TFF: How define tff.simulation.ClientData.from_clients_and_fn Function?
In the federated learning context, One such classmethod that should work would be tff.simulation.ClientData.from_clients_and_fn. Here, if I pass a list of client_ids and a function which returns the appropriate dataset when given a client id, you will have your hands on a fully functional ClientData.

I think here, an approach for defining the function I may use is to construct a Python dict which maps client IDs to tf.data.Dataset objects--you could then define a function which takes a client id, looks up the dataset in the dict, and returns the dataset.
So I define function as below but I think it is wrong, what do you think?

```<code>list = ["0","1","2"]
tab = {"0":ds, "1":ds, "2":ds}
def create_tf_dataset_for_client_fn(id):
    return ds

source = tff.simulation.ClientData.from_clients_and_fn(list, create_tf_dataset_for_client_fn)
</code>```

I suppose here that the 4 clients have the same dataset :'ds'

答:
Creating a dict of (client_id, dataset) key-value pairs is a reasonable way to set up a tff.simulation.ClientData. Indeed, the code in the question will result in all clients have the same dataset since ds is return for all values of parameter id. One thing to watch out in pre-constructing a dict of datasets is that it may require loading the entire contents of the data into memory (may fail for large datasets).

Alternatively, constructing the dataset on-demand could reduce memory usage. One example might be to have a dict of (client_id, file path) key-value pairs. Something like:

dataset_paths = {
  'client_0': '/tmp/A.txt',
  'client_1': '/tmp/B.txt',
  'client_2': '/tmp/C.txt',
}

def create_tf_dataset_for_client_fn(id):
   path = dataset_paths.get(id)
   if path is None:
     raise ValueError(f'No dataset for client {id}')
   return tf.data.Dataset.TextLineDataset(path)

source = tff.simulation.ClientData.from_clients_and_fn(
  dataset_paths.keys(), create_tf_dataset_for_client_fn)
```

This is similar to the approach used in tff.simulation.FilePerUserClientData. It may be useful to look at the code of that class as an example.

Body:
In the federated learning context, One such classmethod that should work would be tff.simulation.ClientData.from_clients_and_fn. Here, if I pass a list of client_ids and a function which returns the appropriate dataset when given a client id, you will have your hands on a fully functional ClientData.

I think here, an approach for defining the function I may use is to construct a Python dict which maps client IDs to tf.data.Dataset objects--you could then define a function which takes a client id, looks up the dataset in the dict, and returns the dataset.
So I define function as below but I think it is wrong, what do you think?

list = ["0","1","2"]
tab = {"0":ds, "1":ds, "2":ds}
def create_tf_dataset_for_client_fn(id):
    return ds

source = tff.simulation.ClientData.from_clients_and_fn(list, create_tf_dataset_for_client_fn)

I suppose here that the 4 clients have the same dataset :'ds'

Body:
Creating a dict of (client_id, dataset) key-value pairs is a reasonable way to set up a tff.simulation.ClientData. Indeed, the code in the question will result in all clients have the same dataset since ds is return for all values of parameter id. One thing to watch out in pre-constructing a dict of datasets is that it may require loading the entire contents of the data into memory (may fail for large datasets).

Alternatively, constructing the dataset on-demand could reduce memory usage. One example might be to have a dict of (client_id, file path) key-value pairs. Something like:

dataset_paths = {
  'client_0': '/tmp/A.txt',
  'client_1': '/tmp/B.txt',
  'client_2': '/tmp/C.txt',
}

def create_tf_dataset_for_client_fn(id):
   path = dataset_paths.get(id)
   if path is None:
     raise ValueError(f'No dataset for client {id}')
   return tf.data.Dataset.TextLineDataset(path)

source = tff.simulation.ClientData.from_clients_and_fn(
  dataset_paths.keys(), create_tf_dataset_for_client_fn)

This is similar to the approach used in tff.simulation.FilePerUserClientData. It may be useful to look at the code of that class as an example.


问:
C# How to populate ComboBox with Strings from RichTextBox if criteria met
I am trying to populate a combo box with lines from a rich text box.
But only if the last 6 characters of a line in the rich text box contains the string "device".
I do not know the amount of lines in the rich text box and the amount of lines that contain the string "device", until runtime.

Let’s say there are 6 lines in the combo box and 2 items that contain the string "device".
But both numbers can and do change during runtime.

int IntCountLines is equal to the amount of lines in the rich text box.
int IntNumberOfDevices is equal to the number of lines that contain the string "device" (in the last 6 characters) in the rich text box.

The first line [0] in the rich text box is always ignored.
So, starting at line [1].

If line 1 in the rich text box contains the string "device", I want to add it to the combo box.
If it does not, then move to line 2 and check that. If this contains the string "device" add it to the combo box.
If it does not, then move to line 3 and so on.

int IntCountLines

int IntNumberOfDevices.

Richtextbox name is: RtxtAdbOutput.

ComboBox name is: CmbIPs.

I have:

```<code>StrTmpOutput = rtxtAdbOutput.Lines[1].Substring(rtxtAdbOutput.Lines[1].Length - 6);

if (StrTmpOutput == "device")
{
    CmbIPs.Items.Add(rtxtAdbOutput.Lines[1].Remove(rtxtAdbOutput.Lines[1].Length - 7));
}

StrTmpOutput = rtxtAdbOutput.Lines[2].Substring(rtxtAdbOutput.Lines[2].Length - 6);

if (StrTmpOutput == "device")
{
    CmbIPs.Items.Add(rtxtAdbOutput.Lines[2].Remove(rtxtAdbOutput.Lines[2].Length - 7));
}

StrTmpOutput = rtxtAdbOutput.Lines[3].Substring(rtxtAdbOutput.Lines[3].Length - 6);

if (StrTmpOutput == "device")
{
    CmbIPs.Items.Add(rtxtAdbOutput.Lines[3].Remove(rtxtAdbOutput.Lines[3].Length - 7));
}
</code>```

And so on. But do not know the amount of lines until runtime means I do not know how long to carry on adding if statements.
Plus, it gives errors if it is an empty line (as it tries to strip 7 characters from the end of a string that does not exist though I could put in some error checking to stop this).

Is there any way I can improve this with a for loop or similar?

I want to keep doing this until the amount of lines added to the combobox matches the value of IntNumberOfDevices.

答:
You can use a combination of the List<T>.ForEach() method and the String.EndsWith()

```<code>rtxtAdbOutput.Lines.ToList()
    .GetRange(1, rtxtAdbOutput.Lines.Count() - 1)
    .Where(line => line.EndsWith("device")).ToList()
    .ForEach(validLine => CmbIPs.Items.Add(validLine.Remove(validLine.Length - 7)));
</code>```

What this does is get all of the lines with an index higher than 0 as a list, then selects the ones that end with "device" using String.EndsWith, then for each of those adds them to the combo box using ForEach().

DotnetFiddle demonstrating it

String.EndsWith documentation

List.ForEach documentation

Body:
I am trying to populate a combo box with lines from a rich text box.
But only if the last 6 characters of a line in the rich text box contains the string "device".
I do not know the amount of lines in the rich text box and the amount of lines that contain the string "device", until runtime.

Let’s say there are 6 lines in the combo box and 2 items that contain the string "device".
But both numbers can and do change during runtime.

int IntCountLines is equal to the amount of lines in the rich text box.
int IntNumberOfDevices is equal to the number of lines that contain the string "device" (in the last 6 characters) in the rich text box.

The first line [0] in the rich text box is always ignored.
So, starting at line [1].

If line 1 in the rich text box contains the string "device", I want to add it to the combo box.
If it does not, then move to line 2 and check that. If this contains the string "device" add it to the combo box.
If it does not, then move to line 3 and so on.

int IntCountLines

int IntNumberOfDevices.

Richtextbox name is: RtxtAdbOutput.

ComboBox name is: CmbIPs.

I have:

StrTmpOutput = rtxtAdbOutput.Lines[1].Substring(rtxtAdbOutput.Lines[1].Length - 6);

if (StrTmpOutput == "device")
{
    CmbIPs.Items.Add(rtxtAdbOutput.Lines[1].Remove(rtxtAdbOutput.Lines[1].Length - 7));
}

StrTmpOutput = rtxtAdbOutput.Lines[2].Substring(rtxtAdbOutput.Lines[2].Length - 6);

if (StrTmpOutput == "device")
{
    CmbIPs.Items.Add(rtxtAdbOutput.Lines[2].Remove(rtxtAdbOutput.Lines[2].Length - 7));
}

StrTmpOutput = rtxtAdbOutput.Lines[3].Substring(rtxtAdbOutput.Lines[3].Length - 6);

if (StrTmpOutput == "device")
{
    CmbIPs.Items.Add(rtxtAdbOutput.Lines[3].Remove(rtxtAdbOutput.Lines[3].Length - 7));
}

And so on. But do not know the amount of lines until runtime means I do not know how long to carry on adding if statements.
Plus, it gives errors if it is an empty line (as it tries to strip 7 characters from the end of a string that does not exist though I could put in some error checking to stop this).

Is there any way I can improve this with a for loop or similar?

I want to keep doing this until the amount of lines added to the combobox matches the value of IntNumberOfDevices.

Body:
You can use a combination of the List<T>.ForEach() method and the String.EndsWith()

rtxtAdbOutput.Lines.ToList()
    .GetRange(1, rtxtAdbOutput.Lines.Count() - 1)
    .Where(line => line.EndsWith("device")).ToList()
    .ForEach(validLine => CmbIPs.Items.Add(validLine.Remove(validLine.Length - 7)));

What this does is get all of the lines with an index higher than 0 as a list, then selects the ones that end with "device" using String.EndsWith, then for each of those adds them to the combo box using ForEach().

DotnetFiddle demonstrating it

String.EndsWith documentation

List.ForEach documentation


问:
How to protect a contact form without captcha?
On my website I have a couple of forms where someone (without registration) can send message to specified, registered user. The form is simple, and I want to keep that way. What is the best way to protect a contact form againts spam and bots if I don't want to use any captcha?</p>

```<code>Your message:...
Your e-mail:...
[Send]
</code>```

答:
Use: iScramble

It basically takes a string (your form html stored as a string in PHP) and generates a block of obfuscated Javascript.

It can help hide those form keys you are using to secure your forms, or completely hide your form from bots all together.

I've been using this since the 90's (the page at the link above is clearly at least that old) and I don't get form spam ever.

Body:
On my website I have a couple of forms where someone (without registration) can send message to specified, registered user. The form is simple, and I want to keep that way. What is the best way to protect a contact form againts spam and bots if I don't want to use any captcha?

Your message:...
Your e-mail:...
[Send]


问:
Should I use Static class for Database connectivity in C#.net?
I have a class which contain all the database connection activities. What i want to know is should i make this class as static then i can call anywhere without creating it.
but the application runs in different pcs in same network in same time.

OR ELSE

should i create a normal class that can be use in other classes by inheriting it?

答:
A static class might declutter your code somewhat. It's not a bad idea.

But I'm not sure what that has to do with the application running on different pcs on the same network.


问:
How do I convert a random number in to a character
I have tried to convert a random number into a character.

If I type a number into a variable it works, but if I do this int number = (int)(Math.random()*10); and then to assign it to a char and convert it char c = (char)number; when I print it, it shows nothing without errors like an invisible character.

Could you help me to do this?

答:
Use an Integer and convert to String.</p>

```<code>public class Main {
    public static void main(String[] args) {
        Integer number = new Integer(Math.random() * 10);
        String c = number.toString();
        System.out.println(c);
    }
}
</code>```

Body:
Use an Integer and convert to String.

public class Main {
    public static void main(String[] args) {
        Integer number = new Integer(Math.random() * 10);
        String c = number.toString();
        System.out.println(c);
    }
}


问:
How to merge source rows using SSIS Kingswaysoft without using a temp table
I have a source table with multiple rows of data but with no header row. I need to migrate this data to D365 CRM as two entities; A header entity and the corresponding content/rows entity.

Is there any way to create the header entity in Kingswaysoft / SSIS where the header would represent all the rows with the same batch number and their total payment?

Preferably without a temp table? (If its not possible without a temp table).

Thanks in advance!!!

This is what i get when i add the multicast:

What do I do here? there are no options.

This is the SQL I wrote to merge the rows.

```<code>SELECT [business]
  ,[payment]
  ,[batch],
   SUM(CASE WHEN payment >= 0  THEN payment ELSE 0 END) pay,
   SUM(CASE WHEN payment >= 420  THEN 21.72 ELSE 0 END)
   TransactionAmount1,
   SUM(CASE WHEN payment <= 299.99 AND payment >= 260 THEN 15.35 ELSE 0
   END) TransactionAmount2,

   FROM [Payments]
   Group By batch, business_num
</code>```

答:
This is what your data flow will look like:

In the aggregate group by batch,business and sum(payments). There is no need to create a headerID. Batch is your link.

Body:
I have a source table with multiple rows of data but with no header row. I need to migrate this data to D365 CRM as two entities; A header entity and the corresponding content/rows entity.

Is there any way to create the header entity in Kingswaysoft / SSIS where the header would represent all the rows with the same batch number and their total payment?

Preferably without a temp table? (If its not possible without a temp table).

Thanks in advance!!!

This is what i get when i add the multicast:

What do I do here? there are no options.

This is the SQL I wrote to merge the rows.

SELECT [business]
  ,[payment]
  ,[batch],
   SUM(CASE WHEN payment >= 0  THEN payment ELSE 0 END) pay,
   SUM(CASE WHEN payment >= 420  THEN 21.72 ELSE 0 END)
   TransactionAmount1,
   SUM(CASE WHEN payment <= 299.99 AND payment >= 260 THEN 15.35 ELSE 0
   END) TransactionAmount2,

   FROM [Payments]
   Group By batch, business_num


问:
Parsing from json call to map in flutter
Hi the following dart code in flutter, make a rest call to a node.js server returning a map of values in a map. When I run the code, however, the exception below is raised. How can I go about solving this?
Below is an example of json values returning from the rest server in node.js.

Dart Code:

```<code>  static Future<Map> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
      String RagioneSociale, bool isUtente) async {

    Map ret;
    Map map = {
      'IdUtente': u.GetIdUtente(),
      'IdCantiere': IdCantiere,
      'NomeCantiere': NomeCantiere,
      'RagioneSociale': RagioneSociale,
      'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
    };
    String value = await apiRequest("/cantieri/ricerca", map);

    ret = json.decode(value);
          return ret;
  }
</code>```

Exception:

```<code>[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
#0      CantiereController.Ricerca (package:MyApp/Controller/Cantiere.dart:28:5)
<asynchronous suspension>
#1      Cantiere.ricerca (package:MyApp/Model/Cantiere.dart:18:142)
#2      inizializzaValori (package:MyApp/View/Cantieri/training_screen.dart:25:38)
<asynchronous suspension>
#3      _TrainingScreenState.initState (package:MyApp/View/Cantieri/training_screen.dart:47:5)
#4      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
#5      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
#6      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#7      MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5551:32)
#8      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#9      Element.updateChild (package:flutter/src/widgets/framework.dart:2988<…>MyApp
</code>```

ApiRest.dart Code:

```<code>Future<String> apiRequest(String urlpassed, Map jsonMap) async {
  //Give server and port
  String server = await Storage.leggi("Server");
  String porta = await Storage.leggi("Porta");

  var url=""+server+":"+porta;

  url=url+urlpassed;
  HttpClient httpClient = new HttpClient();

  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();

  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}
</code>```

JSON Example:

```<code>[
    {
        "IdCantiere": 4,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "dsdso",
        "NomeCantiere": "sala sdsd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "sddsdsd"
    },
    {
        "IdCantiere": 5,
        "IdCliente": 204,
        "Filiale": "SEDE",
        "RagioneSociale": "sdsds",
        "NomeCantiere": "manutenzione allarme",
        "DataCreazioneCantiere": "2017-08-04T18:27:42.017Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "manutenzione impianto allarme AVS"
    },
    {
        "IdCantiere": 6,
        "IdCliente": 140,
        "Filiale": "SEDE",
        "RagioneSociale": "Psdsddo",
        "NomeCantiere": "Ristrutturazione terremoto",
        "DataCreazioneCantiere": "2017-08-07T17:45:15.347Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "        stampato 10/01/19"
    }
]
</code>```

答:
The rest service is returning a list of Map and you method is awaiting for just a Map, probably change your method like the code below could help

static Future<List<Map<String,dynamic>>> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
      String RagioneSociale, bool isUtente) async {

    Map ret;
    Map map = {
      'IdUtente': u.GetIdUtente(),
      'IdCantiere': IdCantiere,
      'NomeCantiere': NomeCantiere,
      'RagioneSociale': RagioneSociale,
      'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
    };
    String value = await apiRequest("/cantieri/ricerca", map);

    ret = json.decode(value);
          return ret;
  }

```

Body:
Hi the following dart code in flutter, make a rest call to a node.js server returning a map of values in a map. When I run the code, however, the exception below is raised. How can I go about solving this?
Below is an example of json values returning from the rest server in node.js.

Dart Code:

  static Future<Map> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
      String RagioneSociale, bool isUtente) async {

    Map ret;
    Map map = {
      'IdUtente': u.GetIdUtente(),
      'IdCantiere': IdCantiere,
      'NomeCantiere': NomeCantiere,
      'RagioneSociale': RagioneSociale,
      'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
    };
    String value = await apiRequest("/cantieri/ricerca", map);

    ret = json.decode(value);
          return ret;
  }

Exception:

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
#0      CantiereController.Ricerca (package:MyApp/Controller/Cantiere.dart:28:5)
<asynchronous suspension>
#1      Cantiere.ricerca (package:MyApp/Model/Cantiere.dart:18:142)
#2      inizializzaValori (package:MyApp/View/Cantieri/training_screen.dart:25:38)
<asynchronous suspension>
#3      _TrainingScreenState.initState (package:MyApp/View/Cantieri/training_screen.dart:47:5)
#4      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
#5      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
#6      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#7      MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5551:32)
#8      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#9      Element.updateChild (package:flutter/src/widgets/framework.dart:2988<…>MyApp

ApiRest.dart Code:

Future<String> apiRequest(String urlpassed, Map jsonMap) async {
  //Give server and port
  String server = await Storage.leggi("Server");
  String porta = await Storage.leggi("Porta");

  var url=""+server+":"+porta;

  url=url+urlpassed;
  HttpClient httpClient = new HttpClient();

  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();

  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}

JSON Example:

[
    {
        "IdCantiere": 4,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "dsdso",
        "NomeCantiere": "sala sdsd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "sddsdsd"
    },
    {
        "IdCantiere": 5,
        "IdCliente": 204,
        "Filiale": "SEDE",
        "RagioneSociale": "sdsds",
        "NomeCantiere": "manutenzione allarme",
        "DataCreazioneCantiere": "2017-08-04T18:27:42.017Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "manutenzione impianto allarme AVS"
    },
    {
        "IdCantiere": 6,
        "IdCliente": 140,
        "Filiale": "SEDE",
        "RagioneSociale": "Psdsddo",
        "NomeCantiere": "Ristrutturazione terremoto",
        "DataCreazioneCantiere": "2017-08-07T17:45:15.347Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "        stampato 10/01/19"
    }
]


问:
How do I stop UWP Camera requiring permission to the Microphone
So I am initialising a MediaCapture element in my UWP application on my Surface Pro device like so:

```<code>            // Create MediaCapture and its settings
            mediaCapture = new MediaCapture();
            var mediaInitSettings = new MediaCaptureInitializationSettings
            {
                VideoDeviceId = cameraDevice.Id,
                AudioDeviceId = string.Empty,
                //StreamingCaptureMode = StreamingCaptureMode.Video,
                //PhotoCaptureSource = PhotoCaptureSource.Photo
            };

            // Initialize MediaCapture
            try
            {
                await mediaCapture.InitializeAsync(mediaInitSettings);
                ....
            }
</code>```

at the line InitializeAsync the application asks for both camera and microphone capabilities.

Now I have no need for the Microphone capability as I am only capturing photos and many of my users deny access to the Microphone saying "Why do you need microphone access to take a photo"

I tested using the built in "Camera" app and denying permission to the Microphone on windows and this works perfectly.

I looked at the documentation and it says:

InitializeAsync will launch a consent prompt to get the user's
  permission for the app to access the microphone or camera

So is it possible to stop the app asking for Microphone permissions?

答:
Ok I managed to solve it pretty easily by changing the StreamingCaptureMode on the MediaCaptureInitializationSettings adding this line:

```<code>StreamingCaptureMode = StreamingCaptureMode.Video
</code>```

so it became:

```<code>var mediaInitSettings = new MediaCaptureInitializationSettings
{
     VideoDeviceId = cameraDevice.Id,
     AudioDeviceId = string.Empty,
     StreamingCaptureMode = StreamingCaptureMode.Video,
};
</code>```

Body:
So I am initialising a MediaCapture element in my UWP application on my Surface Pro device like so:

            // Create MediaCapture and its settings
            mediaCapture = new MediaCapture();
            var mediaInitSettings = new MediaCaptureInitializationSettings
            {
                VideoDeviceId = cameraDevice.Id,
                AudioDeviceId = string.Empty,
                //StreamingCaptureMode = StreamingCaptureMode.Video,
                //PhotoCaptureSource = PhotoCaptureSource.Photo
            };

            // Initialize MediaCapture
            try
            {
                await mediaCapture.InitializeAsync(mediaInitSettings);
                ....
            }

at the line InitializeAsync the application asks for both camera and microphone capabilities.

Now I have no need for the Microphone capability as I am only capturing photos and many of my users deny access to the Microphone saying "Why do you need microphone access to take a photo"

I tested using the built in "Camera" app and denying permission to the Microphone on windows and this works perfectly.

I looked at the documentation and it says:

InitializeAsync will launch a consent prompt to get the user's
  permission for the app to access the microphone or camera

So is it possible to stop the app asking for Microphone permissions?

Body:
Ok I managed to solve it pretty easily by changing the StreamingCaptureMode on the MediaCaptureInitializationSettings adding this line:

StreamingCaptureMode = StreamingCaptureMode.Video

so it became:

var mediaInitSettings = new MediaCaptureInitializationSettings
{
     VideoDeviceId = cameraDevice.Id,
     AudioDeviceId = string.Empty,
     StreamingCaptureMode = StreamingCaptureMode.Video,
};