问:
How to check whether dynamically attached event listener exists or not?
Here is my problem: is it somehow possible to check for the existence of a dynamically attached event listener? Or how can I check the status of the "onclick" (?) property in the DOM? I have searched the internet just like Stack Overflow for a solution, but no luck. Here is my html:

 link 1
 link 2
```
<p>Then in Javascript I attach a dynamically created event listener to the 2nd link:</p>
<pre class="lang-js prettyprint-override"><code>document.getElementById('link2').addEventListener('click', linkclick, false);
</code>```

The code runs well, but all my attempts to detect that attached listener fail:

// test for #link2 - dynamically created eventlistener
alert(elem.onclick); // null
alert(elem.hasAttribute('onclick')); // false
alert(elem.click); // function click(){[native code]} // btw, what's this?
```

jsFiddle is here.
If you click "Add onclick for 2" and then "[link 2]", the event fires well,
but the "Test link 2" always reports false.
Can somebody help?

答:
I did something like that:

```<code>const element = document.getElementById('div');

if (element.getAttribute('listener') !== 'true') {
     element.addEventListener('click', function (e) {
         const elementClicked = e.target;
         elementClicked.setAttribute('listener', 'true');
         console.log('event has been attached');
    });
}
</code>```

Creating a special attribute for an element when the listener is attached and then checking if it exists.

Body:
Here is my problem: is it somehow possible to check for the existence of a dynamically attached event listener? Or how can I check the status of the "onclick" (?) property in the DOM? I have searched the internet just like Stack Overflow for a solution, but no luck. Here is my html:

 link 1
 link 2

Then in Javascript I attach a dynamically created event listener to the 2nd link:

document.getElementById('link2').addEventListener('click', linkclick, false);

The code runs well, but all my attempts to detect that attached listener fail:

// test for #link2 - dynamically created eventlistener
alert(elem.onclick); // null
alert(elem.hasAttribute('onclick')); // false
alert(elem.click); // function click(){[native code]} // btw, what's this?

jsFiddle is here.
If you click "Add onclick for 2" and then "[link 2]", the event fires well,
but the "Test link 2" always reports false.
Can somebody help?

Body:
I did something like that:

const element = document.getElementById('div');

if (element.getAttribute('listener') !== 'true') {
     element.addEventListener('click', function (e) {
         const elementClicked = e.target;
         elementClicked.setAttribute('listener', 'true');
         console.log('event has been attached');
    });
}

Creating a special attribute for an element when the listener is attached and then checking if it exists.


来源: stackexchange

问:
How to generate serial number in a query?
We're using PostgreSQL v8.2.3.

How do I generate serial number in the query output?  I want to display serial number for each row returned by the query.

Example: SELECT employeeid, name FROM employee

I expect to generate and display serial number against each row starting from one.

答:
You have two options.

Either upgrade to PostgreSQL v8.4 and use the row_number() function:

```<code>SELECT row_number() over (ORDER BY something) as num_by_something, *
FROM table
ORDER BY something;
</code>```

Or jump through some hoops as described in Simulating Row Number in PostgreSQL Pre 8.4.

ContentLicense: CC BY-SA 2.5

Body:
You have two options.

Either upgrade to PostgreSQL v8.4 and use the row_number() function:

SELECT row_number() over (ORDER BY something) as num_by_something, *
FROM table
ORDER BY something;

Or jump through some hoops as described in Simulating Row Number in PostgreSQL Pre 8.4.


问:
grep range of numbers
For the following text I need to count the lines that the number between parenthesis is in the range [10-20].

    This function's cyclomatic complexity is too high. (1)
    This function's cyclomatic complexity is too high. (2)
    This function's cyclomatic complexity is too high. (3)
    This function's cyclomatic complexity is too high. (4)
    This function's cyclomatic complexity is too high. (5)
    This function's cyclomatic complexity is too high. (6)
    This function's cyclomatic complexity is too high. (7)
    This function's cyclomatic complexity is too high. (8)
    This function's cyclomatic complexity is too high. (9)
    This function's cyclomatic complexity is too high. (10)
    This function's cyclomatic complexity is too high. (12)
    This function's cyclomatic complexity is too high. (13)
    This function's cyclomatic complexity is too high. (14)
    This function's cyclomatic complexity is too high. (15)
    This function's cyclomatic complexity is too high. (16)
    This function's cyclomatic complexity is too high. (17)
```

<p>Im trying the following commands:</p>

```cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10-20])"
cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10,11,12,13,14,15,16,17,18,20])"
```

But didnt work. Whats the correct way to do it?

答:
I do not have access to a terminal so this is untested, but try cat pruebascript.txt | grep -c "This function's cyclomatic complexity is too high. (1[0-9]|20)". Your regular expression in grep asks for 1 or 2, and 2 or 0.

1[0-9] will match anything between 10 to 19 as well as 20.

Read more about numeric ranges regex:
https://www.regular-expressions.info/numericranges.html

ContentLicense: CC BY-SA 4.0

Title: grep range of numbers

Body:
For the following text I need to count the lines that the number between parenthesis is in the range [10-20].

    This function's cyclomatic complexity is too high. (1)
    This function's cyclomatic complexity is too high. (2)
    This function's cyclomatic complexity is too high. (3)
    This function's cyclomatic complexity is too high. (4)
    This function's cyclomatic complexity is too high. (5)
    This function's cyclomatic complexity is too high. (6)
    This function's cyclomatic complexity is too high. (7)
    This function's cyclomatic complexity is too high. (8)
    This function's cyclomatic complexity is too high. (9)
    This function's cyclomatic complexity is too high. (10)
    This function's cyclomatic complexity is too high. (12)
    This function's cyclomatic complexity is too high. (13)
    This function's cyclomatic complexity is too high. (14)
    This function's cyclomatic complexity is too high. (15)
    This function's cyclomatic complexity is too high. (16)
    This function's cyclomatic complexity is too high. (17)

Im trying the following commands:

cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10-20])"
cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10,11,12,13,14,15,16,17,18,20])"

But didnt work. Whats the correct way to do it?

ContentLicense: CC BY-SA 3.0


问:
iScroll not working in iOS device
I already have an app. Im trying to integrate iScroll for faster scroll in iOS.

So created iScroll instance on the element having "overflow:auto" as specified in http://iscrolljs.com

Android has no issues. But iOS doesn't scroll at all.

Anything else do I need to do to let this work in iOS ?

答:
I think my answer can help someone who is stuck with iScroll.

In the existing app, just check if there are any transitions already added on the element. As these will override the transition added by iScroll.

in iOS 10 scrolling is not smooth, use {'useTransition': false} for smooth scroll. But iOS 11 works fine without this.

These will be ignored sometimes.

Title: iScroll not working in iOS device


问:
Hashing Algorithm for passwords
I am looking for hashing algorithm to be used in my current application for password encryption. I came across this link

https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet

Argon2[*7] is the winner of the password hashing competition and should be considered as your first choice for new applications;
PBKDF2 [*4] when FIPS certification or enterprise support on many platforms is required;
scrypt [*5] where resisting any/all hardware accelerated attacks is necessary but support isn’t.
bcrypt where PBKDF2 or scrypt support is not available.

I have not used any of these earlier projects, i know of SHa-256. But i would like to know which one is the best algorithm to encrypt passwords.
considering compute, memory used, return hash value length, whether we need to use salt value or not.

They also suggest Argon2 , but it is relatively new. can we use it? is it recommended?

Any suggestions on these.

答:
When saving a password verifier just using a hash function is not sufficient and just adding a salt does little to improve the security.

Instead iterate over an HMAC with a random salt for about a 100ms duration and save the salt with the hash.

Better yet use a function such as PBKDF2, Rfc2898DeriveBytes, Argon2, password_hash, Bcrypt or similar functions.

The point is to make the attacker spend substantial of time finding passwords by brute force.

PBKDF2 also known as Rfc2898 and Rfc2898DeriveBytes is the current NIST approved method, Argon2 is an even better solution but is not as widely available.

Title: Hashing Algorithm for passwords


问:
Websocket issue Internet Explorer
My app collects news and is fed by a websocket that periodically provides the data to show, the cadence of news is changeable and depends on when the vendors emit them.
When the app is opened in Internet Explorer, if no new items are received, the connection is stopped suddenly after about 20 seconds.

By doing some research I managed to bring the problem back to this specific Internet Explorer behavior:

https://connect.microsoft.com/IE/feedback/details/804653/rfc6455-websocket-pong-frame

In practice I found that IE sends Pong control frames, but if it does not receive a Ping response, it closes the connection.
Unfortunately I can not change anything server side to handle this unsolicited message, I was wondering if there is a way to handle this abnormal IE behavior from inside my app.

答: It seems that the issue happend only if the webSocket remain in idle state for more than 20 secs. We simply raised the frequency of heartbeat messages from the server up to 1 message every 10 secs and the issue never happened again</p>

Title: Websocket issue Internet Explorer


问:
Access local file from browser using jquery or Javascript
I'm trying to access local file from Browser. The file is located in Client Computer under C drive.

I tried different solution but all gave me error Access is denied.

I know that almost all browsers have disabled this functionality, but isn't there any setting we can do in browser or in client computer to make it work.

Someone told me to install browser extension to make it work, but I don't know how to do that.

```<code>  try {
                var xmlhttp;
                if (window.XMLHttpRequest) {
                    xmlhttp = new XMLHttpRequest();
                }
                else {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }

                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4) {
                        var lines = xmlhttp.responseText;    //*here we get all lines from text file*
                        alert(lines);
                    }
                }

                xmlhttp.open("GET", "file:///E:\file.txt", true);
                xmlhttp.send();
            } catch (e) {
                alert(e);
            }
</code>```

Any help will be highly appreciated.

Thanks

答:
Unfortunately no, for security reasons you cannot automatically load a file from the user's Hard Drive.

What you can do is create an <input name="myFile" type="file"> and make the user manually select the file you need. This is the only way

Body:
I'm trying to access local file from Browser. The file is located in Client Computer under C drive.

I tried different solution but all gave me error Access is denied.

I know that almost all browsers have disabled this functionality, but isn't there any setting we can do in browser or in client computer to make it work.

Someone told me to install browser extension to make it work, but I don't know how to do that.

  try {
                var xmlhttp;
                if (window.XMLHttpRequest) {
                    xmlhttp = new XMLHttpRequest();
                }
                else {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }

                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4) {
                        var lines = xmlhttp.responseText;    //*here we get all lines from text file*
                        alert(lines);
                    }
                }

                xmlhttp.open("GET", "file:///E:\file.txt", true);
                xmlhttp.send();
            } catch (e) {
                alert(e);
            }

Any help will be highly appreciated.

Thanks


问:
Bridge multiple BlackBerry connections to increase bandwidth
I am interested in doing something like "link aggregation" over the data connection on multiple BlackBerry devices.
What tools are available to do this?  If I write this myself, how do I balance out the data across the different devices?  Can this be done entirely on the remote side - with just the BlackBerries and a computer, or will I need a server to connect all the data back together?</p>

答:
For data tethering, the easiest way is to play with routing table.  For example, you have 3 BlackBerries connected to one computer, and they will be shown as three different network adapters.

Now you can design your routing metrics by dividing IP address range.  Say, BB1 routes traffic to and from 1.1.1.1 to 70.255.255.255, BB2 routes 71.0.0.1 to 142.255.255.255, and all other traffic goes through BB3.  Ideally the three devices will have balanced load.

If you want to have something like trunking, i.e. triple bandwidth connecting to same IP/port, that will be challenging, because you're handling a three IP to one problem and you have no control over the IP addresses assigned to the BlackBerries (your ISP assign them to you).  In that case, having your own server as a relay makes sense, but I seriously doubt the usefulness.  Switch to LTE will be a much easier choice in this case.


问:
Display nothing when there is internet connection with react-native-offline
I am using the react-native-offline module. My intention is to display some error when there is no connection. I am using withNetworkConnectivity to display some red text when the internet is off. Here is my code:

```<code>import React from 'react';
import { View, Text } from 'react-native';
import { withNetworkConnectivity } from 'react-native-offline';

const ConnectionStatus = ({ isConnected }) => (
  <View style={styles.viewStyle}>
    <Text style={styles.textStyle}>{isConnected ? '' : 'You are offline. Make sure your device is connected'}</Text>
  </View>
);

const styles = {
  viewStyle: {
    height: 20,
    marginTop: 20,
    alignItems: 'center',
    flex: 0.1
  },
  textStyle: {
    alignSelf: 'center',
    color: 'red',
    fontSize: 20,
  }
};

export default withNetworkConnectivity()(ConnectionStatus);
</code>```

The problem however is that even when there is internet the space represented by the top View tag is still present. How do I make sure that my component only takes up space when there is not connection ?

答:
You have to optionally render your text component. </p>

```<code>const renderText = () => {
    if (!isConnected) {
        return <Text> Your error Text </Text>;
    }
};

const ConnectionStatus = ({ isConnected }) => (
  <View style={styles.viewStyle}>
    {renderText()}
  </View>
);
</code>```

Body:
I am using the react-native-offline module. My intention is to display some error when there is no connection. I am using withNetworkConnectivity to display some red text when the internet is off. Here is my code:

import React from 'react';
import { View, Text } from 'react-native';
import { withNetworkConnectivity } from 'react-native-offline';

const ConnectionStatus = ({ isConnected }) => (
  <View style={styles.viewStyle}>
    <Text style={styles.textStyle}>{isConnected ? '' : 'You are offline. Make sure your device is connected'}</Text>
  </View>
);

const styles = {
  viewStyle: {
    height: 20,
    marginTop: 20,
    alignItems: 'center',
    flex: 0.1
  },
  textStyle: {
    alignSelf: 'center',
    color: 'red',
    fontSize: 20,
  }
};

export default withNetworkConnectivity()(ConnectionStatus);

The problem however is that even when there is internet the space represented by the top View tag is still present. How do I make sure that my component only takes up space when there is not connection ?

Body:
You have to optionally render your text component.

const renderText = () => {
    if (!isConnected) {
        return <Text> Your error Text </Text>;
    }
};

const ConnectionStatus = ({ isConnected }) => (
  <View style={styles.viewStyle}>
    {renderText()}
  </View>
);


问:
Return array of custom class objects from dictionary
I have a super simple class I called a Tuple:

```<code>Private vals(1) As Integer
-----
Public Property Get x()

x = vals(0)

End Property
-----
Public Property Get y()

y = vals(1)

End Property
-----
Public Sub SetVals(x As Integer, y As Integer)

vals(0) = x
vals(1) = y

End Sub
</code>```

I have a dictionary which is populated with arrays of these Tuples:

```<code>for x = whatever to whatever
   Set t = New Tuple
   t.SetVals somevalue, someothervalue
   ReDim Preserve tupleArray(x)
   Set tupleArray(x) = t
next x
theDictionary.Add someKey, tupleArray
</code>```

I want to later retrieve the arrays from the dictionary but I'm struggling with it. Here's what I've tried

```<code>Sub DoStuffWithDictionary(dict as object, index as Integer)

Dim tupleArray() as Tuple

' Error: "Property let procedure not defined and property get procedure did not return an object"
tupleArray = dict.Items(index)

' Error: can't assign to array
Set tupleArray = dict.Items(index)

' Error: same as above
Dim tupleArray as Object

' Error: same as above
Dim tupleArray as Variant

End Sub
</code>```

Looping on the dictionary keys they all print out OK, I just can't get to the arrays.

答:
See the example below:

On every dictionary key iteration, you need to loop the inner array as well.

Tuple Class:

```<code>Private vals(1) As Long

Public Property Get X() As Long
    X = vals(0)
End Property

Public Property Get Y() As Long
    Y = vals(1)
End Property

Public Sub SetVals(ByVal X As Long, ByVal Y As Long)
    vals(0) = X
    vals(1) = Y
End Sub
</code>```

Test:

```<code>Sub TestTuple()

    Dim d As Scripting.Dictionary
    Dim t As Tuple
    Dim arr() As Variant
    Dim i As Long, ii As Long

    Set d = New Scripting.Dictionary

    For i = 1 To 3
        For ii = 0 To 3
            Set t = New Tuple
                t.SetVals i + ii + 10, i + ii + 20
            ReDim Preserve arr(ii)
            Set arr(ii) = t
        Next ii
        d.Add CStr(i), arr
        Erase arr
    Next i

    Dim Key As Variant
    For Each Key In d.Keys
        For i = 0 To UBound(d(Key))
            Debug.Print "X: " & d(Key)(i).X, "Y: " & d(Key)(i).Y
        Next i
        Debug.Print ""
    Next
End Sub
</code>```

Output:

```<code>X: 11         Y: 21
X: 12         Y: 22
X: 13         Y: 23
X: 14         Y: 24

X: 12         Y: 22
X: 13         Y: 23
X: 14         Y: 24
X: 15         Y: 25

X: 13         Y: 23
X: 14         Y: 24
X: 15         Y: 25
X: 16         Y: 26
</code>```

Edit:

You can declare your array as Tuple if you wish. See below:

```<code>Sub Test2()

    Dim arr() As Tuple
    Dim t As Tuple
    Dim i As Long

    For i = 0 To 4
        Set t = New Tuple
            t.SetVals i + 10, i + 20
            ReDim Preserve arr(i)
        Set arr(i) = t
    Next i

    For i = 0 To UBound(arr)
        Debug.Print arr(i).X, arr(i).Y
    Next
End Sub

 '10            20
 '11            21
 '12            22
 '13            23
 '14            24
</code>```

Body:
I have a super simple class I called a Tuple:

Private vals(1) As Integer
-----
Public Property Get x()

x = vals(0)

End Property
-----
Public Property Get y()

y = vals(1)

End Property
-----
Public Sub SetVals(x As Integer, y As Integer)

vals(0) = x
vals(1) = y

End Sub

I have a dictionary which is populated with arrays of these Tuples:

for x = whatever to whatever
   Set t = New Tuple
   t.SetVals somevalue, someothervalue
   ReDim Preserve tupleArray(x)
   Set tupleArray(x) = t
next x
theDictionary.Add someKey, tupleArray

I want to later retrieve the arrays from the dictionary but I'm struggling with it. Here's what I've tried

Sub DoStuffWithDictionary(dict as object, index as Integer)

Dim tupleArray() as Tuple

' Error: "Property let procedure not defined and property get procedure did not return an object"
tupleArray = dict.Items(index)

' Error: can't assign to array
Set tupleArray = dict.Items(index)

' Error: same as above
Dim tupleArray as Object

' Error: same as above
Dim tupleArray as Variant

End Sub

Looping on the dictionary keys they all print out OK, I just can't get to the arrays.

Body:
See the example below:

On every dictionary key iteration, you need to loop the inner array as well.

Tuple Class:

Private vals(1) As Long

Public Property Get X() As Long
    X = vals(0)
End Property

Public Property Get Y() As Long
    Y = vals(1)
End Property

Public Sub SetVals(ByVal X As Long, ByVal Y As Long)
    vals(0) = X
    vals(1) = Y
End Sub

Test:

Sub TestTuple()

    Dim d As Scripting.Dictionary
    Dim t As Tuple
    Dim arr() As Variant
    Dim i As Long, ii As Long

    Set d = New Scripting.Dictionary

    For i = 1 To 3
        For ii = 0 To 3
            Set t = New Tuple
                t.SetVals i + ii + 10, i + ii + 20
            ReDim Preserve arr(ii)
            Set arr(ii) = t
        Next ii
        d.Add CStr(i), arr
        Erase arr
    Next i

    Dim Key As Variant
    For Each Key In d.Keys
        For i = 0 To UBound(d(Key))
            Debug.Print "X: " & d(Key)(i).X, "Y: " & d(Key)(i).Y
        Next i
        Debug.Print ""
    Next
End Sub

Output:

X: 11         Y: 21
X: 12         Y: 22
X: 13         Y: 23
X: 14         Y: 24

X: 12         Y: 22
X: 13         Y: 23
X: 14         Y: 24
X: 15         Y: 25

X: 13         Y: 23
X: 14         Y: 24
X: 15         Y: 25
X: 16         Y: 26

Edit:

You can declare your array as Tuple if you wish. See below:

Sub Test2()

    Dim arr() As Tuple
    Dim t As Tuple
    Dim i As Long

    For i = 0 To 4
        Set t = New Tuple
            t.SetVals i + 10, i + 20
            ReDim Preserve arr(i)
        Set arr(i) = t
    Next i

    For i = 0 To UBound(arr)
        Debug.Print arr(i).X, arr(i).Y
    Next
End Sub

 '10            20
 '11            21
 '12            22
 '13            23
 '14            24


问:
Block form submit if no one checkbox checked
I need help because confused how to block form submit if no one checkbox checked.

var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');

$form.on('submit', function(e) {
  $.each($checkbox, function(index, value) {
    if (!$(value).is(':checked')) {
      alert('Opps! You not select friends.');
      e.preventDefault();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="send-invite-form">
  <input type="checkbox" class="invitation-friends" value="875" />
  <input type="checkbox" class="invitation-friends" value="394" />
  <button type="submit">Send</submit>
    </form></code>```

The code check every checkbox. I don't want it. I want if one checkbox checked, the form can submit. If no one checked, bail submit.

Please help.

答:
Since submit button is controlling form submit, I am controlling its enable/disable status based on checkbox click

window.onload = checkBoxEventAndOnSubmitFunctionality();

  function checkBoxEventAndOnSubmitFunctionality() {
    let checkBoxes = document.getElementsByClassName('invitation-friends');
    let checkBoxChecked = 0;

    for(i=0;i<checkBoxes.length;i++) {
       checkBoxes[i].onclick = function(e) {
          if(e.path[0].checked) checkBoxChecked += 1;
          else checkBoxChecked -= 1;
       }
    }
    document.getElementById("send-invite-form").onsubmit = function(e) {
      if(checkBoxChecked !=0) {
        alert("can submit");
         document.getElementById("send-invite-form").submit();
      }
      else {
        alert("can NOT submit");
        e.preventDefault();
      }
    }
  } ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="send-invite-form" onsubmit="checkForCheckBoxes" method="POST">
     <input type="checkbox" class="invitation-friends" value="875" />
     <input type="checkbox" class="invitation-friends" value="394" />

     <button type="submit" id="submitButton">Send</button>
</form></code>```

Body:
I need help because confused how to block form submit if no one checkbox checked.

var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');

$form.on('submit', function(e) {
  $.each($checkbox, function(index, value) {
    if (!$(value).is(':checked')) {
      alert('Opps! You not select friends.');
      e.preventDefault();
    }
  });
});

<form id="send-invite-form">
  <input type="checkbox" class="invitation-friends" value="875" />
  <input type="checkbox" class="invitation-friends" value="394" />
  <button type="submit">Send</submit>
    </form>

The code check every checkbox. I don't want it. I want if one checkbox checked, the form can submit. If no one checked, bail submit.

Please help.

Body:
Since submit button is controlling form submit, I am controlling its enable/disable status based on checkbox click

window.onload = checkBoxEventAndOnSubmitFunctionality();

  function checkBoxEventAndOnSubmitFunctionality() {
    let checkBoxes = document.getElementsByClassName('invitation-friends');
    let checkBoxChecked = 0;

    for(i=0;i<checkBoxes.length;i++) {
       checkBoxes[i].onclick = function(e) {
          if(e.path[0].checked) checkBoxChecked += 1;
          else checkBoxChecked -= 1;
       }
    }
    document.getElementById("send-invite-form").onsubmit = function(e) {
      if(checkBoxChecked !=0) {
        alert("can submit");
         document.getElementById("send-invite-form").submit();
      }
      else {
        alert("can NOT submit");
        e.preventDefault();
      }
    }
  }

<form id="send-invite-form" onsubmit="checkForCheckBoxes" method="POST">
     <input type="checkbox" class="invitation-friends" value="875" />
     <input type="checkbox" class="invitation-friends" value="394" />

     <button type="submit" id="submitButton">Send</button>
</form>


问:
How to call dropdown value from one java class(page) to another TestNG class(test) in selenium webdriver?
I want to select and store a dropdown value in one element in a page(java class) and call it from different class.

EX : i am doing like this for all other fields

```<code>public class Home_page {

    private static WebElement element = null;

    public static WebElement txtbox_FirstName(WebDriver driver) {
        element = driver.findElement(By.id("u_0_g"));
        return element;
    }
}

public class Action_createAccount {

    private static WebDriver driver = null;

    public static void main(String args[]) {

    System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
    driver.get("https://www.facebook.com/");

    Home_page.txtbox_FirstName(driver).sendKeys("Anu");
   }
}
</code>```

and this is working perfectly. I am not able to write code for drop down to work in the same way. Please help

答:
If you want to select birth day, the sample code is here. it may help you.</p>

```<code>public class Home_page {
    private static WebElement element = null;

    public static WebElement txtbox_FirstName(WebDriver driver) {
        element = driver.findElement(By.id("u_0_g"));
        return element;
    }
    Public static WebElement dropdown_BirthDay_Day(WebDriver driver){
        element = driver.findElement(By.id("day"));
        return element;
    }
    Public static WebElement dropdown_BirthDay_Month(WebDriver driver){
        element = driver.findElement(By.id("month"));
        return element;
    }Public static WebElement dropdown_BirthDay_Year(WebDriver driver){
        element = driver.findElement(By.id("year"));
        return element;
    }

}

public class Action_createAccount {

    private static WebDriver driver = null;

    public static void main(String args[]) {

        System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.get("https://www.facebook.com/");

        Home_page.txtbox_FirstName(driver).sendKeys("Anu");
        new Select(Home_page.dropdown_BirthDay_Day(driver)).selectByVisibleText("16");
        new Select(Home_page.dropdown_BirthDay_Month(driver)).selectByVisibleText("Nov");
        new Select(Home_page.dropdown_BirthDay_Year(driver)).selectByVisibleText("1990");
    }
}
</code>```

Body:
I want to select and store a dropdown value in one element in a page(java class) and call it from different class.

EX : i am doing like this for all other fields

public class Home_page {

    private static WebElement element = null;

    public static WebElement txtbox_FirstName(WebDriver driver) {
        element = driver.findElement(By.id("u_0_g"));
        return element;
    }
}

public class Action_createAccount {

    private static WebDriver driver = null;

    public static void main(String args[]) {

    System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
    driver.get("https://www.facebook.com/");

    Home_page.txtbox_FirstName(driver).sendKeys("Anu");
   }
}

and this is working perfectly. I am not able to write code for drop down to work in the same way. Please help

Body:
If you want to select birth day, the sample code is here. it may help you.

public class Home_page {
    private static WebElement element = null;

    public static WebElement txtbox_FirstName(WebDriver driver) {
        element = driver.findElement(By.id("u_0_g"));
        return element;
    }
    Public static WebElement dropdown_BirthDay_Day(WebDriver driver){
        element = driver.findElement(By.id("day"));
        return element;
    }
    Public static WebElement dropdown_BirthDay_Month(WebDriver driver){
        element = driver.findElement(By.id("month"));
        return element;
    }Public static WebElement dropdown_BirthDay_Year(WebDriver driver){
        element = driver.findElement(By.id("year"));
        return element;
    }

}

public class Action_createAccount {

    private static WebDriver driver = null;

    public static void main(String args[]) {

        System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.get("https://www.facebook.com/");

        Home_page.txtbox_FirstName(driver).sendKeys("Anu");
        new Select(Home_page.dropdown_BirthDay_Day(driver)).selectByVisibleText("16");
        new Select(Home_page.dropdown_BirthDay_Month(driver)).selectByVisibleText("Nov");
        new Select(Home_page.dropdown_BirthDay_Year(driver)).selectByVisibleText("1990");
    }
}


问:
I want the variable to be accessed from anywhere
Here i want to access the variable "finalPrice " in another function, how can i achive this?</p>

```<code>  function available(id){
    $.ajax({
        method:"GET",
    }).done(function(data){

     for(j=0; j<available_location.length; j++) {

            var finalPrice =available_location[j].price_details.final_price;
   };
});

function razorpay() {
    $.ajax({
        url : 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type : 'GET',
        data : {

         },
        success: function(data){
              alert(finalPrice );
           }
    });
}
</code>```

答:
If the second call require the first, use of callbacks. If it doesn't call boths, and wait for both answers before you perform the treatment which is to calculate the finalPrice and use it.

It is bad to create a global variable named finalPrice because I'm pretty sure you are running theses both request in parralel, which would result to uncertain behavior if razorpay resolve before available.

First case example

```<code> function available(id, callback) {
  $.ajax({
    method: "GET",
  }).done(function(data) {

    var finalPrice = 0;

    for (j = 0; j < available_location.length; j++) {
      finalPrice = available_location[j].price_details.final_price;
    }

    callback(finalPrice);
  });

  function razorpay(finalPrice) {
    $.ajax({
      url: 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
      type: 'GET',
      data: {

      },
      success: function(data) {
        alert(finalPrice);
      }
    });
  }

  available(id, function(finalPrice) {
    razorpay(finalPrice);
  });
</code>```

Body:
Here i want to access the variable "finalPrice " in another function, how can i achive this?

  function available(id){
    $.ajax({
        method:"GET",
    }).done(function(data){

     for(j=0; j<available_location.length; j++) {

            var finalPrice =available_location[j].price_details.final_price;
   };
});

function razorpay() {
    $.ajax({
        url : 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type : 'GET',
        data : {

         },
        success: function(data){
              alert(finalPrice );
           }
    });
}

Body:
If the second call require the first, use of callbacks. If it doesn't call boths, and wait for both answers before you perform the treatment which is to calculate the finalPrice and use it.

It is bad to create a global variable named finalPrice because I'm pretty sure you are running theses both request in parralel, which would result to uncertain behavior if razorpay resolve before available.

First case example

 function available(id, callback) {
  $.ajax({
    method: "GET",
  }).done(function(data) {

    var finalPrice = 0;

    for (j = 0; j < available_location.length; j++) {
      finalPrice = available_location[j].price_details.final_price;
    }

    callback(finalPrice);
  });

  function razorpay(finalPrice) {
    $.ajax({
      url: 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
      type: 'GET',
      data: {

      },
      success: function(data) {
        alert(finalPrice);
      }
    });
  }

  available(id, function(finalPrice) {
    razorpay(finalPrice);
  });


问:
how to use image in ios with Xamarin forms
I use Xamrin forms for an app on IOs and Android.

in my Android project and IOS project, i have a folder "drawable" (with my image) in the "resources" folder.

In my XAML i call like this :
<Image Source="@drawable/clockCircular.png"/>

When attempting to view the image on Android, no problem I see my image.
When attempting to view the image on iOS, the image doesn't appear.

I would like to keep this file structure (resources > drawable).
I have followed many tutorials on the web as images but I'm still blocked here.

答:
Resources > drawable structure for android and you need put image in Resources folder of iOS project and also verify File name is correct and not used any special symbol.

Edit

You need to set image source like below no need to add specify drawable Both platforms iOS(Resources) and Android (Resources > drawable) taken automatically.

```<code><Image Source="clockCircular.png"/>
</code>```

Body:
Resources > drawable structure for android and you need put image in Resources folder of iOS project and also verify File name is correct and not used any special symbol.

Edit

You need to set image source like below no need to add specify drawable Both platforms iOS(Resources) and Android (Resources > drawable) taken automatically.

<Image Source="clockCircular.png"/>


Title: grep range of numbers

Body: grep -c "(1[0-9])\|(20)" filename


问:
I need to use a SELECT - JOIN sentence on a stored procedure PL/SQL
I had a problem with Oracle SQL. I need to use this PL/SQL sentence on a stored procedure:

```<code>select t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN
      from curso t
      inner join contrato c on t.ID_CURSO = c.curso_id_curso
      inner join PAQUETE_ACTIVIDADES p on
            c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
where id_curso=value;
</code>```

I need to show the data of this select query
How can I do that? I'm new at this
Thanks for your help

答:
here an Example . i hope it helps u</p>

```<code>CREATE OR REPLACE PROCEDURE my_first_stored_proc IS
v_sql varchar2(2000);
v_ID_CURSO number;
v_DESCRIPCION varchar2(500);
v_FECHA_INICIO varchar2(50);
v_FECHA_FIN number;
BEGIN
 v_sql := 'select t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN ';
 v_sql := v_sql||' from curso t ';
 v_sql := v_sql||' inner join contrato c on t.ID_CURSO = c.curso_id_curso
   ';
 v_sql := v_sql||' inner join PAQUETE_ACTIVIDADES p on ';
 v_sql := v_sql||' c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES ';
 v_sql := v_sql||' where id_curso=value ';

  --the result is one row selected
 EXECUTE IMMEDIATE v_sql INTO v_ID_CURSO,v_DESCRIPCION,v_FECHA_INICIO,
 v_FECHA_FIN;
 --// Do something else with variable
  v_ID_CURSO,v_DESCRIPCION,v_FECHA_INICIO, v_FECHA_FIN
   -- ...
  --// End -Do something else with variable
  v_ID_CURSO,v_DESCRIPCION,v_FECHA_INICIO, v_FECHA_FIN
 --// Or you can save select result in a table by doing something like this
  v_sql := 'create table my_first_table As ';
  v_sql := v_sql||' select
  t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN ';
   v_sql := v_sql||' from curso t ';
  v_sql := v_sql||' inner join contrato c on t.ID_CURSO = c.curso_id_curso
  ';
  v_sql := v_sql||' inner join PAQUETE_ACTIVIDADES p on ';
  v_sql := v_sql||' c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
  ';
  v_sql := v_sql||' where id_curso=value ';
  EXECUTE IMMEDIATE v_sql;
   --// Do something else with my_first_table
  -- ...
   --// End -Do something else with my_first_table

   --// and so on....

 EXCEPTION
 WHEN OTHERS THEN
   dbms_output.put_line('ERROR: '||sqlerrm);
 END my_first_stored_proc;
</code>```

Body:
I had a problem with Oracle SQL. I need to use this PL/SQL sentence on a stored procedure:

select t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN
      from curso t
      inner join contrato c on t.ID_CURSO = c.curso_id_curso
      inner join PAQUETE_ACTIVIDADES p on
            c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
where id_curso=value;

I need to show the data of this select query
How can I do that? I'm new at this
Thanks for your help

Body:
here an Example . i hope it helps u

CREATE OR REPLACE PROCEDURE my_first_stored_proc IS
v_sql varchar2(2000);
v_ID_CURSO number;
v_DESCRIPCION varchar2(500);
v_FECHA_INICIO varchar2(50);
v_FECHA_FIN number;
BEGIN
 v_sql := 'select t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN ';
 v_sql := v_sql||' from curso t ';
 v_sql := v_sql||' inner join contrato c on t.ID_CURSO = c.curso_id_curso
   ';
 v_sql := v_sql||' inner join PAQUETE_ACTIVIDADES p on ';
 v_sql := v_sql||' c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES ';
 v_sql := v_sql||' where id_curso=value ';

  --the result is one row selected
 EXECUTE IMMEDIATE v_sql INTO v_ID_CURSO,v_DESCRIPCION,v_FECHA_INICIO,
 v_FECHA_FIN;
 --// Do something else with variable
  v_ID_CURSO,v_DESCRIPCION,v_FECHA_INICIO, v_FECHA_FIN
   -- ...
  --// End -Do something else with variable
  v_ID_CURSO,v_DESCRIPCION,v_FECHA_INICIO, v_FECHA_FIN
 --// Or you can save select result in a table by doing something like this
  v_sql := 'create table my_first_table As ';
  v_sql := v_sql||' select
  t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN ';
   v_sql := v_sql||' from curso t ';
  v_sql := v_sql||' inner join contrato c on t.ID_CURSO = c.curso_id_curso
  ';
  v_sql := v_sql||' inner join PAQUETE_ACTIVIDADES p on ';
  v_sql := v_sql||' c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
  ';
  v_sql := v_sql||' where id_curso=value ';
  EXECUTE IMMEDIATE v_sql;
   --// Do something else with my_first_table
  -- ...
   --// End -Do something else with my_first_table

   --// and so on....

 EXCEPTION
 WHEN OTHERS THEN
   dbms_output.put_line('ERROR: '||sqlerrm);
 END my_first_stored_proc;


问:
Polymorphism and the new operator [C++]
I am working on an api, which during runtime decides which higher-level api to use, I have many abstract classes, and derived classes for each high-level api, and a context class which provides me with the correct derived classes for the job, using a function (for example):

```<code>Mesh* genMesh(data d) { if(m_useA_API) return new A_mesh(d); else return B_mesh(d); }
</code>```

something like that, now the question is, is it possible to make the code less ugly ? and instead of using methods inside the context class, can I override new operator in the base class to return the appropriate derived class instance?

if not, what are some possible solutions?

tl;dr this is what i'd like to do

```<code>Mesh* m = new Mesh(data); // and the base class decides which derived class to use instead of the Context class.
</code>```

Thanks.

答:
You can not use new as factory, but you could use Implementation Pattern for it:

```<code>class Mesh {
  std::unique_ptr<MeshImpl> _impl;
public:
  Mesh(int data)
  : _impl(
    m_use_A_API
      ? new A_mesh(data)
      : new B_mesh(data)
  ) {
  }
  MeshImpl& get_value() { return *_impl; }
};
</code>```

Classes A_mesh, B_mesh are different classes that inherited from class MeshImpl and will be initialized by correct way;

Or you can improve your factory code by next way:

move your method genMesh(int) inside class Mesh

make constructors of Mesh private, for be sure that nobody call it directly.

Title: Polymorphism and the new operator [C++]

Body:
I am working on an api, which during runtime decides which higher-level api to use, I have many abstract classes, and derived classes for each high-level api, and a context class which provides me with the correct derived classes for the job, using a function (for example):

Mesh* genMesh(data d) { if(m_useA_API) return new A_mesh(d); else return B_mesh(d); }

something like that, now the question is, is it possible to make the code less ugly ? and instead of using methods inside the context class, can I override new operator in the base class to return the appropriate derived class instance?

if not, what are some possible solutions?

tl;dr this is what i'd like to do

Mesh* m = new Mesh(data); // and the base class decides which derived class to use instead of the Context class.

Thanks.

Body:
You can not use new as factory, but you could use Implementation Pattern for it:

class Mesh {
  std::unique_ptr<MeshImpl> _impl;
public:
  Mesh(int data)
  : _impl(
    m_use_A_API
      ? new A_mesh(data)
      : new B_mesh(data)
  ) {
  }
  MeshImpl& get_value() { return *_impl; }
};

Classes A_mesh, B_mesh are different classes that inherited from class MeshImpl and will be initialized by correct way;

Or you can improve your factory code by next way:

move your method genMesh(int) inside class Mesh

make constructors of Mesh private, for be sure that nobody call it directly.


问:
VBA deleting a duplicate copy of chart object fails in Excel 2013
I have a VBA code that is intended to copy the contents of a range into a chart, to be able to export it to a PNG file (+some post-processing using an external command). Here is the relevant part:

```<code>Sub GenererImage()  ' Entry point
    getparams    ' Collect parameters and define global variables
    MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen,Format:=xlPicture
    Application.DisplayAlerts = False

    With ObjetGraphique.Duplicate
        .Chart.Paste
        .Chart.Export Filename:=CheminImage, Filtername:="PNG"
        .Select
        .Delete
    End With
    Application.DisplayAlerts = True
End Sub
</code>```

The getparams procedure called in there is just collecting some parameters from another worksheet to define:

"MiseEnPage": reference to the worksheet object where the range I want to copy exists,

"ZoneImage" is set to the "B4:F11" string (refers to the range address),

"ObjetGraphique" is a reference to a ChartObject inside the "MiseEnPage" sheet. This ChartObject is an empty container (I am mainly using it to easily set the width and height).

"CheminImage" is a string containing the path to the picture filename on disk.

This code used to work perfectly in Excel 2010. Now my company has deployed Excel 2013 and my code now fails on the .Delete line, leaving the copy of the ChartObject (with the range picture pasted inside it) on the sheet and stopping macro execution.

I have tried activating the worksheet first, selecting the duplicate prior to deleting it and other things, to no avail. When tracing the execution in the debugger it chokes on the delete line with error 1004.

I am frustratingly stuck. Any clue?

答:
If this works

```<code> With ObjetGraphique.Duplicate
    .Chart.Paste
    .Chart.Export Filename:=CheminImage, Filtername:="PNG"
    .Select
End With
Selection.Delete
</code>```

we have to assume that either the With is holding a reference and preventing the delete, or that the delete routine called by the selection object is not the same delete that's called by ObjetGraphique.Duplicate.delete, or that it's a subtle timing bug and that the extra time it takes to retrieve the selected object is enough to fix it.

Body:
I have a VBA code that is intended to copy the contents of a range into a chart, to be able to export it to a PNG file (+some post-processing using an external command). Here is the relevant part:

Sub GenererImage()  ' Entry point
    getparams    ' Collect parameters and define global variables
    MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen,Format:=xlPicture
    Application.DisplayAlerts = False

    With ObjetGraphique.Duplicate
        .Chart.Paste
        .Chart.Export Filename:=CheminImage, Filtername:="PNG"
        .Select
        .Delete
    End With
    Application.DisplayAlerts = True
End Sub

The getparams procedure called in there is just collecting some parameters from another worksheet to define:

"MiseEnPage": reference to the worksheet object where the range I want to copy exists,

"ZoneImage" is set to the "B4:F11" string (refers to the range address),

"ObjetGraphique" is a reference to a ChartObject inside the "MiseEnPage" sheet. This ChartObject is an empty container (I am mainly using it to easily set the width and height).

"CheminImage" is a string containing the path to the picture filename on disk.

This code used to work perfectly in Excel 2010. Now my company has deployed Excel 2013 and my code now fails on the .Delete line, leaving the copy of the ChartObject (with the range picture pasted inside it) on the sheet and stopping macro execution.

I have tried activating the worksheet first, selecting the duplicate prior to deleting it and other things, to no avail. When tracing the execution in the debugger it chokes on the delete line with error 1004.

I am frustratingly stuck. Any clue?

Body:
If this works

 With ObjetGraphique.Duplicate
    .Chart.Paste
    .Chart.Export Filename:=CheminImage, Filtername:="PNG"
    .Select
End With
Selection.Delete

we have to assume that either the With is holding a reference and preventing the delete, or that the delete routine called by the selection object is not the same delete that's called by ObjetGraphique.Duplicate.delete, or that it's a subtle timing bug and that the extra time it takes to retrieve the selected object is enough to fix it.


问:
How to get value after 2nd hash in input parameter
My below t-sql only works when there is one hash symbol in the input parameter.

How can I change it to so I can get the value after the 2nd hash symbol?

I think I need to use a combination of REVERSE and RIGHT but I can't figure it out.

```<code>DECLARE @SEAL_SECURITY3 As Varchar(50); SET @SEAL_SECURITY3 = NULL;
DECLARE @SEAL_SECURITY As Varchar(50); SET @SEAL_SECURITY = 'MS-7#MS-8#MS-9'

SET @SEAL_SECURITY3 = CASE WHEN CHARINDEX('#', @SEAL_SECURITY) = 0 THEN NULL
ELSE SUBSTRING(@SEAL_SECURITY, CHARINDEX('#', @SEAL_SECURITY) + 1, LEN(@SEAL_SECURITY) - CHARINDEX('#', @SEAL_SECURITY) + 1)
END

SELECT @SEAL_SECURITY3
</code>```

The result of this is MS-8#MS-9

Desired result is  MS-9

UPDATE

is it possible to get the Desired result by changing the SET ELSE block as opposed to the SELECT statement?

答:
If your are using SQL SERVER and In your string, count of # is always less and equals to 4 then below script will help to get desire result

```<code>SELECT PARSENAME(REPLACE(@SEAL_SECURITY,'#','.'),1)
</code>```

Body:
My below t-sql only works when there is one hash symbol in the input parameter.

How can I change it to so I can get the value after the 2nd hash symbol?

I think I need to use a combination of REVERSE and RIGHT but I can't figure it out.

DECLARE @SEAL_SECURITY3 As Varchar(50); SET @SEAL_SECURITY3 = NULL;
DECLARE @SEAL_SECURITY As Varchar(50); SET @SEAL_SECURITY = 'MS-7#MS-8#MS-9'

SET @SEAL_SECURITY3 = CASE WHEN CHARINDEX('#', @SEAL_SECURITY) = 0 THEN NULL
ELSE SUBSTRING(@SEAL_SECURITY, CHARINDEX('#', @SEAL_SECURITY) + 1, LEN(@SEAL_SECURITY) - CHARINDEX('#', @SEAL_SECURITY) + 1)
END

SELECT @SEAL_SECURITY3

The result of this is MS-8#MS-9

Desired result is  MS-9

UPDATE

is it possible to get the Desired result by changing the SET ELSE block as opposed to the SELECT statement?

Body:
If your are using SQL SERVER and In your string, count of # is always less and equals to 4 then below script will help to get desire result

SELECT PARSENAME(REPLACE(@SEAL_SECURITY,'#','.'),1)


问:
How to target the parent class from nested classes in SASS
Is there a way to achieve something like below in SASS without indicating .group-left twice?

```<code>.wrapper .group-left {
  background-color: blue;
}
.wrapper-child:nth-child(2n+2) .group-left {
  background: red;
}
</code>```

I was trying to put ampersand after .group-left, but doesn't work. So, I have to re-select .group-left. Below is my current code.

```<code>.wrapper {
  &:nth-child(2n+2) .group-left {
    background-color: red;
  }
  .group-left {
    background-color: blue;
  }
}
</code>```

Please advise. Thank you.

答:
You could use parent selector and invert your nesting in sass</p>

```<code>.group-left {
  .wrapper & {
    background-color: blue;
  }
  .wrapper-child:nth-child(2n+2) & {
    background: red;
  }
}
</code>```

Body:
Is there a way to achieve something like below in SASS without indicating .group-left twice?

.wrapper .group-left {
  background-color: blue;
}
.wrapper-child:nth-child(2n+2) .group-left {
  background: red;
}

I was trying to put ampersand after .group-left, but doesn't work. So, I have to re-select .group-left. Below is my current code.

.wrapper {
  &:nth-child(2n+2) .group-left {
    background-color: red;
  }
  .group-left {
    background-color: blue;
  }
}

Please advise. Thank you.

Body:
You could use parent selector and invert your nesting in sass

.group-left {
  .wrapper & {
    background-color: blue;
  }
  .wrapper-child:nth-child(2n+2) & {
    background: red;
  }
}


问:
Creating a number pyramid by iteration
I am trying to make a number pyramid, but have some problem to find the right conditions.

```<code>int n = scanner.nextInt();
int a;
for(int q = 1; q <= n; q++)
{
    for(int space = 0; space < n-q; space++){
        System.out.print(" ");
    }
    a = 1;
    for(int p = 1; p <= q; p++){
        if((p <= q / 2 && p != 1)){
            a++;
        }
        else if((p != 1) && (p > q / 2 + 1)){
            a--;
        }
        System.out.print(a+" ");
    }
    System.out.println();
}
</code>```

It creates a proper pyramid, but the uneven rows stop to increase to early.

Supposed outcome:

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

The outcome of my code is

```<code>         1
        1 1
       1 1 0
      1 2 2 1
     1 2 2 1 0
    1 2 3 3 2 1
   1 2 3 3 2 1 0
  1 2 3 4 4 3 2 1
 1 2 3 4 4 3 2 1 0
1 2 3 4 5 5 4 3 2 1
</code>```

答:
Try this, it works:</p>

```<code>int number = 5;
for (int i = 0; i < number; i++) {
    int x = 1;
    for (int j = 0; j < (number + i); j++) {
        if (j < number - i - 1) {
            System.out.print(" ");
        } else {
            System.out.print(x);
            if (j < (number - 1)) {
                x++;
            } else {
                x--;
            }
        }
    }
    System.out.println(" ");
}
</code>```

Title: Creating a number pyramid by iteration

Body:
I am trying to make a number pyramid, but have some problem to find the right conditions.

int n = scanner.nextInt();
int a;
for(int q = 1; q <= n; q++)
{
    for(int space = 0; space < n-q; space++){
        System.out.print(" ");
    }
    a = 1;
    for(int p = 1; p <= q; p++){
        if((p <= q / 2 && p != 1)){
            a++;
        }
        else if((p != 1) && (p > q / 2 + 1)){
            a--;
        }
        System.out.print(a+" ");
    }
    System.out.println();
}

It creates a proper pyramid, but the uneven rows stop to increase to early.

Supposed outcome:

    1
   1 1
  1 2 1
 1 2 2 1
1 2 3 2 1

The outcome of my code is

         1
        1 1
       1 1 0
      1 2 2 1
     1 2 2 1 0
    1 2 3 3 2 1
   1 2 3 3 2 1 0
  1 2 3 4 4 3 2 1
 1 2 3 4 4 3 2 1 0
1 2 3 4 5 5 4 3 2 1

Body:
Try this, it works:

int number = 5;
for (int i = 0; i < number; i++) {
    int x = 1;
    for (int j = 0; j < (number + i); j++) {
        if (j < number - i - 1) {
            System.out.print(" ");
        } else {
            System.out.print(x);
            if (j < (number - 1)) {
                x++;
            } else {
                x--;
            }
        }
    }
    System.out.println(" ");
}


问:
Prevent slicing in "throw e;" when passing an unthrown exception as a parameter
If I want to provide a substituteable ErrorHandler class which can be used to provide different styles of handling (e.g. rethrow, log and rethrow, swallow, call some function, etc), then I can do something like the following:

ErrorHandler.h (this is long and should probably be read only after the problem, below)

```<code>template<typename Target, typename F, typename... Args>
using IsReturnType = std::is_same<std::result_of_t<F(Args...)>, Target>;

template<typename ReturnType, typename Function, typename... Args>
using EnableIfReturnType = typename std::enable_if<IsReturnType<ReturnType, Function, Args...>::value, ReturnType>::type;

class ErrorHandler
{
public:
    virtual void handleException(std::exception& e);
    void Throw(std::exception& e);

    // Templated Try functions
};

// Return type is void
template<typename F, typename... Ts>
typename EnableIfReturnType<void, F, Ts...>
ErrorHandler::Try(F&& function, Ts&&... args) {
    try {
        std::forward<F>(function)(std::forward<Ts>(args)...);
    }
    catch (std::exception& e) {
        handleException(e);
    }
}

// Return type is short
template<typename F, typename... Ts>
typename EnableIfReturnType<short, F, Ts...>
ErrorHandler::Try(F&& function, Ts&&... args) {
    short result = 0;
    try {
        result = std::forward<F>(function)(std::forward<Ts>(args)...);
        if (result != 0) {
            std::string msg = "getmessagehereErr";
            throw std::runtime_error(msg);
        }
    }
    catch (std::exception& e) {
        handleException(e);
    }
    return result;
}

// Return type is other
template<typename F, typename... Ts>
typename std::enable_if<!((IsReturnType<short, F, Ts...>::value) || (IsReturnType<void, F, Ts...>::value)), std::result_of_t<F(Ts...)>>::type
ErrorHandler::Try(F&& function, Ts&&... args) {
    using R = std::result_of_t<F(Ts...)>;
    R result;
    try {
        result = std::forward<F>(function)(std::forward<Ts>(args)...);
    }
    catch (std::exception& e) {
        handleException(e);
    }
    return result;
}
</code>```

SomeImplementation.cpp

```<code>extern ErrorHandler *eh;
short result = eh->Try(Function, Arg1, Arg2);
// where Function(Arg1, Arg2) returns a short, although
// a different return type could be provided for a different function via the templates
</code>```

This allows me to wrap function calls with Try and have the ErrorHandler pointed to be *eh (which could be a child of ErrorHandler, with different handleException(std::exception &e)).

Real question starts here

However, if I want to throw an error from a function that I know doesn't result in an exception, I can't do this:

```<code>int result = nonThrowingFunction();
if (result) { throw std::exception("Message"); }
</code>```

because that won't be passed to the ErrorHandler *eh.

I can't directly call eh->handleException(..), because the default implementation is {throw;}, and this won't work properly if the exception it is passed hasn't already been thrown.

I can call Throw(e) with

```<code>Throw(std::exception &e) {
    try {
        throw e;
    }
    catch(std::exception &ex) {
        handleException(ex);
    }
}
</code>```

but this slices the exception, meaning all exceptions thrown in this way become whatever type I specify for Throw. I can't template Throw, because I can't get a pointer to a template function (in the general case).

Is there some good solution here, or should I write out an overloaded Throw for each exception type? (And if that's the sensible solution, is there some preprocessor magic that can write the same function for a list of different arguments?)

Edited to try and clarify the point of the question, and guide readers away from the somewhat bulky template<...> Try(...) function(s).

答:
Using a template to handle any exception type should work:</p>

```<code>template<typename ExceptionType>
void Throw(ExceptionType &e) {
    try {
        throw e;
    }
    catch(ExceptionType &ex) {
        handleException(ex);
    }
}
</code>```

Body:
If I want to provide a substituteable ErrorHandler class which can be used to provide different styles of handling (e.g. rethrow, log and rethrow, swallow, call some function, etc), then I can do something like the following:

ErrorHandler.h (this is long and should probably be read only after the problem, below)

template<typename Target, typename F, typename... Args>
using IsReturnType = std::is_same<std::result_of_t<F(Args...)>, Target>;

template<typename ReturnType, typename Function, typename... Args>
using EnableIfReturnType = typename std::enable_if<IsReturnType<ReturnType, Function, Args...>::value, ReturnType>::type;

class ErrorHandler
{
public:
    virtual void handleException(std::exception& e);
    void Throw(std::exception& e);

    // Templated Try functions
};

// Return type is void
template<typename F, typename... Ts>
typename EnableIfReturnType<void, F, Ts...>
ErrorHandler::Try(F&& function, Ts&&... args) {
    try {
        std::forward<F>(function)(std::forward<Ts>(args)...);
    }
    catch (std::exception& e) {
        handleException(e);
    }
}

// Return type is short
template<typename F, typename... Ts>
typename EnableIfReturnType<short, F, Ts...>
ErrorHandler::Try(F&& function, Ts&&... args) {
    short result = 0;
    try {
        result = std::forward<F>(function)(std::forward<Ts>(args)...);
        if (result != 0) {
            std::string msg = "getmessagehereErr";
            throw std::runtime_error(msg);
        }
    }
    catch (std::exception& e) {
        handleException(e);
    }
    return result;
}

// Return type is other
template<typename F, typename... Ts>
typename std::enable_if<!((IsReturnType<short, F, Ts...>::value) || (IsReturnType<void, F, Ts...>::value)), std::result_of_t<F(Ts...)>>::type
ErrorHandler::Try(F&& function, Ts&&... args) {
    using R = std::result_of_t<F(Ts...)>;
    R result;
    try {
        result = std::forward<F>(function)(std::forward<Ts>(args)...);
    }
    catch (std::exception& e) {
        handleException(e);
    }
    return result;
}

SomeImplementation.cpp

extern ErrorHandler *eh;
short result = eh->Try(Function, Arg1, Arg2);
// where Function(Arg1, Arg2) returns a short, although
// a different return type could be provided for a different function via the templates

This allows me to wrap function calls with Try and have the ErrorHandler pointed to be *eh (which could be a child of ErrorHandler, with different handleException(std::exception &e)).

Real question starts here

However, if I want to throw an error from a function that I know doesn't result in an exception, I can't do this:

int result = nonThrowingFunction();
if (result) { throw std::exception("Message"); }

because that won't be passed to the ErrorHandler *eh.

I can't directly call eh->handleException(..), because the default implementation is {throw;}, and this won't work properly if the exception it is passed hasn't already been thrown.

I can call Throw(e) with

Throw(std::exception &e) {
    try {
        throw e;
    }
    catch(std::exception &ex) {
        handleException(ex);
    }
}

but this slices the exception, meaning all exceptions thrown in this way become whatever type I specify for Throw. I can't template Throw, because I can't get a pointer to a template function (in the general case).

Is there some good solution here, or should I write out an overloaded Throw for each exception type? (And if that's the sensible solution, is there some preprocessor magic that can write the same function for a list of different arguments?)

Edited to try and clarify the point of the question, and guide readers away from the somewhat bulky template<...> Try(...) function(s).

Body:
Using a template to handle any exception type should work:

template<typename ExceptionType>
void Throw(ExceptionType &e) {
    try {
        throw e;
    }
    catch(ExceptionType &ex) {
        handleException(ex);
    }
}


问:
In Swift, why is CodingKey the protocol I see being used with enums for use of the Codable protocol on a struct?
In Swift, why is CodingKey the protocol I see being used with enums for use of the Codable protocol on a struct?

I haven't tested this in too many ways, but I consistently am getting this error trying to replicate all the examples I am finding. I get perfect behavior out of just using the Codable protocol on an enum.

```<code>// This throws Error
struct Foo: Codable { //! Type 'Foo' does not conform to protocol 'Codable'

    var id: String
    var name: String
    var type: MyType
    var order: Int

    enum MyType: String, CodingKey {
        case this
        case that
        case and
        case theOtherThing
    }

}

// This doesn't
struct Foo: Codable {

    var id: String
    var name: String
    var type: MyType
    var order: Int

    enum MyType: String, Codable {
        case this
        case that
        case and
        case theOtherThing
    }
}
</code>```

答:
Why to use Coding key?

If the keys used in your serialized data format don't match the
  property names from your data type, provide alternative keys by
  specifying String as the raw-value type for the CodingKeys
  enumeration.

Example:-

Json -

```<code>    let jsonExample = """
 {
        "id":1,
        "name_Of_person":"jack",
        "emailId":"Demo@apple.com"
}
""".data(using: .utf8)!
</code>```

Create struct which conforms to Codable protocol

```<code>struct UserData: Codable {
    var id: Int
    var name: String
    var email: String
    //Set JSON key values for fields in our custom type
    private enum CodingKeys: String, CodingKey {
        case id //Leave it blank because id matches with json Id
        case name = "name_Of_person"
        case email = "emailId"
    }
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = try values.decode(Int.self, forKey: .id)
        name = try values.decode(String.self, forKey: .name)
        email = try values.decode(String.self, forKey: .email)
    }
}
</code>```

Usage-

```<code> //Decode struct using JSONDecoder

    let jsonDecoder = JSONDecoder()
    do {
        let modelResult = try jsonDecoder.decode(UserData.self,from: jsonExample)
        print("id is \(modelResult.id) - Name is \(modelResult.name) - email is \((modelResult.email))")
    } catch {
        print(error)
    }
</code>```

Body:
In Swift, why is CodingKey the protocol I see being used with enums for use of the Codable protocol on a struct?

I haven't tested this in too many ways, but I consistently am getting this error trying to replicate all the examples I am finding. I get perfect behavior out of just using the Codable protocol on an enum.

// This throws Error
struct Foo: Codable { //! Type 'Foo' does not conform to protocol 'Codable'

    var id: String
    var name: String
    var type: MyType
    var order: Int

    enum MyType: String, CodingKey {
        case this
        case that
        case and
        case theOtherThing
    }

}

// This doesn't
struct Foo: Codable {

    var id: String
    var name: String
    var type: MyType
    var order: Int

    enum MyType: String, Codable {
        case this
        case that
        case and
        case theOtherThing
    }
}

Body:
Why to use Coding key?

If the keys used in your serialized data format don't match the
  property names from your data type, provide alternative keys by
  specifying String as the raw-value type for the CodingKeys
  enumeration.

Example:-

Json -

    let jsonExample = """
 {
        "id":1,
        "name_Of_person":"jack",
        "emailId":"Demo@apple.com"
}
""".data(using: .utf8)!

Create struct which conforms to Codable protocol

struct UserData: Codable {
    var id: Int
    var name: String
    var email: String
    //Set JSON key values for fields in our custom type
    private enum CodingKeys: String, CodingKey {
        case id //Leave it blank because id matches with json Id
        case name = "name_Of_person"
        case email = "emailId"
    }
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = try values.decode(Int.self, forKey: .id)
        name = try values.decode(String.self, forKey: .name)
        email = try values.decode(String.self, forKey: .email)
    }
}

Usage-

 //Decode struct using JSONDecoder

    let jsonDecoder = JSONDecoder()
    do {
        let modelResult = try jsonDecoder.decode(UserData.self,from: jsonExample)
        print("id is \(modelResult.id) - Name is \(modelResult.name) - email is \((modelResult.email))")
    } catch {
        print(error)
    }


问:
Nginx real client IP to TCP stream backend
I'm trying to use Nginx as proxy for my TCP daemon, to make Nginx be SSL/TLS frontend, as well as load control.

My backend app needs real client IP, and this is a problem.

```<code>stream {
    server {
        listen     3333;
        proxy_pass 127.0.0.1:2222;
    }
}
</code>```

I found one solution in docs:

```<code>proxy_bind $remote_addr transparent;
</code>```

But it's too complicated:

"In order for this parameter to work, it is necessary to run nginx
  worker processes with the superuser privileges and configure kernel
  routing table to intercept network traffic from the proxied server."

Is there any other way to pass $remote_addr to backend?

I tried modify client message body using sub_filter, send http headers, etc. But all of this can work only with http context, not with stream unfortunately.

答:
To my knowledge, there are only two solutions: proxy_bind and proxy_protocol.

proxy_bind

As you quoted from the documentation, the work processes will need superuser privileges. Obviously. this not a best practice. Additionally, it might cause connection issues back to the remote clients.

Assuming the Nginx is running as the nginx user, run this command to give it permissions.

```<code>usermod -aG sudo nginx
</code>```

proxy_protocol

This solution requires the upsteam destination (e.g. the backend app) accepts PROXY protocol.

```<code>stream {
    server {
        listen         3333;
        proxy_pass     127.0.0.1:2222;
        proxy_protocol on;
    }
}
</code>```

The above solutions assume the Nginx server is the entry point to the network. If there is a edge device (e.g. load balancer), it is very likely it is changing the source IP. In this case, you will need to enable proxy protocol on the edge device and enable proxy_protocol listener in the server block.  I haven't tested it, but something like this should work.

```<code>stream {
    server {
        listen            3333 proxy_protocol;
        proxy_pass        127.0.0.1:2222;
        proxy_protocol    on;
        set_real_ip_from  $proxy_protocol_addr;
    }
}
</code>```

Body:
I'm trying to use Nginx as proxy for my TCP daemon, to make Nginx be SSL/TLS frontend, as well as load control.

My backend app needs real client IP, and this is a problem.

stream {
    server {
        listen     3333;
        proxy_pass 127.0.0.1:2222;
    }
}

I found one solution in docs:

proxy_bind $remote_addr transparent;

But it's too complicated:

"In order for this parameter to work, it is necessary to run nginx
  worker processes with the superuser privileges and configure kernel
  routing table to intercept network traffic from the proxied server."

Is there any other way to pass $remote_addr to backend?

I tried modify client message body using sub_filter, send http headers, etc. But all of this can work only with http context, not with stream unfortunately.

Body:
To my knowledge, there are only two solutions: proxy_bind and proxy_protocol.

proxy_bind

As you quoted from the documentation, the work processes will need superuser privileges. Obviously. this not a best practice. Additionally, it might cause connection issues back to the remote clients.

Assuming the Nginx is running as the nginx user, run this command to give it permissions.

usermod -aG sudo nginx

proxy_protocol

This solution requires the upsteam destination (e.g. the backend app) accepts PROXY protocol.

stream {
    server {
        listen         3333;
        proxy_pass     127.0.0.1:2222;
        proxy_protocol on;
    }
}

The above solutions assume the Nginx server is the entry point to the network. If there is a edge device (e.g. load balancer), it is very likely it is changing the source IP. In this case, you will need to enable proxy protocol on the edge device and enable proxy_protocol listener in the server block.  I haven't tested it, but something like this should work.

stream {
    server {
        listen            3333 proxy_protocol;
        proxy_pass        127.0.0.1:2222;
        proxy_protocol    on;
        set_real_ip_from  $proxy_protocol_addr;
    }
}


问:
Factory Model in C#
I have a bunch of MDI child nodes that are all created in the same way and to reduce redundant code I'd like to be able to call a method, pass it a string (name of child node), have it create the node and add it to the parent.

I can do all the stuff except create the class from a string of a class name, how can I do this?

OwnerDisplayName: Malfist

Title: Factory Model in C#

LastEditorDisplayName: chris

Body: Activator.CreateInstance(Type.GetType(typeName))

OwnerDisplayName: Bryan Watts


问:
Ruby Mechanize crashes during authentication redirection; sslv3 alert illegal parameter
My script attempts to log into a website via a form.  After being redirected several times during authentication, it crashes with an sslv3 alert illegal parameter.  I was wondering if something weird was going on with the cookies so I checked the HTML headers with the DEBUG output.  The two outputs are pasted below.

Some other weird things: the click_button and submit methods appear to do different things; namely, click_button gets the execution of the redirections to last a little longer, but it also crashes with the above error.  submit doesn't crash the program, but the login doesn't appear to work either.  I tried running it on an older version of Ruby and the error turns into a connection_refused error while using click_button and the behavior is identical while using submit.

Here are outputs I mentioned in the first paragraph in .txt, in case you find the text below difficult to read.

DEBUG OUTPUT when I run the script:

```
`I, [2010-11-15T17:52:20.462201 #22853]  INFO -- : follow redirect to: htps://xx2web1.apps.XXXXXXXXX.com/BANPROD1/xxauthent.ss_md5_login?timestamp_in=1289814682&uin_in=XXXXXXXXX&digest_in=be34b4b470a0da1831c7c432e353c320
/usr/lib/ruby/1.9.1/net/http.rb:677:in 'connect': SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: sslv3 alert illegal parameter (OpenSSL::SSL::SSLError)
        from /usr/lib/ruby/1.9.1/net/http.rb:677:in 'connect'
        from /usr/lib/ruby/1.9.1/net/http.rb:637:in 'do_start'
        from /usr/lib/ruby/1.9.1/net/http.rb:632:in 'start'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:527:in 'fetch_page'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:611:in 'fetch_page'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:611:in 'fetch_page'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:464:in 'post_form'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:370:in 'submit'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize/form.rb:141:in 'submit'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize/form.rb:147:in 'click_button'
        from ./courseChecker.rb:33:in 'block in '
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:262:in 'get'
        from ./courseChecker.rb:26:in ''`
```

HTML HEADERS TRACE from successful Firefox login:

```
`htps://xx2web1.apps.XXXXXXXXX.com/BANPROD1/xxauthent.ss_md5_login?timestamp_in=1289814134&uin_in=XXXXXXXXX&digest_in=d75483c390a2ab4ec0b939eaef7ecb1f`

`GET /BANPROD1/xxauthent.ss_md5_login?timestamp_in=1289814134&uin_in=XXXXXXXXX&digest_in=d75483c390a2ab4ec0b939eaef7ecb1f HTTP/1.1
Host: xx2web1.apps.XXXXXXXXX.com
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Firefox/3.6.12
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: htps://eas.admin.XXXXXXXXX.com/eas/servlet/EasLogin?redirect=htps://webprod.admin.XXXXXXXXX.com/ssa/servlet/SelfServiceLogin?appName=com.XXXXXXXXX.aits.SelfServiceLogin&dad=BANPROD1
Cookie: RedirectString=https://webprod.admin.XXXXXXXXX.com/ssa/servlet/SelfServiceLogin?appName=com.XXXXXXXXX.aits.SelfServiceLogin&dad=BANPROD1; EnterpriseSessionId=8cc56f29-28de-4a01-96b8-6f58c30d6b6e-155.69.191.54; TESTID=test`

`HTTP/1.1 200 OK
Date: Mon, 15 Nov 2010 09:42:03 GMT
Server: Oracle-Application-Server-10g/10.1.2.3.0 Oracle-HTTP-Server
Content-Length: 228
Set-Cookie: SESSID=RTlCTzQ4MTc5NDAzOQ==
Connection: close
Content-Type: text/html; charset=UTF-8`
```

答:
Have you tried getting Mechanize to go via a proxy, for example Charles, and look into what its sending back and forth compared to Firefox?

It can be configured to look into https interactions.

Have fun, Chris

Body:
My script attempts to log into a website via a form.  After being redirected several times during authentication, it crashes with an sslv3 alert illegal parameter.  I was wondering if something weird was going on with the cookies so I checked the HTML headers with the DEBUG output.  The two outputs are pasted below.

Some other weird things: the click_button and submit methods appear to do different things; namely, click_button gets the execution of the redirections to last a little longer, but it also crashes with the above error.  submit doesn't crash the program, but the login doesn't appear to work either.  I tried running it on an older version of Ruby and the error turns into a connection_refused error while using click_button and the behavior is identical while using submit.

Here are outputs I mentioned in the first paragraph in .txt, in case you find the text below difficult to read.

DEBUG OUTPUT when I run the script:

`I, [2010-11-15T17:52:20.462201 #22853]  INFO -- : follow redirect to: htps://xx2web1.apps.XXXXXXXXX.com/BANPROD1/xxauthent.ss_md5_login?timestamp_in=1289814682&uin_in=XXXXXXXXX&digest_in=be34b4b470a0da1831c7c432e353c320
/usr/lib/ruby/1.9.1/net/http.rb:677:in 'connect': SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: sslv3 alert illegal parameter (OpenSSL::SSL::SSLError)
        from /usr/lib/ruby/1.9.1/net/http.rb:677:in 'connect'
        from /usr/lib/ruby/1.9.1/net/http.rb:637:in 'do_start'
        from /usr/lib/ruby/1.9.1/net/http.rb:632:in 'start'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:527:in 'fetch_page'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:611:in 'fetch_page'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:611:in 'fetch_page'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:464:in 'post_form'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:370:in 'submit'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize/form.rb:141:in 'submit'
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize/form.rb:147:in 'click_button'
        from ./courseChecker.rb:33:in 'block in '
        from /usr/lib/ruby/gems/1.9.1/gems/mechanize-1.0.0/lib/mechanize.rb:262:in 'get'
        from ./courseChecker.rb:26:in ''`

HTML HEADERS TRACE from successful Firefox login:

`htps://xx2web1.apps.XXXXXXXXX.com/BANPROD1/xxauthent.ss_md5_login?timestamp_in=1289814134&uin_in=XXXXXXXXX&digest_in=d75483c390a2ab4ec0b939eaef7ecb1f`

`GET /BANPROD1/xxauthent.ss_md5_login?timestamp_in=1289814134&uin_in=XXXXXXXXX&digest_in=d75483c390a2ab4ec0b939eaef7ecb1f HTTP/1.1
Host: xx2web1.apps.XXXXXXXXX.com
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Firefox/3.6.12
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: htps://eas.admin.XXXXXXXXX.com/eas/servlet/EasLogin?redirect=htps://webprod.admin.XXXXXXXXX.com/ssa/servlet/SelfServiceLogin?appName=com.XXXXXXXXX.aits.SelfServiceLogin&dad=BANPROD1
Cookie: RedirectString=https://webprod.admin.XXXXXXXXX.com/ssa/servlet/SelfServiceLogin?appName=com.XXXXXXXXX.aits.SelfServiceLogin&dad=BANPROD1; EnterpriseSessionId=8cc56f29-28de-4a01-96b8-6f58c30d6b6e-155.69.191.54; TESTID=test`

`HTTP/1.1 200 OK
Date: Mon, 15 Nov 2010 09:42:03 GMT
Server: Oracle-Application-Server-10g/10.1.2.3.0 Oracle-HTTP-Server
Content-Length: 228
Set-Cookie: SESSID=RTlCTzQ4MTc5NDAzOQ==
Connection: close
Content-Type: text/html; charset=UTF-8`


答:
If you are using Oracle 12c, you could use DBMS_SQL.RETURN_RESULT.

```<code>CREATE OR REPLACE PROCEDURE pr_show_output
AS
   l_cursor   SYS_REFCURSOR;
BEGIN
   OPEN l_cursor FOR
      SELECT t.ID_CURSO,
             p.DESCRIPCION,
             p.FECHA_INICIO,
             p.FECHA_FIN
        FROM curso t
             INNER JOIN contrato c ON t.ID_CURSO = c.curso_id_curso
             INNER JOIN PAQUETE_ACTIVIDADES p
                ON c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
       WHERE id_curso = VALUE;

   DBMS_SQL.return_result (l_cursor);
END;
/
</code>```

Title: I need to use a SELECT - JOIN sentence on a stored procedure PL/SQL

Body:
I had a problem with Oracle SQL. I need to use this PL/SQL sentence on a stored procedure:

select t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN
      from curso t
      inner join contrato c on t.ID_CURSO = c.curso_id_curso
      inner join PAQUETE_ACTIVIDADES p on
            c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
where id_curso=value;

I need to show the data of this select query
How can I do that? I'm new at this
Thanks for your help

Body:
If you are using Oracle 12c, you could use DBMS_SQL.RETURN_RESULT.

CREATE OR REPLACE PROCEDURE pr_show_output
AS
   l_cursor   SYS_REFCURSOR;
BEGIN
   OPEN l_cursor FOR
      SELECT t.ID_CURSO,
             p.DESCRIPCION,
             p.FECHA_INICIO,
             p.FECHA_FIN
        FROM curso t
             INNER JOIN contrato c ON t.ID_CURSO = c.curso_id_curso
             INNER JOIN PAQUETE_ACTIVIDADES p
                ON c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
       WHERE id_curso = VALUE;

   DBMS_SQL.return_result (l_cursor);
END;
/


答:
Linking to explicitly instantiated templates works via pointer.

As a result, the following is valid (or at least, compileable and unit-test-passing) code.

ErrorHandler.h

```<code>class ErrorHandler {
...
template<typename E>
void Throw(E& e);
...
}
</code>```

ErrorHandler.cpp

```<code>template<typename E>
void ErrorHandler::Throw(E& e)
{
    try {
        throw e;
    }
    catch (E&e) {
        handleException(e);
    }
}

template void ErrorHandler::Throw<std::exception>(std::exception&);
template void ErrorHandler::Throw<std::runtime_error>(std::runtime_error&);
template void ErrorHandler::Throw<std::invalid_argument>(std::invalid_argument&);
</code>```

and reduces the burden to add a new exception that won't be sliced down to adding an additional line to the cpp file, which isn't included anywhere else, saving compilation times.

This also won't compile if the result would slice the exception, since then there will be a linking error.

Title: Prevent slicing in "throw e;" when passing an unthrown exception as a parameter

Body:
Linking to explicitly instantiated templates works via pointer.

As a result, the following is valid (or at least, compileable and unit-test-passing) code.

ErrorHandler.h

class ErrorHandler {
...
template<typename E>
void Throw(E& e);
...
}

ErrorHandler.cpp

template<typename E>
void ErrorHandler::Throw(E& e)
{
    try {
        throw e;
    }
    catch (E&e) {
        handleException(e);
    }
}

template void ErrorHandler::Throw<std::exception>(std::exception&);
template void ErrorHandler::Throw<std::runtime_error>(std::runtime_error&);
template void ErrorHandler::Throw<std::invalid_argument>(std::invalid_argument&);

and reduces the burden to add a new exception that won't be sliced down to adding an additional line to the cpp file, which isn't included anywhere else, saving compilation times.

This also won't compile if the result would slice the exception, since then there will be a linking error.


问:
A Perl system call must send exactly both characters single & double quote ' "
A Perl system call must send the following string to the UnixShell:

```<code>'"XYZ"'
</code>```

In my Perl script I have used the following command:

```<code>system("cleartool mkattr -replace ATTRIBUTE '"$attribute"' lbtype:$label");
</code>```

Everything is well passed to the Shell Unix, except both uses of the quote character:

```<code>'
</code>```

Indeed,

```<code>cleartool mkattr -replace ATTRIBUTE
</code>```

The above command is passed as it is exactly what I want.
The Perl variables $attribute and $label are well interpreted.
But I don't know what to do to obtain exactly:

```<code>'"XYZ"'
</code>```

Here XYZ is the value of the Perl variable $attribute
OS is AIX (Unix) and Shell is ksh. cleartool is the command line interface of Clearcase but no Clearcase skill is necessary to fix my problem.

答:
See "Quote and Quote like Operators" and use qq{...}:

```<code>system(qq{cleartool mkattr -replace ATTRIBUTE '"$attribute"' lbtype:$label});
</code>```

qq{...} is exactly like "..." except you can then use double quotes " in your string without escaping them.

You can use any character directly after the qq and must then use the same character to denote the end-of-string, i.e. qqX...X would work the same way. You would run into problems if your string contains Xes, so don't do that.

You can also use paired characters as delimiter ({}, (), <>) which is what you usually will see.

Body:
A Perl system call must send the following string to the UnixShell:

'"XYZ"'

In my Perl script I have used the following command:

system("cleartool mkattr -replace ATTRIBUTE '"$attribute"' lbtype:$label");

Everything is well passed to the Shell Unix, except both uses of the quote character:

'

Indeed,

cleartool mkattr -replace ATTRIBUTE

The above command is passed as it is exactly what I want.
The Perl variables $attribute and $label are well interpreted.
But I don't know what to do to obtain exactly:

'"XYZ"'

Here XYZ is the value of the Perl variable $attribute
OS is AIX (Unix) and Shell is ksh. cleartool is the command line interface of Clearcase but no Clearcase skill is necessary to fix my problem.

Body:
See "Quote and Quote like Operators" and use qq{...}:

system(qq{cleartool mkattr -replace ATTRIBUTE '"$attribute"' lbtype:$label});

qq{...} is exactly like "..." except you can then use double quotes " in your string without escaping them.

You can use any character directly after the qq and must then use the same character to denote the end-of-string, i.e. qqX...X would work the same way. You would run into problems if your string contains Xes, so don't do that.

You can also use paired characters as delimiter ({}, (), <>) which is what you usually will see.


问:
Prolog bidirectional predicate
I have to create family relations in Prolog for an assignment and I stumbled upon this problem.

```<code>man(john).
woman(lisa).
married(john,lisa).

?- married(john,X).
X = lisa.

?- married(X,john).
false.
</code>```

How to make this predicate work in two ways?
If john is married to lisa, then lisa is married to john.

For facts I can only use gender, parent, and married:

```<code>man(john).
woman(lisa).
parent(john,steve).
parent(lisa,steve).
married(john,lisa).
</code>```

That requirement makes this solution unusable for me. I can't just add relation wife(lisa,john). because I have to define wife, husband etc. by myself, like.

```<code>wife(X,Y) :- woman(X),married(X,Y).
</code>```

答:
If you can't add helper relation (it sounds like homework exercise), try to use predicate @< which operates on the "Standard Order of Terms":

```<code>married(A,B) :- A @< B, married(B,A).
</code>```

Note, however, that this solution brings also some negative aspects (please read this answer).

Title: Prolog bidirectional predicate

Body:
I have to create family relations in Prolog for an assignment and I stumbled upon this problem.

man(john).
woman(lisa).
married(john,lisa).

?- married(john,X).
X = lisa.

?- married(X,john).
false.

How to make this predicate work in two ways?
If john is married to lisa, then lisa is married to john.

For facts I can only use gender, parent, and married:

man(john).
woman(lisa).
parent(john,steve).
parent(lisa,steve).
married(john,lisa).

That requirement makes this solution unusable for me. I can't just add relation wife(lisa,john). because I have to define wife, husband etc. by myself, like.

wife(X,Y) :- woman(X),married(X,Y).

Body:
If you can't add helper relation (it sounds like homework exercise), try to use predicate @< which operates on the "Standard Order of Terms":

married(A,B) :- A @< B, married(B,A).

Note, however, that this solution brings also some negative aspects (please read this answer).


问:
batch script to send email
How to write a Windows batch script to send a mail? Give an example</p>

答:
You will need to use a third party tool such as blat (http://www.blat.net/).  Then in your batch file, you would have a line like the following:

blat -to foo@bar.com -f bar@foo.com -subject "Email Subject" -body "Email body" -server mysmtphost

Title: batch script to send email


问:
Compare Two Named Pipe Handles
Is it possible to compare two HANDLE objects of the Named Pipe variety?

If, for example, I have a list of all active Handles via Process Explorer or some similar tool, could I compare a given Handle to all active Handles to determine which Handle from the list point towards the same Named Pipe?

I can't use the native function NtQueryObject here sadly, too unstable.

I've also tried to simply determine the name of the named pipe given it's handle using GetFinalPathNameByHandle but it appears to be incompatible with named pipe handles.

答: Since Windows 10 there is a reliable way using CompareObjectHandles

Title: Compare Two Named Pipe Handles


问:
reduxForm 7.0.4 Unknown props `input`, `meta` on <input> tag. Remove these props from the element
I'm setting up a form wizard as demonstrated here, but am getting the above error.

The component it finds objectionable is

```<code><Field
    name="Company"
    component={company => (
                            <div>
                            <input type="text" {...company}
                             placeholder="company" />
                            {company.touched && company.error && <span>
                            {company.error}</span>}
                            </div>
    )}
/>
</code>```

I understand that the tutorial is written for reduxForm 6.5.0 and I'm running 7.0.4, so what do I need to change to make this work?

答:
Found it-the updated tutorial is here: https://redux-form.com/7.0.4/examples/wizard/

Essentially, we use a helper called renderField.js:

import React from 'react'

```<code>const renderField = ({ input, label, type, meta: { touched, error } }) =>
  <div>
    <label>
      {label}
    </label>
    <div>
      <input {...input} placeholder={label} type={type} />
      {touched &&
        error &&
        <span>
          {error}
        </span>}
    </div>
  </div>

export default renderField
</code>```

Then, fields are rendered thusly:

```<code><Field
        name="firstName"
        type="text"
        component={renderField}
        label="First Name"
      />
</code>```

Body:
I'm setting up a form wizard as demonstrated here, but am getting the above error.

The component it finds objectionable is

<Field
    name="Company"
    component={company => (

                            <input type="text" {...company}
                             placeholder="company" />
                            {company.touched && company.error &&
                            {company.error}}

    )}
/>

I understand that the tutorial is written for reduxForm 6.5.0 and I'm running 7.0.4, so what do I need to change to make this work?

Body:
Found it-the updated tutorial is here: https://redux-form.com/7.0.4/examples/wizard/

Essentially, we use a helper called renderField.js:

import React from 'react'

const renderField = ({ input, label, type, meta: { touched, error } }) =>
  <div>
    <label>
      {label}
    </label>
    <div>
      <input {...input} placeholder={label} type={type} />
      {touched &&
        error &&
        <span>
          {error}
        </span>}
    </div>
  </div>

export default renderField

Then, fields are rendered thusly:

<Field
        name="firstName"
        type="text"
        component={renderField}
        label="First Name"
      />


问:
Elasticsearch process memory locking failed
I have set boostrap.memory_lock=true
Updated /etc/security/limits.conf added memlock unlimited for elastic search user

My elastic search was running fine for many months. Suddenly it failed 1 day back. In logs I can see below error and process never starts

ERROR: bootstrap checks failed
memory locking requested for elasticsearch process but memory is not locked

I hit ulimit -as and I can see max locked memory set to unlimited. What is going wrong here? I have been trying for hours but all in vain. Please help.

OS is RHEL 7.2
Elasticsearch 5.1.2

ulimit -as output

```<code>core file size        (blocks -c) 0
data seg size         (kbytes -d) unlimited
scheduling policy            (-e) 0
file size            (blocks, -f) unlimited
pending signals              (-i) 83552
max locked memory    (kbytes, -l) unlimited
max memory size      (kbytes, -m) unlimited
open files                   (-n) 65536
pipe size         (512 bytes, -q) 8
POSIX message queues   (bytes,-q) 819200
real-time priority           (-r) 0
stack size            kbytes, -s) 8192
cpu time             seconds, -t) unlimited
max user processes           (-u) 4096
virtual memory       (kbytes, -v) unlimited
file locks                   (-x) unlimited
</code>```

答:
Make sure that your elasticsearch start process is configured to unlimited. For if e.g. you start elasticsarch with another user as the one configured in /etc/security/limits.conf or as root while defining a wildcard entry in limits.conf (which is not for root) it won't work.

Test itto be sure:
you could e.g. put ulimit -a ; exit just after the "#Start Daemon" in /etc/init.d/elasticsearch and start with bash /etc/init.d/elasticsearch start (adapt accordingly to your start mechanism).

Body:
I have set boostrap.memory_lock=true
Updated /etc/security/limits.conf added memlock unlimited for elastic search user

My elastic search was running fine for many months. Suddenly it failed 1 day back. In logs I can see below error and process never starts

ERROR: bootstrap checks failed
memory locking requested for elasticsearch process but memory is not locked

I hit ulimit -as and I can see max locked memory set to unlimited. What is going wrong here? I have been trying for hours but all in vain. Please help.

OS is RHEL 7.2
Elasticsearch 5.1.2

ulimit -as output

core file size        (blocks -c) 0
data seg size         (kbytes -d) unlimited
scheduling policy            (-e) 0
file size            (blocks, -f) unlimited
pending signals              (-i) 83552
max locked memory    (kbytes, -l) unlimited
max memory size      (kbytes, -m) unlimited
open files                   (-n) 65536
pipe size         (512 bytes, -q) 8
POSIX message queues   (bytes,-q) 819200
real-time priority           (-r) 0
stack size            kbytes, -s) 8192
cpu time             seconds, -t) unlimited
max user processes           (-u) 4096
virtual memory       (kbytes, -v) unlimited
file locks                   (-x) unlimited


问:
How to set a Multiline-TextView non-editable
I have a TextView which is from inputType="textMultiLine". The problem is, when I click (and hold) in a free part of the TextView (a part where is no text), it presents me the option of pasting text in. And when I do so, it overwrites the existing text with the text in the clipboard.
I don't want this behavior. What can I do to make the TextView non-editable?

this is the xml-Code:

```<code><TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1. Hello, Dies ist ein Beispielsatz. \n2. Dies ist der zweite Satz."
        android:textSize="20dp"
        android:inputType="textMultiLine"
        />
</code>```

Note:
If I remove the inputType="textMultiLine", the option of pasting text is no longer presented. But I want the TextView to be multiline.

答:
```<code>.setFocusable(false);
</code>```

Setting this to false will also ensure that this view is not focusable
  in touch mode.

XML

```<code>android:focusable="false"
</code>```

Body:
I have a TextView which is from inputType="textMultiLine". The problem is, when I click (and hold) in a free part of the TextView (a part where is no text), it presents me the option of pasting text in. And when I do so, it overwrites the existing text with the text in the clipboard.
I don't want this behavior. What can I do to make the TextView non-editable?

this is the xml-Code:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1. Hello, Dies ist ein Beispielsatz. \n2. Dies ist der zweite Satz."
        android:textSize="20dp"
        android:inputType="textMultiLine"
        />

Note:
If I remove the inputType="textMultiLine", the option of pasting text is no longer presented. But I want the TextView to be multiline.

Body:
.setFocusable(false);

Setting this to false will also ensure that this view is not focusable
  in touch mode.

XML

android:focusable="false"


问:
Is there a way to specify ANYTHING as an argument to NUnit Mocks Expect call?
I'm using NUnit mocks and would like to specify that I expect a call but without saying what the arguments will be for example:

```<code>mock.ExpectAndReturn("Equals", true, ANY_ARGUMENT);
</code>```

Obviously filling in the correct syntax instead of ANY_ARGUMENT.

Is there a way to do this?

If I specify no arguments - NUnit fails the test because it expected 0 arguments but received 1.

答:
Yes there is a such a function in NUnit Mocks.

Instead of the ExpectAndReturn use SetReturnValue. First function, as it names tell you, you specify input object and return object. Last function just specify a return object for the specific function.

Use: interfaceMock.SetReturnValue("SomeRetrunFunction", someReturnFunction);

Body:
I'm using NUnit mocks and would like to specify that I expect a call but without saying what the arguments will be for example:

mock.ExpectAndReturn("Equals", true, ANY_ARGUMENT);

Obviously filling in the correct syntax instead of ANY_ARGUMENT.

Is there a way to do this?

If I specify no arguments - NUnit fails the test because it expected 0 arguments but received 1.