问:
Calling the callback function on successful authorization
I'm new to developing applications with reactive-native. I'm trying to make a transition with successful authorization to the next application scene. Here is my code

```<code>login = () => {
   firebaseApp.auth().signInWithEmailAndPassword(email, password
   ).then((userData) => {
       var uid = userData.uid;
       localStorage.save('uidKey', uid)
       console.log('uidKey');
       // transition
     }
   ).catch((error) => {
     AlertIOS.alert(
      'Login Failed!',
      'Please try again'
     );
   }); }); }
</code>```

I know how to trigger a transition by pressing the button. By adding this line of code

```<code>onPress={() => Actions.root()}>
</code>```

But I have no idea how to call this function from a callback. In the string //transition

Be so kind, help me

答:
You should be able to import Actions and then fire off the same transition:</p>

```<code>import { Actions } from 'react-native-router-flux';
...
login = () => {
    firebaseApp.auth().signInWithEmailAndPassword(email, password
    ).then((userData) => {
            var uid = userData.uid;
            localStorage.save('uidKey', uid)
            console.log('uidKey');
            // transition
            Actions.root()
        }
    ).catch((error) => {
        AlertIOS.alert(
            'Login Failed!',
            'Please try again'
        );
    }); }); }
</code>```

Body:
I'm new to developing applications with reactive-native. I'm trying to make a transition with successful authorization to the next application scene. Here is my code

login = () => {
   firebaseApp.auth().signInWithEmailAndPassword(email, password
   ).then((userData) => {
       var uid = userData.uid;
       localStorage.save('uidKey', uid)
       console.log('uidKey');
       // transition
     }
   ).catch((error) => {
     AlertIOS.alert(
      'Login Failed!',
      'Please try again'
     );
   }); }); }

I know how to trigger a transition by pressing the button. By adding this line of code

onPress={() => Actions.root()}>

But I have no idea how to call this function from a callback. In the string //transition

Be so kind, help me

Body:
You should be able to import Actions and then fire off the same transition:

import { Actions } from 'react-native-router-flux';
...
login = () => {
    firebaseApp.auth().signInWithEmailAndPassword(email, password
    ).then((userData) => {
            var uid = userData.uid;
            localStorage.save('uidKey', uid)
            console.log('uidKey');
            // transition
            Actions.root()
        }
    ).catch((error) => {
        AlertIOS.alert(
            'Login Failed!',
            'Please try again'
        );
    }); }); }


来源: stackexchange

问:
How to display Edittext in Android
I have an EditText that looks like this:

When doing an action in the EditText the background is changed with the following code:

```<code>edtCampo.setBackgroundColor(Color.RED);
</code>```

Then another action is made and the EditText background is changed again with the following code:

```<code>edtCampo.setBackgroundColor(Color.TRANSPARENT);
</code>```

The problem is that in the EditText I do not see the line below, what property should I give to make it look like the first image ?

答:
Try to use </p>

```<code>int backgroundResource = 0;
if(redBackgroundNeeded){
    backgroundResource = R.color.red;
}
view.setBackgroundResource(backgroundResource);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to display Edittext in Android

Body:
I have an EditText that looks like this:

When doing an action in the EditText the background is changed with the following code:

edtCampo.setBackgroundColor(Color.RED);

Then another action is made and the EditText background is changed again with the following code:

edtCampo.setBackgroundColor(Color.TRANSPARENT);

The problem is that in the EditText I do not see the line below, what property should I give to make it look like the first image ?

Body:
Try to use

int backgroundResource = 0;
if(redBackgroundNeeded){
    backgroundResource = R.color.red;
}
view.setBackgroundResource(backgroundResource);


问:
How would I take the average of the first column of a file every 6 lines with bash?
I have a file that looks like this:

```<code>[root@localhost ~]# cat output.txt
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
</code>```

How would I sort this and calculate the averages of the first 2 columns? I have a for loop that runs 6 times to populate this data so it would only have to calculate the averages every 6 lines.

答:
Bash is the wrong tool -- it doesn't support floating-point math. Use awk instead:

```<code>awk '
# Initialization: Run once at startup
BEGIN {
  i=0;
  sum1=0;
  sum2=0;
}

# Run once per line
{
  sum1+=$1;
  sum2+=$2;
  if(++i >= 6) {
    print (sum1 / i) " " (sum2 / i);
    sum1=0;
    sum2=0;
    i=0;
  }
}

# Run once at the very end, for if our total number of lines was not divisible by 6
END {
  if(i > 0) {
    print (sum1 / i) " " (sum2 / i)
  }
}
'
</code>```

Body:
I have a file that looks like this:

[root@localhost ~]# cat output.txt
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan
 0.0 709312 gnome-session-b dan
 0.7 3662292  \_ gnome-shell dan
 0.0 1157420  \_ gnome-softw dan
 0.0 903172 gnome-shell-cal dan
 0.0 286580 gnome-keyring-d dan

How would I sort this and calculate the averages of the first 2 columns? I have a for loop that runs 6 times to populate this data so it would only have to calculate the averages every 6 lines.

Body:
Bash is the wrong tool -- it doesn't support floating-point math. Use awk instead:

awk '
# Initialization: Run once at startup
BEGIN {
  i=0;
  sum1=0;
  sum2=0;
}

# Run once per line
{
  sum1+=$1;
  sum2+=$2;
  if(++i >= 6) {
    print (sum1 / i) " " (sum2 / i);
    sum1=0;
    sum2=0;
    i=0;
  }
}

# Run once at the very end, for if our total number of lines was not divisible by 6
END {
  if(i > 0) {
    print (sum1 / i) " " (sum2 / i)
  }
}
'


问:
Firebase Auth Creating new user with text input from a different class
I have two view controllers, first view controller contains the textfield for the (email/username) input from the user. The second view controller contains the textfield for the (password) input from the user. The second view controller also contains a Button to execute the FireBase Auth code to create a new user. I want to take the email text from the first view controller class one and transfer that data onto to the second view controller class in order to successfully create a new user. I tried using a global variable but it doesn't seem to work, any help this dilemma? Any help is appreciated thanks!

答:
I do not recommend the use of a global struct in this case, but if you want to do this. You can create a new swift file and move your struct out to that file. Like this:

```<code>struct GlobalData {
    var email: String? = nil
}

var globalData = GlobalData()
</code>```

You can get any value in that struct using globalData.email

However, I think it makes more sense for you to pass the data when you segue. If you don't know how to make a segue look at this question. Then you can do something like this:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "nameOfYourSegue" {
            let controller = segue.destination as! NameOfViewControllerYourGoingTo
            controller.email = email
        }
</code>```

You can look at this and this and this for more information. Let me know if you still have questions.

Body:
I do not recommend the use of a global struct in this case, but if you want to do this. You can create a new swift file and move your struct out to that file. Like this:

struct GlobalData {
    var email: String? = nil
}

var globalData = GlobalData()

You can get any value in that struct using globalData.email

However, I think it makes more sense for you to pass the data when you segue. If you don't know how to make a segue look at this question. Then you can do something like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "nameOfYourSegue" {
            let controller = segue.destination as! NameOfViewControllerYourGoingTo
            controller.email = email
        }

You can look at this and this and this for more information. Let me know if you still have questions.


问:
Alamofire request to twilio swift
I'm trying to get an SMS from twilio.com but get nil in response. Can anyone say what I'm doing wrong?</p>

```<code>class SMSVerificationService: NSObject {

    static let sharedInstance = SMSVerificationService()

    func SMSRequest(countryCode:String, phoneNumber: String) {
        let accountSid = "ACc4d9785419f144412823ff20as34660c3d"
        let authToken = "4wqecx41f8999caa23735da214" // changed :)

        let url = URL(string: "https://\(accountSid):\(authToken)@api.twilio.com/2010-04-01/Accounts\(accountSid)/Messages")
        print("url", url!)

        let parameters = [
            "To": "+37378847884",
            "From" : "+14243960339",
            "Body": "Hi daddy"
        ]
        Alamofire.request(url!, method: .post, parameters: parameters,
                          encoding: JSONEncoding.default, headers: [:]).responseJSON { response in
                            let response = String(describing: response.result.value)
                            print(response)
        }
    }

}
</code>```

答:
Twilio developer evangelist here.

We do not recommend that you make requests to the Twilio API directly from your native application. To do so, you would need to store or retrieve your account SID and auth token in the application somewhere. If you do this, then a malicious attacker could get access to your credentials and abuse your Twilio account.

This is actually known as the Eavesdropper vulnerability and was written about earlier this year.

Instead we recommend that you create a web application and send the API requests from there. There is a blog post on how to do that here: https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html

I notice that your class is called SMSVerificationService too. If you are looking to build phone verification, then I recommend you take a look at the Twilio Verify API that does a lot of the work for you.

Title: Alamofire request to twilio swift

Body:
I'm trying to get an SMS from twilio.com but get nil in response. Can anyone say what I'm doing wrong?

class SMSVerificationService: NSObject {

    static let sharedInstance = SMSVerificationService()

    func SMSRequest(countryCode:String, phoneNumber: String) {
        let accountSid = "ACc4d9785419f144412823ff20as34660c3d"
        let authToken = "4wqecx41f8999caa23735da214" // changed :)

        let url = URL(string: "https://\(accountSid):\(authToken)@api.twilio.com/2010-04-01/Accounts\(accountSid)/Messages")
        print("url", url!)

        let parameters = [
            "To": "+37378847884",
            "From" : "+14243960339",
            "Body": "Hi daddy"
        ]
        Alamofire.request(url!, method: .post, parameters: parameters,
                          encoding: JSONEncoding.default, headers: [:]).responseJSON { response in
                            let response = String(describing: response.result.value)
                            print(response)
        }
    }

}


问:
React: open pdf document from a link
I am new to react and I need to create a react component to open a pdf file. The pdf document will be opened through a link. I did some research and checked some posts on stackoverflow. e.g Create PDF file from HTML text React
But this one converts from html to pdf and what i need to do is just open a pdf document.

Is there any article or posts online that could help me?
Any help is appreciated

答: If the url of the pdf is not "cross-origin" you could use the "PDFJS" library to render the PDF in the browser.</p>

Title: React: open pdf document from a link


问:
In JShell, how to import classpath from a Maven project
I have a local Maven project under development. How can I launch jshell with the project class path with all the dependencies, so that I can test project or dependency classes inside JShell.

答:
See In Maven, how to output the classpath being used?.

According to:

```<code>jshell --help
</code>```

run JShell with:

```<code>jshell --class-path <path>
</code>```

Body:
See In Maven, how to output the classpath being used?.

According to:

jshell --help

run JShell with:

jshell --class-path <path>


问:
Divide num by (num / 10) recursively
I'm trying to write a function that divides a number by his tens recursively.

For ex: Given the number 555, the function will return 2:

555 / 55 / 5 = 2

The following code outputs 11:

555 / (55 / 5) = 50

function recursion(num){
    return num < 10 ? num : Math.floor(num / recursion(Math.floor(num / 10)));
}

console.log(recursion(555));```

How should the desired function to be programmed recursively yet conventionally?

答:
I solved it using a recursive multiplication function as follows:

function divideByTens(num){
    return Math.floor(num / recursionM(Math.floor(num / 10)));
}

function recursionM(num){
    if(num < 10)
        return num;

    return num * recursionM(Math.floor(num / 10));
}

console.log(divideByTens(555));```

Title: Divide num by (num / 10) recursively

Body:
I'm trying to write a function that divides a number by his tens recursively.

For ex: Given the number 555, the function will return 2:

555 / 55 / 5 = 2

The following code outputs 11:

555 / (55 / 5) = 50

function recursion(num){
    return num < 10 ? num : Math.floor(num / recursion(Math.floor(num / 10)));
}

console.log(recursion(555));

How should the desired function to be programmed recursively yet conventionally?


问:
twilio A 'From' phone number is required swift
I'm trying to get sms from twilio service but keep getting this error.

Request:

```<code>func SMSRequest(countryCode:String, phoneNumber: String) {
        let accountSid = "ACc4d9785419f144412823ff2034660c3d"
        let authToken = "a2293a42841f8999caa237er363" // changed

        let phoneNumber = "+14243960339"
        let toNumber = "+37378847884"

        let url = URL(string: "https://\(accountSid):\(authToken)@api.twilio.com/2010-04-01/Accounts/\(accountSid)/SMS/Messages")
        print("url", url!)

        let parameters = [
            "From": phoneNumber,
            "To": toNumber,
            "Body":"Hi daddy"
        ]

        Alamofire.request(url!, method: .post, parameters: parameters,
                          encoding: JSONEncoding.default, headers: [:]).responseJSON { response in
                            let response = String(describing: response.result.ifFailure({
                                print(response)
                                if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {print("Data: \(utf8Text)")}
                            }))

        }
    }
</code>```

Error:

```<code><TwilioResponse><RestException><Code>21603</Code><Message>A 'From' phone number is required.</Message><MoreInfo>https://www.twilio.com/docs/errors/21603</MoreInfo><Status>400</Status></RestException></TwilioResponse>
</code>```

All the credentials I get from here

Solution:
use utf8 encoding.

答:
Twilio developer evangelist here.

It's important to note that, even though you have solved your problem, you are building a fundamentally insecure application. I left this comment on your other question, but I need to point it out here too.

We do not recommend that you make requests to the Twilio API directly from your native application. To do so, you would need to store or retrieve your account SID and auth token in the application somewhere. If you do this, then a malicious attacker could get access to your credentials and abuse your Twilio account.

This is actually known as the Eavesdropper vulnerability and was written about earlier this year.

Instead we recommend that you create a web application and send the API requests from there. There is a blog post on how to do that here: https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html

Body:
I'm trying to get sms from twilio service but keep getting this error.

Request:

func SMSRequest(countryCode:String, phoneNumber: String) {
        let accountSid = "ACc4d9785419f144412823ff2034660c3d"
        let authToken = "a2293a42841f8999caa237er363" // changed

        let phoneNumber = "+14243960339"
        let toNumber = "+37378847884"

        let url = URL(string: "https://\(accountSid):\(authToken)@api.twilio.com/2010-04-01/Accounts/\(accountSid)/SMS/Messages")
        print("url", url!)

        let parameters = [
            "From": phoneNumber,
            "To": toNumber,
            "Body":"Hi daddy"
        ]

        Alamofire.request(url!, method: .post, parameters: parameters,
                          encoding: JSONEncoding.default, headers: [:]).responseJSON { response in
                            let response = String(describing: response.result.ifFailure({
                                print(response)
                                if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {print("Data: \(utf8Text)")}
                            }))

        }
    }

Error:

<TwilioResponse><RestException>21603<Message>A 'From' phone number is required.</Message><MoreInfo>https://www.twilio.com/docs/errors/21603</MoreInfo><Status>400</Status></RestException></TwilioResponse>

All the credentials I get from here

Solution:
use utf8 encoding.


问:
Yet Another Conditional Operator Nesting Question
As per C precedence tables, the ternary conditional operator has right-to-left
associativity.

So, is it directly convertible to the equivalent if-else ladder?

For example, can:

```<code>x?y?z:u:v;
</code>```

be interpreted as:

```<code>if(x)
{
   if(y)
   { z; }
   else
   { u; }
}
else
{ v; }
</code>```

by matching an else (:) with the closest unpaired if (?)? Or does right-to-left associativity imply some other arrangement?

答:
The example you gave could only be interpreted in one way (like the if statements you gave), whether the ternary operator had right-to-left or left-to-right associativity.

Where the right-to-left associativity matters is when you have:

```<code>x = a ? b : c ? d : e;
</code>```

Which is interpreted as: x = a ? b : (c ? d : e), not as x = (a ? b : c) ? d : e.

To give a more realistic example:

```<code>int getSign(int x) {
    return x < 0 ? -1 :
           x > 0 ?  1 :
                    0;
}
</code>```

This is identical to the (probably more readable) if / else-if statements:

```<code>int getSign(int x) {
    if (x < 0)
         return -1;
    else if (x > 0)
         return 1;
    else return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
As per C precedence tables, the ternary conditional operator has right-to-left
associativity.

So, is it directly convertible to the equivalent if-else ladder?

For example, can:

x?y?z:u:v;

be interpreted as:

if(x)
{
   if(y)
   { z; }
   else
   { u; }
}
else
{ v; }

by matching an else (:) with the closest unpaired if (?)? Or does right-to-left associativity imply some other arrangement?

Body:
The example you gave could only be interpreted in one way (like the if statements you gave), whether the ternary operator had right-to-left or left-to-right associativity.

Where the right-to-left associativity matters is when you have:

x = a ? b : c ? d : e;

Which is interpreted as: x = a ? b : (c ? d : e), not as x = (a ? b : c) ? d : e.

To give a more realistic example:

int getSign(int x) {
    return x < 0 ? -1 :
           x > 0 ?  1 :
                    0;
}

This is identical to the (probably more readable) if / else-if statements:

int getSign(int x) {
    if (x < 0)
         return -1;
    else if (x > 0)
         return 1;
    else return 0;
}


问:
aws s3 metadata all keys
The only way to read the user-defined metadata on an s3 object it seems is using head-object.

AWS_PROFILE=development aws s3api head-object --bucket "xxx-development" --key 'my-object-key'

s3api list-objects let's you get all the objects in the bucket including being able to filter for required patterns in the keys using --query, but it doesn't give the user-defined metadata associated with those objects.

AWS_PROFILE=development aws s3api list-objects --bucket "xxx-development" --query 'Contents[?contains(Key, 'original')]'

Is there a way to get all the objects and associated user-defined metadata without enumerating all the objects and iterating through all of them and doing a head-object on each?

user-defined metadata keys help us categorize our uploads to give meaningful insights.

答:
Unfortunately, no. The GET Bucket (List Objects) Version 2 (as well as Version 1) do not return user-defined metadata for an object.

You'll have to use HEAD object on each object returned by GET Bucket.

Title: aws s3 metadata all keys


问:
How to identify transaction as full reversal or partial reversal transaction by inspecting ISO8583 fields
I want to identify if transaction 0420 message is full reversal or partial reversal, How to do it? Should we say F95 (Replacement amount) is not set if it is full reversal.

Question:
Which field identifies transaction as a full reversal or partial reversal?
Do we need original transaction as well (0200 tran request) or 0420 itself contains enough information to identify the reversal category?

答:
This will depend on your endpoint specs.

We have some systems that sends you a replacement amount in field 95, some others in field 30 (which is actually for fees) but the basic idea is what you say, if you have a replacement amount, it's a partial reversal.

In ISO-8583 v2003 you've got data element 24 (Function Code) with specific values for accurate and estimated replacement amounts.


问:
how i get a value from a return statement of sqlserver stored procedure to java?
i'am trying to get into a variable called valorReturn the return statement in my stored procedure of sql server...
The sqlserver stored procedure is working fine, but the problem is java..

```<code>create procedure login
@cliente varchar(10),@pw varchar(10)
as begin
if exists(select cliente from seg where cliente=@cliente)
begin
if(select pw from seg where cliente=@cliente)=@pw
begin
   if(select privilegio from seg where cliente=@cliente)=0 begin
print 0
return 0
end
end

exec 'xd','xd'
</code>```

here i get a message from PRINT line:
  0

so, i should be able get the value and set it into variable valorReturn with this JAVA code

```<code>String consulta="exec login '"+usr+"','"+pw+"'";
CallableStatement st=con.prepareCall(consulta);
st.setInt(1,10);
st.registerOutParameter(1, Types.INTEGER);
st.execute();
int valorReturn=st.getInt(1);
</code>```

this is the exception printed in console

com.microsoft.sqlserver.jdbc.SQLServerException: index 1 is out of bound.

thanks, i appreciate any help! :)

答:
SQL needs to provide an output parameter to bind onto.

SQL:

```<code>create procedure login
    @cliente varchar(10), @pw varchar(10), @result INT = -1 OUTPUT
    as begin
    if exists(select cliente from seg where cliente=@cliente)
    begin
    if(select pw from seg where cliente=@cliente)=@pw
        begin
        if(select privilegio from seg where cliente=@cliente)=0 begin
        print 0
        SET @result = 0 -- new parameter
       return 0
    end
end
</code>```

Java:

```<code>    String consulta="exec login ?,?,?"; //moved out to parameters to avoid SQL injection.
    CallableStatement st= con.prepareCall(consulta);
    st.setString(1,usr);
    st.setString(2,pw);
    st.registerOutParameter(3, Types.INTEGER);
    st.execute();
    int valorReturn=st.getInt(3);
</code>```

More information can be found at https://learn.microsoft.com/en-us/sql/connect/jdbc/using-a-stored-procedure-with-output-parameters

Body:
i'am trying to get into a variable called valorReturn the return statement in my stored procedure of sql server...
The sqlserver stored procedure is working fine, but the problem is java..

create procedure login
@cliente varchar(10),@pw varchar(10)
as begin
if exists(select cliente from seg where cliente=@cliente)
begin
if(select pw from seg where cliente=@cliente)=@pw
begin
   if(select privilegio from seg where cliente=@cliente)=0 begin
print 0
return 0
end
end

exec 'xd','xd'

here i get a message from PRINT line:
  0

so, i should be able get the value and set it into variable valorReturn with this JAVA code

String consulta="exec login '"+usr+"','"+pw+"'";
CallableStatement st=con.prepareCall(consulta);
st.setInt(1,10);
st.registerOutParameter(1, Types.INTEGER);
st.execute();
int valorReturn=st.getInt(1);

this is the exception printed in console

com.microsoft.sqlserver.jdbc.SQLServerException: index 1 is out of bound.

thanks, i appreciate any help! :)

Body:
SQL needs to provide an output parameter to bind onto.

SQL:

create procedure login
    @cliente varchar(10), @pw varchar(10), @result INT = -1 OUTPUT
    as begin
    if exists(select cliente from seg where cliente=@cliente)
    begin
    if(select pw from seg where cliente=@cliente)=@pw
        begin
        if(select privilegio from seg where cliente=@cliente)=0 begin
        print 0
        SET @result = 0 -- new parameter
       return 0
    end
end

Java:

    String consulta="exec login ?,?,?"; //moved out to parameters to avoid SQL injection.
    CallableStatement st= con.prepareCall(consulta);
    st.setString(1,usr);
    st.setString(2,pw);
    st.registerOutParameter(3, Types.INTEGER);
    st.execute();
    int valorReturn=st.getInt(3);

More information can be found at https://learn.microsoft.com/en-us/sql/connect/jdbc/using-a-stored-procedure-with-output-parameters


问:
Strongly typing the output of a c# method
I have a c# function that has a method signature like this: public bool SerInto(out string result). I am trying to call this function to get the resultant string from this method. How do you call this? I want data to be of the type string. Is there a way to strongly type this variable?

Is this correct?

```<code>let string dataString
ds.SerInto(dataString)
</code>```

How do I get dataString to be the output string of this function

答:
F# can see the out parameters tupled with the return value.
So you should be able to call the C# function like this:

```<code>let (resultBool, dataString) = ds.SerInto()
</code>```

Which is a really nice feature. More about this here.

Body:
I have a c# function that has a method signature like this: public bool SerInto(out string result). I am trying to call this function to get the resultant string from this method. How do you call this? I want data to be of the type string. Is there a way to strongly type this variable?

Is this correct?

let string dataString
ds.SerInto(dataString)

How do I get dataString to be the output string of this function

Body:
F# can see the out parameters tupled with the return value.
So you should be able to call the C# function like this:

let (resultBool, dataString) = ds.SerInto()

Which is a really nice feature. More about this here.


问:
How to pull an article from the XML feed of a news site?
I have a concept to build a native Android app for a WordPress website.  The feed is in XML and it has everything that I need except the tag that houses the article itself.  I understand why this may be the case but I still want to display the article itself in the app as well alongside whatever header image it came with.

I usually only parsed with JSON so XML is pretty new to me.  Another question is that with XML, am I getting the XML feed from the feed link itself (url.com/feed)?

答: Documentation This is the basics and should get you pointed in the right direction. As far as getting the xml feed, API's vary on url's and requirements (and I cant be sure of the url without knowing which API you're using) depending on whether its a plugin or directly from your site.</p>


问:
How to receive data from json and store it into a variable?
I got a piece of code in here:

```<code>$.get("/upcase", {text: text})
.done((data) => {
    $('#results').prepend('<li>' + data['result'] + '</li>');
    $('#input').val(''); // reset the textbox
});
</code>```

Usually the data data['result'] will be pass to a html
tag with id="results" to form a list, but what if I want to store it into a variable, how do I achieve that?

At least it does not work like this:

```<code>let something = $('#results').val(data['result']);
</code>```

答:
declare a variable outside what you have, and in scope of where you need it. Say global. then just assign the data to it. i.e.

```<code>let globalResult;
$.get("/upcase", {text: text})
  .done((data) => {
    globalResult = data;
    $('#results').prepend('<li>' + data['result'] + '</li>');
    $('#input').val('');   // reset the textbox
  })
</code>```

just remember that data will be an object and get copied by reference, not value. So if you change data or globalData it will change the other. If that is no good you need to actually copy each element across.

Body:
I got a piece of code in here:

$.get("/upcase", {text: text})
.done((data) => {
    $('#results').prepend('
' + data['result'] + '
');
    $('#input').val(''); // reset the textbox
});

Usually the data data['result'] will be pass to a html
tag with id="results" to form a list, but what if I want to store it into a variable, how do I achieve that?

At least it does not work like this:

let something = $('#results').val(data['result']);

Body:
declare a variable outside what you have, and in scope of where you need it. Say global. then just assign the data to it. i.e.

let globalResult;
$.get("/upcase", {text: text})
  .done((data) => {
    globalResult = data;
    $('#results').prepend('<li>' + data['result'] + '</li>');
    $('#input').val('');   // reset the textbox
  })

just remember that data will be an object and get copied by reference, not value. So if you change data or globalData it will change the other. If that is no good you need to actually copy each element across.


问:
How to zip the contents of a whole directory?
I'm using python 2.7 and try to archive a directory:
the object is to: archive the whole folder's content
subject: C:\User\blah\blah\parentfolder

```<code>structure:C...parentfolder\ 1.docx
                            2.xlxs
                            4.pdf
                            subfolder\5.pdf
                                      6.txt
</code>```

Now I know that shutil.make_archive() can zip me the folder, but it turned out to be like this

```<code>C:\\User\\blah\\blah\\zipfile_name\\parentfolder\ 1.docx
                                                  2.xlxs
                                                  4.pdf
                                                  subfolder\5.pdf
                                                            6.txt
</code>```

but I want a to skip the parentfolder layer in the zipfile_name folder, that is:(This is where the problem is different, I did learn shutil.make_archive from that question, but as I open the shutil module, I found out that make_archive has four intakes. I didn't know what makes them different and used the four input one, that's where I had my question. The previous one didn't not point out why it used just three inputs, and the other answers were using very complicated self-defined functions or so. The answer I chose in this problem compared and explained the difference, which I really appreciate. As a non-computer science majored, I think this kind of details help a lot of people.)

```<code>C:\\User\\blah\\blah\\zipfile_name\\ 1.docx
                                     2.xlxs
                                     4.pdf
                                     subfolder\5.pdf
                                               6.txt
</code>```

if I use os.path.walk and so on to write every file to zipfile_name, it seems it will be super complicated, as I will need to first 1.list everything in the folder--while:1 file?--write into zip folder while:0 directory?--make_directory , and list all items, and while loop again this process( do until no directory exists in the last directory)

Plus I don't know how to make a directory in a .zip folder.  So all this just seems complicated.

So is there a way to change a folder into an archive folder while keeping the folder structure?

答:
It's just a matter of how you pass the information about the parentfolder folder in the parameters of make_archive.

Consider the following two examples:

```<code>shutil.make_archive('myarchive', 'zip', '/User/blah/blah', 'parentfolder')
</code>```

This will create the zip archive myarchive.zip. If you open myarchive.zip you will first see the folder parentfolder and if you open that you will see the contents of the original parentfolder from which the archive was made.

```<code>shutil.make_archive('myarchive', 'zip', '/User/blah/blah/parentfolder')
</code>```

This will create the zip archive myarchive.zip. If you open myarchive.zip you will immediately see the contents of the original parentfolder from which the archive was made. The folder name parentfolder will not appear in the archive.

The parameters are documented in https://docs.python.org/2/library/shutil.html, though to be honest it is not easy for me to see where the behavior I illustrated above is documented. I found it by trial and error
(Python 2.7.14 on Windows).

Body:
I'm using python 2.7 and try to archive a directory:
the object is to: archive the whole folder's content
subject: C:\User\blah\blah\parentfolder

structure:C...parentfolder\ 1.docx
                            2.xlxs
                            4.pdf
                            subfolder\5.pdf
                                      6.txt

Now I know that shutil.make_archive() can zip me the folder, but it turned out to be like this

C:\\User\\blah\\blah\\zipfile_name\\parentfolder\ 1.docx
                                                  2.xlxs
                                                  4.pdf
                                                  subfolder\5.pdf
                                                            6.txt

but I want a to skip the parentfolder layer in the zipfile_name folder, that is:(This is where the problem is different, I did learn shutil.make_archive from that question, but as I open the shutil module, I found out that make_archive has four intakes. I didn't know what makes them different and used the four input one, that's where I had my question. The previous one didn't not point out why it used just three inputs, and the other answers were using very complicated self-defined functions or so. The answer I chose in this problem compared and explained the difference, which I really appreciate. As a non-computer science majored, I think this kind of details help a lot of people.)

C:\\User\\blah\\blah\\zipfile_name\\ 1.docx
                                     2.xlxs
                                     4.pdf
                                     subfolder\5.pdf
                                               6.txt

if I use os.path.walk and so on to write every file to zipfile_name, it seems it will be super complicated, as I will need to first 1.list everything in the folder--while:1 file?--write into zip folder while:0 directory?--make_directory , and list all items, and while loop again this process( do until no directory exists in the last directory)

Plus I don't know how to make a directory in a .zip folder.  So all this just seems complicated.

So is there a way to change a folder into an archive folder while keeping the folder structure?

Body:
It's just a matter of how you pass the information about the parentfolder folder in the parameters of make_archive.

Consider the following two examples:

shutil.make_archive('myarchive', 'zip', '/User/blah/blah', 'parentfolder')

This will create the zip archive myarchive.zip. If you open myarchive.zip you will first see the folder parentfolder and if you open that you will see the contents of the original parentfolder from which the archive was made.

shutil.make_archive('myarchive', 'zip', '/User/blah/blah/parentfolder')

This will create the zip archive myarchive.zip. If you open myarchive.zip you will immediately see the contents of the original parentfolder from which the archive was made. The folder name parentfolder will not appear in the archive.

The parameters are documented in https://docs.python.org/2/library/shutil.html, though to be honest it is not easy for me to see where the behavior I illustrated above is documented. I found it by trial and error
(Python 2.7.14 on Windows).


问:
::SysFreeString() not behaving correctly
I've run into a problem with ::SysFreeString(). It seems that when I call the following block with a large BSTR (mine is ~40,000 characters),

```<code>            VARIANT attValue;
            attValue.vt = VT_BSTR;
            attValue.bstrVal = attributeValue.AllocSysString();
            // use the bstrVal
            ::SysFreeString(attValue.bstrVal);
            VariantClear(&attValue);
</code>```

the string is not cleared correctly and corrupts the heap. However, with smaller (~16,000 characters) BSTR's, it works correctly and no corruption occurs. Is there an upper limit that I'm missing with the allocation or freeing?

Why is ::SysFreeString() behaving this way?

答:
DO NOT call SysFreeString() if you are going to call VariantClear(), and vice versa.  VariantClear() frees the BSTR for you, this is documented behavior:

The function clears a VARIANTARG by setting the vt field to VT_EMPTY. The current contents of the VARIANTARG are released first. If the vtfield is VT_BSTR, the string is freed. If the vtfield is VT_DISPATCH, the object is released. If the vt field has the VT_ARRAY bit set, the array is freed.

You are attempting to free the same memory twice using an invalid pointer the second time, since you are not resetting attValue.bstrVal to NULL after calling SysFreeString().

Call EITHER SysFreeString() OR VariantClear(), but not BOTH.  Calling VariantClear() would be the preferred solution in this example since you are using a VARIANT to hold the BSTR.

Since you are clearly using a wrapper class to allocate the BSTR, I suggest you use a similar wrapper class to manage the VARIANT for you, such as CComVariant or _variant_t.

Body:
I've run into a problem with ::SysFreeString(). It seems that when I call the following block with a large BSTR (mine is ~40,000 characters),

            VARIANT attValue;
            attValue.vt = VT_BSTR;
            attValue.bstrVal = attributeValue.AllocSysString();
            // use the bstrVal
            ::SysFreeString(attValue.bstrVal);
            VariantClear(&attValue);

the string is not cleared correctly and corrupts the heap. However, with smaller (~16,000 characters) BSTR's, it works correctly and no corruption occurs. Is there an upper limit that I'm missing with the allocation or freeing?

Why is ::SysFreeString() behaving this way?


问:
only first line of wp_enqueue_style gets executed
I'm trying to build a child theme for an existing theme someone else built. That theme uses multiple stylesheets and of course, I want the child theme to enqueue them all.

Strangely enough I noticed that that only the first line of the wp_enqueue_style() of the parent theme gets executed while the wp_enqueue_style() of the child theme does work.

I'm kinda stuck and I have no clue on how to make the child theme use all those stylesheets.

```<code>    function my_theme_enqueue_styles() {

    //parent style
    $parent_style = 'parent-style';

    //enqueue css of the parent theme
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/bootstrap.min.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/custom-login.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-awesome.min.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-dc-cash.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-dccash.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/hro-admin.css' );

    //enqueue css of the child theme
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array( $parent_style ),
        wp_get_theme()->get('Version')
    );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
</code>```

btw: I know that those css files dont't make any sense. Tell that to the original builder.

download link of the parent theme

答: The first parameter to wp_enqueue_style() needs to be unique.  You are passing in $parent_style for everything.  If you give them all unique names, maybe using $parent_style as a prefix, it should fix it.

Body:
I'm trying to build a child theme for an existing theme someone else built. That theme uses multiple stylesheets and of course, I want the child theme to enqueue them all.

Strangely enough I noticed that that only the first line of the wp_enqueue_style() of the parent theme gets executed while the wp_enqueue_style() of the child theme does work.

I'm kinda stuck and I have no clue on how to make the child theme use all those stylesheets.

    function my_theme_enqueue_styles() {

    //parent style
    $parent_style = 'parent-style';

    //enqueue css of the parent theme
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/bootstrap.min.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/custom-login.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-awesome.min.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-dc-cash.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-dccash.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/hro-admin.css' );

    //enqueue css of the child theme
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array( $parent_style ),
        wp_get_theme()->get('Version')
    );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );

btw: I know that those css files dont't make any sense. Tell that to the original builder.

download link of the parent theme


问:
SELECT same element from two tables
I got these two tables:

```<code>Create table  Consumidor  (
    numero  int(9),
    email   varchar(30) not null,
    sexo    char(1) not null,
    nascimento  date    not null,
    constraint Consumidor_sexo_RI001     check (sexo in ('F','M')),
    constraint Consumidor_unique_RI002  unique(email),
    constraint pk_Consumidor     primary key (numero)
);

Create table  Dependente  (
    consumidor  int(9),
    numero  int(2),
    sexo    char(1) not null,
    nascimento  date    not null,
    constraint Dependente_sexo_RI003 check (sexo in ('F','M')),
    constraint fk_Dependente_consumidor  foreign key (consumidor) references Consumidor(numero) on delete cascade,
    constraint pk_Dependente     primary key (consumidor,numero)
);
</code>```

What I wanna do is SELECT the 'sexo' and 'nascimento' of both tables. I don't understand how I can do this.

------------------ EDIT -----------------------
The result table should look something like this:

```<code>idade | sexo
  34  |  F
</code>```

It only has two columns for both tables.

答:
Query:

```<code>SELECT c.sexo as "Consumidor", c.nascimento as "Consumidor",
       d.sexo as "Dependente", d.nascimento as "Dependente"
FROM
      Consumidor c JOIN Dependente d ON c.numero = d.consumidor
ORDER BY
      c.nascimento;
</code>```

Result:

```<code>Consumidor  Consumidor  Dependente  Dependente
    M       2012-08-06       F      2012-08-06
</code>```

If you want to combine them together perhaps

```<code>SELECT group_concat(c.sexo,"|",d.sexo) as "sexo",
       group_concat(TIMESTAMPDIFF(YEAR,c.nascimento,CURDATE())
                    ,"|"
                    ,TIMESTAMPDIFF(YEAR,d.nascimento,CURDATE())) as "idade"
FROM
      Consumidor c JOIN Dependente d ON c.numero = d.consumidor
ORDER BY
      c.nascimento;
</code>```

Which produces:

```<code>sexo    idade
F|M      5|5
</code>```

Title: SELECT same element from two tables

Body:
I got these two tables:

Create table  Consumidor  (
    numero  int(9),
    email   varchar(30) not null,
    sexo    char(1) not null,
    nascimento  date    not null,
    constraint Consumidor_sexo_RI001     check (sexo in ('F','M')),
    constraint Consumidor_unique_RI002  unique(email),
    constraint pk_Consumidor     primary key (numero)
);

Create table  Dependente  (
    consumidor  int(9),
    numero  int(2),
    sexo    char(1) not null,
    nascimento  date    not null,
    constraint Dependente_sexo_RI003 check (sexo in ('F','M')),
    constraint fk_Dependente_consumidor  foreign key (consumidor) references Consumidor(numero) on delete cascade,
    constraint pk_Dependente     primary key (consumidor,numero)
);

What I wanna do is SELECT the 'sexo' and 'nascimento' of both tables. I don't understand how I can do this.

------------------ EDIT -----------------------
The result table should look something like this:

idade | sexo
  34  |  F

It only has two columns for both tables.

Body:
Query:

SELECT c.sexo as "Consumidor", c.nascimento as "Consumidor",
       d.sexo as "Dependente", d.nascimento as "Dependente"
FROM
      Consumidor c JOIN Dependente d ON c.numero = d.consumidor
ORDER BY
      c.nascimento;

Result:

Consumidor  Consumidor  Dependente  Dependente
    M       2012-08-06       F      2012-08-06

If you want to combine them together perhaps

SELECT group_concat(c.sexo,"|",d.sexo) as "sexo",
       group_concat(TIMESTAMPDIFF(YEAR,c.nascimento,CURDATE())
                    ,"|"
                    ,TIMESTAMPDIFF(YEAR,d.nascimento,CURDATE())) as "idade"
FROM
      Consumidor c JOIN Dependente d ON c.numero = d.consumidor
ORDER BY
      c.nascimento;

Which produces:

sexo    idade
F|M      5|5


问:
Displaying Hexadecimal numbers
We would display Hexadecimals in A03Eh format which A=10 & E=14, and A is a nibble. But I have seen another display like this : 0x002314A8 , How can we convert the above number into this format ? what is this format ?</p>

答:
The format 0x is the standard Unix way of representing hexadecimal numbers. I am used to seeing 0x at the beginning and not h at the end.

That is the only difference. Like Péter Török said, if you're using C/C++ there are ways to modify what is shown when you print.

ContentLicense: CC BY-SA 2.5

Title: Displaying Hexadecimal numbers


问:
Symfony 3 / Doctrine many-to-one always returns just last addition- FOSUser/OAuth extended
I am working on a login page, where it should be possible to login with different socialnetwork logins (facebook, twitter, google, etc).
It should work like this: every user has the possibility to add the socialnetwork login that he/she wants, so I want to have it as an One User-> Many Socialnetworklogins relation.
What works: Data is stored in Database, but in the line
            var_dump($user->getSocialnetworks());
I just get one Object, not all the ones that should be related to this user. I know that the function justATest adds just a socialnetworklogin to user 1, this was just a test.

```<code><?php
namespace AppBundle\Entity\Registration;

use Doctrine\Common\Collections\ArrayCollection;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
use Symfony\Component\Security\Core\User\UserInterface;

class FOSUBUserProvider extends BaseClass
{
public function justATest(UserResponseInterface $response)
    {
        // get user_id and socialnetworkname from response
        $userIdInSocialNetwork = $response->getUsername();
        $socialnetwork = $response->getResourceOwner()->getName();
        $login= new UserInSocialNetworks();
        $login->setSocialIdentyfier($response->getEmail());
        $login->setSocialNetworkSlug($socialnetwork);

        $user = $this->userManager->findUserBy(array(
                'id' => 1)
        );
        $login->setUserId($user);
        $user->addSocialNetwork($login);
        $this->userManager->updateUser($user);
        $users= $this->userManager->findUsers();
        var_dump($users);
        var_dump($socialnetwork);
        var_dump($user->getSocialnetworks());
        die();
} }
</code>```

The User Class:

```<code><?php

/*
 * This is the User class, depending on fos_userBundle
 */

namespace AppBundle\Entity\Registration;

use Doctrine\Common\Collections\ArrayCollection as ArrayCollection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="UserInSocialNetworks", mappedBy="user_id", cascade={"persist", "remove"})
     * @var ArrayCollection|null

     */
    private $socialnetworks;

    /**
     * @var string
     *
     * @ORM\Column(name="family_name",type="string", length=255, nullable=true)
     */
    private $familyName;

    /**
     * @var string
     *
     * @ORM\Column(name="given_name",type="string", length=255, nullable=true)
     */
    private $givenName;

    public function __construct()
    {
        parent::__construct();
        $this->socialnetworks = new ArrayCollection();
    }

    /**
     * @return string
     */
    public function getFamilyName()
    {
        return $this->familyName;
    }

    /**
     * @param string $familyName
     */
    public function setFamilyName($familyName)
    {
        $this->familyName = $familyName;
    }

    /**
     * @return string
     */
    public function getGivenName()
    {
        return $this->givenName;
    }

    /**
     * @param string $givenName
     */
    public function setGivenName($givenName)
    {
        $this->givenName = $givenName;
    }

    /**
     * @return ArrayCollection
     */
    public function getSocialnetworks()
    {
        return $this->socialnetworks;
    }

    /**
     * @param Collection UserInSocialNetworks
     */
    public function setSocialnetworks($socialnetworks)
    {
        $this->socialnetworks = $socialnetworks;
    }

    /**
     * @param UserInSocialNetwork
     */
    public function addSocialNetwork($socialnetwork)
    {
        $this->getSocialnetworks()->add($socialnetwork);
    }

}
</code>```

The Class where Socialnetworks for Users are stored:

```<code><?php

namespace AppBundle\Entity\Registration;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * UserInSocialNetworks
 *
 * @ORM\Table(name="user_in_social_networks")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\Registration\UserInSocialNetworksRepository")
 */
class UserInSocialNetworks
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="socialnetworks")
     * @ORM\JoinColumn(name="user_id")
     * @var User
     *
     */
    private $userId;

    /**
     * @var int
     *
     * @ORM\Column(name="social_network_slug", type="string", length=255, nullable=true)
     */
    private $socialNetworkSlug;

    /**
     * @var string
     *
     * @ORM\Column(name="social_identifier", type="string", length=255, nullable=true)
     */
    private $socialIdentyfier;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set userId
     *
     * @param integer $userId
     *
     * @return UserInSocialNetworks
     */
    public function setUserId($userId)
    {
        $this->userId = $userId;

        return $this;
    }

    /**
     * Get userId
     *
     * @return int
     */
    public function getUserId()
    {
        return $this->userId;
    }

    /**
     * @return int
     */
    public function getSocialNetworkSlug()
    {
        return $this->socialNetworkSlug;
    }

    /**
     * @param int $socialNetworkSlug
     */
    public function setSocialNetworkSlug($socialNetworkSlug)
    {
        $this->socialNetworkSlug = $socialNetworkSlug;
    }

    /**
     * @return string
     */
    public function getSocialIdentyfier()
    {
        return $this->socialIdentyfier;
    }

    /**
     * @param string $socialIdentyfier
     */
    public function setSocialIdentyfier($socialIdentyfier)
    {
        $this->socialIdentyfier = $socialIdentyfier;
    }

}
</code>```

This is what I get

```<code>object(Doctrine\ORM\PersistentCollection)[545]
  private 'snapshot' =>
    array (size=1) <------- just one
      0 =>
        object(AppBundle\Entity\Registration\UserInSocialNetworks)[336]
          private 'id' => int 5 <---- I added already 5 line with my code to database
          private 'userId' =>
            object(AppBundle\Entity\Registration\User)[516]
              ...
          private 'socialNetworkSlug' => string 'google' (length=6)
          private 'socialIdentyfier' => string 'blablabla@googlemail.com' (length=24)
</code>```

答:
sorry, my fault,
the solution was to correct the relations:

```<code>class UserInSocialNetworks
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Many Socialnetwork Logins have one User
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Registration\User", inversedBy="socialnetworks")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *
     */
    private $user;
</code>```

and

```<code>class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * One User can have many social networks
     * @ORM\OneToMany(targetEntity="UserInSocialNetworks", mappedBy="user", cascade={"remove"})
     */
    private $socialnetworks;
</code>```

Body:
I am working on a login page, where it should be possible to login with different socialnetwork logins (facebook, twitter, google, etc).
It should work like this: every user has the possibility to add the socialnetwork login that he/she wants, so I want to have it as an One User-> Many Socialnetworklogins relation.
What works: Data is stored in Database, but in the line
            var_dump($user->getSocialnetworks());
I just get one Object, not all the ones that should be related to this user. I know that the function justATest adds just a socialnetworklogin to user 1, this was just a test.

<?php
namespace AppBundle\Entity\Registration;

use Doctrine\Common\Collections\ArrayCollection;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
use Symfony\Component\Security\Core\User\UserInterface;

class FOSUBUserProvider extends BaseClass
{
public function justATest(UserResponseInterface $response)
    {
        // get user_id and socialnetworkname from response
        $userIdInSocialNetwork = $response->getUsername();
        $socialnetwork = $response->getResourceOwner()->getName();
        $login= new UserInSocialNetworks();
        $login->setSocialIdentyfier($response->getEmail());
        $login->setSocialNetworkSlug($socialnetwork);

        $user = $this->userManager->findUserBy(array(
                'id' => 1)
        );
        $login->setUserId($user);
        $user->addSocialNetwork($login);
        $this->userManager->updateUser($user);
        $users= $this->userManager->findUsers();
        var_dump($users);
        var_dump($socialnetwork);
        var_dump($user->getSocialnetworks());
        die();
} }

The User Class:

<?php

/*
 * This is the User class, depending on fos_userBundle
 */

namespace AppBundle\Entity\Registration;

use Doctrine\Common\Collections\ArrayCollection as ArrayCollection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="UserInSocialNetworks", mappedBy="user_id", cascade={"persist", "remove"})
     * @var ArrayCollection|null

     */
    private $socialnetworks;

    /**
     * @var string
     *
     * @ORM\Column(name="family_name",type="string", length=255, nullable=true)
     */
    private $familyName;

    /**
     * @var string
     *
     * @ORM\Column(name="given_name",type="string", length=255, nullable=true)
     */
    private $givenName;

    public function __construct()
    {
        parent::__construct();
        $this->socialnetworks = new ArrayCollection();
    }

    /**
     * @return string
     */
    public function getFamilyName()
    {
        return $this->familyName;
    }

    /**
     * @param string $familyName
     */
    public function setFamilyName($familyName)
    {
        $this->familyName = $familyName;
    }

    /**
     * @return string
     */
    public function getGivenName()
    {
        return $this->givenName;
    }

    /**
     * @param string $givenName
     */
    public function setGivenName($givenName)
    {
        $this->givenName = $givenName;
    }

    /**
     * @return ArrayCollection
     */
    public function getSocialnetworks()
    {
        return $this->socialnetworks;
    }

    /**
     * @param Collection UserInSocialNetworks
     */
    public function setSocialnetworks($socialnetworks)
    {
        $this->socialnetworks = $socialnetworks;
    }

    /**
     * @param UserInSocialNetwork
     */
    public function addSocialNetwork($socialnetwork)
    {
        $this->getSocialnetworks()->add($socialnetwork);
    }

}

The Class where Socialnetworks for Users are stored:

<?php

namespace AppBundle\Entity\Registration;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * UserInSocialNetworks
 *
 * @ORM\Table(name="user_in_social_networks")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\Registration\UserInSocialNetworksRepository")
 */
class UserInSocialNetworks
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="socialnetworks")
     * @ORM\JoinColumn(name="user_id")
     * @var User
     *
     */
    private $userId;

    /**
     * @var int
     *
     * @ORM\Column(name="social_network_slug", type="string", length=255, nullable=true)
     */
    private $socialNetworkSlug;

    /**
     * @var string
     *
     * @ORM\Column(name="social_identifier", type="string", length=255, nullable=true)
     */
    private $socialIdentyfier;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set userId
     *
     * @param integer $userId
     *
     * @return UserInSocialNetworks
     */
    public function setUserId($userId)
    {
        $this->userId = $userId;

        return $this;
    }

    /**
     * Get userId
     *
     * @return int
     */
    public function getUserId()
    {
        return $this->userId;
    }

    /**
     * @return int
     */
    public function getSocialNetworkSlug()
    {
        return $this->socialNetworkSlug;
    }

    /**
     * @param int $socialNetworkSlug
     */
    public function setSocialNetworkSlug($socialNetworkSlug)
    {
        $this->socialNetworkSlug = $socialNetworkSlug;
    }

    /**
     * @return string
     */
    public function getSocialIdentyfier()
    {
        return $this->socialIdentyfier;
    }

    /**
     * @param string $socialIdentyfier
     */
    public function setSocialIdentyfier($socialIdentyfier)
    {
        $this->socialIdentyfier = $socialIdentyfier;
    }

}

This is what I get

object(Doctrine\ORM\PersistentCollection)[545]
  private 'snapshot' =>
    array (size=1) <------- just one
      0 =>
        object(AppBundle\Entity\Registration\UserInSocialNetworks)[336]
          private 'id' => int 5 <---- I added already 5 line with my code to database
          private 'userId' =>
            object(AppBundle\Entity\Registration\User)[516]
              ...
          private 'socialNetworkSlug' => string 'google' (length=6)
          private 'socialIdentyfier' => string 'blablabla@googlemail.com' (length=24)

Body:
sorry, my fault,
the solution was to correct the relations:

class UserInSocialNetworks
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Many Socialnetwork Logins have one User
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Registration\User", inversedBy="socialnetworks")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *
     */
    private $user;

and

class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * One User can have many social networks
     * @ORM\OneToMany(targetEntity="UserInSocialNetworks", mappedBy="user", cascade={"remove"})
     */
    private $socialnetworks;


问:
How do I test a JSONP HTTP request in Angular?
I'm using the HttpClientModule and HttpClientJsonpModule to make a JSONP HTTP request in a service.

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    HttpClientJsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

This service uses the jsonp method from the HttpClient class to get a JSONP response from the specified URL. I think that this response is intercepted by JsonpInterceptor and sent to the JsonpClientBackend where the request is handled.

example.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ExampleService {
  url = "https://archive.org/index.php?output=json&callback=callback";

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.jsonp(this.url, 'callback');
  }
}
</code>```

Using the HttpClientTestingModule, I inject the HttpTestingController so I can mock and flush my JSONP HTTP request.

example.service.spec.ts

```<code>import { TestBed, inject } from '@angular/core/testing';
import {
  HttpClientTestingModule,
  HttpTestingController
} from '@angular/common/http/testing';

import { ExampleService } from './example.service';

describe('ExampleService', () => {
  let service: ExampleService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ExampleService]
    });

    service = TestBed.get(ExampleService);
    httpMock = TestBed.get(HttpTestingController);
  });

  describe('#getData', () => {
    it('should return an Observable<any>', () => {
      const dummyData = { id: 1 };

      service.getData().subscribe(data => {
        expect(data).toEqual(dummyData);
      });

      const req = httpMock.expectOne(service.url); // Error
      expect(req.request.method).toBe('JSONP');
      req.flush(dummyData);
    });
  });
});
</code>```

In the end, I get the error

Error: Expected one matching request for criteria "Match URL: https://archive.org/index.php?output=json&callback=callback", found none.

If I change the request method to GET, this test works as expected.

From what I can tell, the HttpClientTestingModule uses the HttpClientTestingBackend but there is no JsonpClientTestingBackend or corresponding interceptor.

How do I test a JSONP HTTP request in Angular?

答:
According to an Angular developer this is a bug. Here's a workaround for now.

example.service.spec.ts

```<code>import { TestBed, inject } from '@angular/core/testing';
// Import the HttpClientJsonpModule, HttpBackend, and JsonpClientBackend
import { HttpClientJsonpModule, HttpBackend, JsonpClientBackend } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { ExampleService } from './example.service';

describe('ExampleService', () => {
  let service: ExampleService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      // Use the HttpBackend instead of the JsonpClientBackend
      providers: [ExampleService, { provide: JsonpClientBackend, useExisting: HttpBackend }]
    });

    service = TestBed.get(ExampleService);
    httpMock = TestBed.get(HttpTestingController);
  });

  describe('#getData', () => {
    it('should return an Observable<any>', () => {
      const dummyData = { id: 1 };

      service.getData().subscribe(data => {
        expect(data).toEqual(dummyData);
      });
      // Pass a function to the expectOne method
      const req = httpMock.expectOne(request => request.url === service.url);
      expect(req.request.method).toBe('JSONP');
      req.flush(dummyData);
    });
  });
});
</code>```

Body:
I'm using the HttpClientModule and HttpClientJsonpModule to make a JSONP HTTP request in a service.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    HttpClientJsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

This service uses the jsonp method from the HttpClient class to get a JSONP response from the specified URL. I think that this response is intercepted by JsonpInterceptor and sent to the JsonpClientBackend where the request is handled.

example.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ExampleService {
  url = "https://archive.org/index.php?output=json&callback=callback";

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.jsonp(this.url, 'callback');
  }
}

Using the HttpClientTestingModule, I inject the HttpTestingController so I can mock and flush my JSONP HTTP request.

example.service.spec.ts

import { TestBed, inject } from '@angular/core/testing';
import {
  HttpClientTestingModule,
  HttpTestingController
} from '@angular/common/http/testing';

import { ExampleService } from './example.service';

describe('ExampleService', () => {
  let service: ExampleService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ExampleService]
    });

    service = TestBed.get(ExampleService);
    httpMock = TestBed.get(HttpTestingController);
  });

  describe('#getData', () => {
    it('should return an Observable<any>', () => {
      const dummyData = { id: 1 };

      service.getData().subscribe(data => {
        expect(data).toEqual(dummyData);
      });

      const req = httpMock.expectOne(service.url); // Error
      expect(req.request.method).toBe('JSONP');
      req.flush(dummyData);
    });
  });
});

In the end, I get the error

Error: Expected one matching request for criteria "Match URL: https://archive.org/index.php?output=json&callback=callback", found none.

If I change the request method to GET, this test works as expected.

From what I can tell, the HttpClientTestingModule uses the HttpClientTestingBackend but there is no JsonpClientTestingBackend or corresponding interceptor.

How do I test a JSONP HTTP request in Angular?

Body:
According to an Angular developer this is a bug. Here's a workaround for now.

example.service.spec.ts

import { TestBed, inject } from '@angular/core/testing';
// Import the HttpClientJsonpModule, HttpBackend, and JsonpClientBackend
import { HttpClientJsonpModule, HttpBackend, JsonpClientBackend } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { ExampleService } from './example.service';

describe('ExampleService', () => {
  let service: ExampleService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      // Use the HttpBackend instead of the JsonpClientBackend
      providers: [ExampleService, { provide: JsonpClientBackend, useExisting: HttpBackend }]
    });

    service = TestBed.get(ExampleService);
    httpMock = TestBed.get(HttpTestingController);
  });

  describe('#getData', () => {
    it('should return an Observable<any>', () => {
      const dummyData = { id: 1 };

      service.getData().subscribe(data => {
        expect(data).toEqual(dummyData);
      });
      // Pass a function to the expectOne method
      const req = httpMock.expectOne(request => request.url === service.url);
      expect(req.request.method).toBe('JSONP');
      req.flush(dummyData);
    });
  });
});


问:
How do I turn off COMMAND mode or VISUAL mode in Sublime?
In Sublime Text 2, if I press escape the page goes into COMMAND mode, which seems to take text input as commands, rather than actually typing the text.

Another oddity is the VISUAL mode, and I have no idea what it does besides it seems to highlight text.

I think they came installed with the theme that I got, 'soda', maybe. Anyway, I searched and found out you can turn off COMMAND mode by pressing 'i'.

Regardless, both of these modes are extremely annoying, how do I get rid of them?

答:
This happened to me. In the default preferences it was set to:

```<code>"ignored_packages": ["Vintage"]
</code>```

but in my user preferences it was set to:

```<code>"ignored_packages": []
</code>```

Make sure that the value is not being overridden.

Body:
This happened to me. In the default preferences it was set to:

"ignored_packages": ["Vintage"]

but in my user preferences it was set to:

"ignored_packages": []

Make sure that the value is not being overridden.


问:
Handling push notification while application is on background
I am trying to fire a procedure or service when receiving a push notification, however I want to do this while the application is running in the background.

I have already tested that it works with the application on foreground, but also need it to do some work when in background if receiving the notification.

I have asked around and have been told that cannot be done, however i would like to ask here to confirm it, thanks in advance.

答:
When your app is in the background, Android directs notification messages to the system tray

On Android, when your app is on foreground and a push notification is sent from your server side with both 'notification' and 'data' keys, OnMessageReceived method in your FireBaseMessagingService will be called. In this same case, when your app is in background, OnMessageReceive will not be called.

However, when a push notification is sent from your server side with only the 'data' key, OnMessageReceive will be called even if your app is running in background or foreground BUT you will have to handle the insertion of the notification in the user's notification tray yourself


问:
How to choose the correct left shift in bit wise operations?
I am learning bare metal programming in c++ and it often involves setting a portion of a 32 bit hardware register address to some combination.

For example for an IO pin, I can set the 15th to 17th bit in a 32 bit address to 001 to mark the pin as an output pin.

I have seen code that does this and I half understand it based on an explanation of another SO question.

```<code># here ra is a physical address
# the 15th to 17th bits are being
# cleared by AND-ing it with a value that is one everywhere
# except in the 15th to 17th bits
ra&=~(7<<12);
</code>```

Another example is:

```<code># this clears the 21st to 23rd bits of another address
ra&=~(7<<21);
</code>```

How do I choose the 7 and how do I choose the number of bits to shift left?

I tried this out in python to see if I can figure it out

```<code>bin((7<<21)).lstrip('-0b').zfill(32)
'00000000111000000000000000000000'
# this has 8, 9 and 10 as the bits which is wrong
</code>```

答:
How do I choose the 7

You want to clear three adjacent bits. Three adjacent bits at the bottom of a word is 1+2+4=7.

and how do I choose the number of bits to shift left

You want to clear bits 21-23, not bits 1-3, so you shift left another 20.

Both your examples are wrong. To clear 15-17 you need to shift left 14, and to clear 21-23 you need to shift left 20.

this has 8, 9,and 10 ...

No it doesn't. You're counting from the wrong end.

Body:
I am learning bare metal programming in c++ and it often involves setting a portion of a 32 bit hardware register address to some combination.

For example for an IO pin, I can set the 15th to 17th bit in a 32 bit address to 001 to mark the pin as an output pin.

I have seen code that does this and I half understand it based on an explanation of another SO question.

# here ra is a physical address
# the 15th to 17th bits are being
# cleared by AND-ing it with a value that is one everywhere
# except in the 15th to 17th bits
ra&=~(7<<12);

Another example is:

# this clears the 21st to 23rd bits of another address
ra&=~(7<<21);

How do I choose the 7 and how do I choose the number of bits to shift left?

I tried this out in python to see if I can figure it out

bin((7<<21)).lstrip('-0b').zfill(32)
'00000000111000000000000000000000'
# this has 8, 9 and 10 as the bits which is wrong


问:
Multiprocessing a loop inside a loop inside a function
I wrote some code to break up a for loop into multiple processes to speed up calculations.

```<code>import numpy as np
import formfactors
from subdivide_loop import subdivide_loop
import multiprocessing

def worker(start, end, triangleI, areaI, scene, kdtree, samples, output):
    form_factors = np.zeros(end-start)
    for j in range(start, end):
        triangleJ = np.array(scene[j][0:4])
        form_factors[start] = formfactors.uniform(triangleJ, triangleI, areaI, kdtree, samples)
    result = output.get(block=True)
    for j in range(start, end):
        result[j] = form_factors[j]
    output.put(result)

def calculate_formfactors(start, end, triangleI, areaI, scene, kdtree, samples, output, nb_processes,
                          max_interval_length):
    intervals = subdivide_loop(start, end, max_interval_length, nb_processes)
    print("start")
    jobs = []
    for k in range(nb_processes):
        p = multiprocessing.Process(target=worker,
                                    args=(intervals[k][0], intervals[k][1], triangleI, areaI, scene, kdtree,
                                          samples, output))
        jobs.append(p)
    for p in jobs:
        p.start()
    for p in jobs:
        p.join()
    results = output.get()
    return results
</code>```

I would like to be able to call calculate_formfactors() inside a function inside a loop, like this:

```<code>def outer_function():
    for i in range(1000):
        for j in range(i + 1, 1000, max_interval_length):
            form_factors = calculate_formfactors(args)
</code>```

But running this gives an error:

```<code>An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.

This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:

    if __name__ == '__main__':
        freeze_support()
        ...
</code>```

Because of how the outer function works, breaking up outer_function() instead of calculate_formfactors() is not possible.

So, any advice on how to do this?

答:
As the error suggests, make sure your outer_function() (or whatever initiates it) is called from within an __main__ guard, e.g.

```<code>if __name__ == "__main__":
    outer_function()
</code>```

It doesn't have to be the outer_function() but you need to trace it all back to the first step that initializes the chain that ultimately leads to the call to multiprocessing.Process() and put it within the above block.

This is because on non-forking systems multiple processes are essentially run as subprocesses so creating new processes from the main script would end up with an infinite recursion/processes spawning. You can read more about it in this answer. Because of that, you have to make sure your multiprocessing initialization code executes only once which is where the __main__ guard comes in.

Body:
I wrote some code to break up a for loop into multiple processes to speed up calculations.

import numpy as np
import formfactors
from subdivide_loop import subdivide_loop
import multiprocessing

def worker(start, end, triangleI, areaI, scene, kdtree, samples, output):
    form_factors = np.zeros(end-start)
    for j in range(start, end):
        triangleJ = np.array(scene[j][0:4])
        form_factors[start] = formfactors.uniform(triangleJ, triangleI, areaI, kdtree, samples)
    result = output.get(block=True)
    for j in range(start, end):
        result[j] = form_factors[j]
    output.put(result)

def calculate_formfactors(start, end, triangleI, areaI, scene, kdtree, samples, output, nb_processes,
                          max_interval_length):
    intervals = subdivide_loop(start, end, max_interval_length, nb_processes)
    print("start")
    jobs = []
    for k in range(nb_processes):
        p = multiprocessing.Process(target=worker,
                                    args=(intervals[k][0], intervals[k][1], triangleI, areaI, scene, kdtree,
                                          samples, output))
        jobs.append(p)
    for p in jobs:
        p.start()
    for p in jobs:
        p.join()
    results = output.get()
    return results

I would like to be able to call calculate_formfactors() inside a function inside a loop, like this:

def outer_function():
    for i in range(1000):
        for j in range(i + 1, 1000, max_interval_length):
            form_factors = calculate_formfactors(args)

But running this gives an error:

An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.

This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:

    if __name__ == '__main__':
        freeze_support()
        ...

Because of how the outer function works, breaking up outer_function() instead of calculate_formfactors() is not possible.

So, any advice on how to do this?

Body:
As the error suggests, make sure your outer_function() (or whatever initiates it) is called from within an __main__ guard, e.g.

if __name__ == "__main__":
    outer_function()

It doesn't have to be the outer_function() but you need to trace it all back to the first step that initializes the chain that ultimately leads to the call to multiprocessing.Process() and put it within the above block.

This is because on non-forking systems multiple processes are essentially run as subprocesses so creating new processes from the main script would end up with an infinite recursion/processes spawning. You can read more about it in this answer. Because of that, you have to make sure your multiprocessing initialization code executes only once which is where the __main__ guard comes in.


问:
NSMetaDataQuery never calls back with NSMetadataQueryDidFinishGatheringNotification
For an iCloud plugin I'm writing, I subscribe my iCloud manager class to these iCloud NSMetaDataQuery observers:

```<code>// Add a predicate for finding the documents
NSString* filePattern = [NSString stringWithFormat:@"*.%@", @"*"];

self.metadataQuery = [[NSMetadataQuery alloc] init];

// Before starting to query, it is required to set the search scope.
arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];

// It is also required to set a search predicate.
[self.metadataQuery setPredicate:[NSPredicate predicateWithFormat:@"%K LIKE %@", NSMetadataItemFSNameKey, filePattern]];

// Listen for the second phase live-updating
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(queryDidReceiveNotification:) name:NSMetadataQueryDidUpdateNotification object:nil];

// Listen for the first phase gathering
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(queryIsDoneGathering:) name:NSMetadataQueryDidFinishGatheringNotification
                                           object:nil];

[self.metadataQuery startQuery];
</code>```

The problem is that none of these selectors are actually ever called back, not even once, and I especially need the NSMetaDataQueryDidUpdateNotification to track upload/download progress of files in the cloud.

An odd thing is that I had this working the other day, but somehow it just stopped working and I've starred myself blind in trying to figure out what the problem actually is. By subscriping to the NSMetadataQueryDidStartGatheringNotification I can see that it does start, but it's like it never finishes. It is quite weird.

I was wondering if anyone have any clue at all as what to be wrong with the above code? Or where else I can look for the problem.

Thank you for your time :)

答:
This was quite the secret to dig up. I don't know if you've given up by now, but at long last, I might be able to help.

It turns out that for some (all?) C++ app configurations, there is a message pump that doesn't run automatically. In my app, I finally started getting my expected callbacks after placing a loop like this following my [m_query startQuery] call:

    // make it look syncronous for now
    while( m_state != finished )
    {
      Check_For_Interruption();
      [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:timeslice]]; //<--**this line is the key**
    }

where the callbacks are setup to correctly update the m_state variable.

My example just blocks, using it's own thread timeslice to run the loop (unless interrupted by a timeout being reached), but this could also be set up in an asynchronous way.

Another thing to note for those who go overboard on legacy support:

This method did cause the app to start leaking mach ports on OS X 10.9 and older. Haven't seen any problems on anything newer than that, though.

Body:
For an iCloud plugin I'm writing, I subscribe my iCloud manager class to these iCloud NSMetaDataQuery observers:

// Add a predicate for finding the documents
NSString* filePattern = [NSString stringWithFormat:@"*.%@", @"*"];

self.metadataQuery = [[NSMetadataQuery alloc] init];

// Before starting to query, it is required to set the search scope.
arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];

// It is also required to set a search predicate.
[self.metadataQuery setPredicate:[NSPredicate predicateWithFormat:@"%K LIKE %@", NSMetadataItemFSNameKey, filePattern]];

// Listen for the second phase live-updating
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(queryDidReceiveNotification:) name:NSMetadataQueryDidUpdateNotification object:nil];

// Listen for the first phase gathering
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(queryIsDoneGathering:) name:NSMetadataQueryDidFinishGatheringNotification
                                           object:nil];

[self.metadataQuery startQuery];

The problem is that none of these selectors are actually ever called back, not even once, and I especially need the NSMetaDataQueryDidUpdateNotification to track upload/download progress of files in the cloud.

An odd thing is that I had this working the other day, but somehow it just stopped working and I've starred myself blind in trying to figure out what the problem actually is. By subscriping to the NSMetadataQueryDidStartGatheringNotification I can see that it does start, but it's like it never finishes. It is quite weird.

I was wondering if anyone have any clue at all as what to be wrong with the above code? Or where else I can look for the problem.

Thank you for your time :)


问:
Hide navbar when scrolling, but do it so that it's not animated but naturally 'scrolled away'
so hiding the navbar when scrolling simply by adding a class with "top: -50px" for example is easy. However, it doesn't feel very natural. It would be so much nicer, if the navbar would be hiding through actual scrolling, so that the speed of the scrolling always fits. Instead of animating it away, I want to scroll the navbar away and back onscreen (instantly away and after a certain amount of pixels of scrolling up back onscreen again).

How would you approach this?

By the way, I don't really want to use any JQuery for this, I'm using Vue.

答: You can use CSS transitions on top to animate it back and forth.  However you are triggering the hide when you scroll, you can add/remove classes to trigger the change.


问:
Bugzilla extension. How to check if custom field empty?

How to check condition if some custom field empty?

For example, it's possible to check that qa_contact is not set.

```<code>sub object_end_of_set_all {
    my ($self, $args) = @_;
    my $object = $args->{'object'};
    if ($object->{'bug_status'} eq 'RESOLVED') {
        if ($object->{'qa_contact'} eq "") {
            ThrowUserError("empty_qa_contact");
        }
    }
}
</code>```

Is there is same way for custom field e.g. cf_test ?

I know that to save custom field in variable, need to:

```<code>my $test = new Bugzilla::Field({ name => 'cf_test' });
</code>```

Which method can be used to get its value or check if it's not empty ?

答:
Found out two problems:
1. After executing ThrowUserError("...") any object (cf_test or even bugzilla fields) is always NULL.
2. If to use Hook "object_end_of_set_all" for custom field then only a cached values are showed for a custom field.

The answer is to use different Hook:

```<code>sub bug_end_of_update {
    my ($self, $args) = @_;
    my ($bug, $old_bug, $timestamp, $changes) = @$args{qw(bug old_bug timestamp changes)};
    if ($bug->bug_status eq 'RESOLVED') {
        if ($bug->cf_test eq "") {
            ThrowUserError("test_is_empty");
        }
    }
}
</code>```

Body:
How to check condition if some custom field empty?

For example, it's possible to check that qa_contact is not set.

sub object_end_of_set_all {
    my ($self, $args) = @_;
    my $object = $args->{'object'};
    if ($object->{'bug_status'} eq 'RESOLVED') {
        if ($object->{'qa_contact'} eq "") {
            ThrowUserError("empty_qa_contact");
        }
    }
}

Is there is same way for custom field e.g. cf_test ?

I know that to save custom field in variable, need to:

my $test = new Bugzilla::Field({ name => 'cf_test' });

Which method can be used to get its value or check if it's not empty ?

Body:
Found out two problems:
1. After executing ThrowUserError("...") any object (cf_test or even bugzilla fields) is always NULL.
2. If to use Hook "object_end_of_set_all" for custom field then only a cached values are showed for a custom field.

The answer is to use different Hook:

sub bug_end_of_update {
    my ($self, $args) = @_;
    my ($bug, $old_bug, $timestamp, $changes) = @$args{qw(bug old_bug timestamp changes)};
    if ($bug->bug_status eq 'RESOLVED') {
        if ($bug->cf_test eq "") {
            ThrowUserError("test_is_empty");
        }
    }
}


问:
How to know if data was persisted during database transaction after method returning?
I have a method written in a Grails service, which processes a lot of data.

I noticed that, sometimes, the method returns success but the data is not persisted to the database.

I debugged it, following all the data till the end of the method and everything is fine, however data is not persisted.

The following image demonstrates the what I just explained. You can see the end of the method, in which a Map object is filled with persistent object metadata. Even you can see the console which contains the printend Hibertate SQL

How can I detect whether a rollback mechanism is thrown after successful method returning?

This is my connection properties for Oracle 12c database. Others configurations are Grails defaults

```<code>dataSource.pooled=true
hibernate.jdbc.use_get_generated_keys=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=false
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
dataSource.driverClassName=oracle.jdbc.driver.OracleDriver
dataSource.dialect=org.hibernate.dialect.OracleDialect

dataSource.url=jdbc:oracle:thin:@172.16.1.20:1521:db
dataSource.username=<USER>
dataSource.password=<PASS>
hibernate.default_schema=<SCHEMA>
</code>```

The service is anotated as @Transactional

```<code>@Transactional
class SincronizacionService {

}
</code>```

Any Idea?

答:
I found the error!

An error thrown inside a method for generating a PDF document with data, appearsto be failing. The second line shows this

```<code>        try {
            denuncia.xmlFirmadoServ = dfileManagerService.guardarDFile(signatureResponse.resultado, "xmlfirmadoservidor.xml", usuario)
            denuncia = actaDenunciaService.generarActaDenuncia(denuncia).denuncia
        } catch (Throwable t) {
            denunciaUtilService.incrementarNumeroDenuncia(true)
            throw t
        }
</code>```

Now, the new question is: If the method is encapsulated inside a try/catchblock, why the catch block is not excecuting?

When I comment the 2nd line inside try/catch block, data is persisted on database

With no comments, generation PDF method is executed till the end, doing all what it must do

Body:
I have a method written in a Grails service, which processes a lot of data.

I noticed that, sometimes, the method returns success but the data is not persisted to the database.

I debugged it, following all the data till the end of the method and everything is fine, however data is not persisted.

The following image demonstrates the what I just explained. You can see the end of the method, in which a Map object is filled with persistent object metadata. Even you can see the console which contains the printend Hibertate SQL

How can I detect whether a rollback mechanism is thrown after successful method returning?

This is my connection properties for Oracle 12c database. Others configurations are Grails defaults

dataSource.pooled=true
hibernate.jdbc.use_get_generated_keys=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=false
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
dataSource.driverClassName=oracle.jdbc.driver.OracleDriver
dataSource.dialect=org.hibernate.dialect.OracleDialect

dataSource.url=jdbc:oracle:thin:@172.16.1.20:1521:db
dataSource.username=<USER>
dataSource.password=<PASS>
hibernate.default_schema=<SCHEMA>

The service is anotated as @Transactional

@Transactional
class SincronizacionService {

}

Any Idea?

Body:
I found the error!

An error thrown inside a method for generating a PDF document with data, appearsto be failing. The second line shows this

        try {
            denuncia.xmlFirmadoServ = dfileManagerService.guardarDFile(signatureResponse.resultado, "xmlfirmadoservidor.xml", usuario)
            denuncia = actaDenunciaService.generarActaDenuncia(denuncia).denuncia
        } catch (Throwable t) {
            denunciaUtilService.incrementarNumeroDenuncia(true)
            throw t
        }

Now, the new question is: If the method is encapsulated inside a try/catchblock, why the catch block is not excecuting?

When I comment the 2nd line inside try/catch block, data is persisted on database

With no comments, generation PDF method is executed till the end, doing all what it must do


问:
What are the File Permission Signs @ and + for?
My mac has folders Shared and Public folders. Their permissions are drwxr-xr-x+ for Public and drwxrwxrwt@ for Shared. What do the signs + and @ mean?</p>

答:
@ means there are "extended attributes". Type

```<code>ls -l@
</code>```

to see what they are. With that command, everything with a @ after it will have some extra lines explaining why it has a @. In my experience, the @ usually means a file is going to be opened with an application other than the default (i.e. it might open with a different text editor than you're used to), or occasionally that it's in a different encoding than the default specified by $LANG.

From the manpage for "ls":

If the file or directory has extended attributes, the permissions field printed by the -l option is followed by a '@' character.  Otherwise, if the file or directory has extended security information, the permissions field printed by the -l option is followed by a '+' character.

OwnerDisplayName: HL

LastEditorDisplayName: GregD

Body:
@ means there are "extended attributes". Type

ls -l@

to see what they are. With that command, everything with a @ after it will have some extra lines explaining why it has a @. In my experience, the @ usually means a file is going to be opened with an application other than the default (i.e. it might open with a different text editor than you're used to), or occasionally that it's in a different encoding than the default specified by $LANG.

From the manpage for "ls":

If the file or directory has extended attributes, the permissions field printed by the -l option is followed by a '@' character.  Otherwise, if the file or directory has extended security information, the permissions field printed by the -l option is followed by a '+' character.

OwnerDisplayName: Chris Lutz