问:
Send data from virtual keyboard to div or from input to div in real time
I would like to ask if anybody know a way to send data in real time from virtual keyboard straight to
 or from <input> field when I type from virtual keyboard to div.

I've tried different methods but none seems to work. Similar questions on stackoverflow give me some idea but keyup function or getElementById is not working in my case please help.

Beneath is my code.

```<code><!DOCTYPE html>
<head>

    <link rel="stylesheet" href="softkeys-0.0.1.css">

    <style>
       body { background-color:#fafafa; font-family:'Roboto';}
    </style>
</head>
<body>
<input type="text" id="a" name="code" class="form-control input-lg">
</form>
<div  style="border:2px inset #AAA ;height:50px; width:500px;"  id="d" >
</div>
<script>
  $('.softkeys').click(function() {
$('#d').text($(this).val());
});
</script>

                <div class="softkeys" data-target="input[name='code']">
  </div>

            </div>
        </div>
    </div>

    <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="softkeys-0.0.1.js"></script>

    <script>
        $(document).ready(function(){
            $('.softkeys').softkeys({
                target : $('.softkeys').data('target'),
                layout : [
                    [
                        ['`','~'],
                        ['1','!'],
                        ['2','@'],
                        ['3','#'],
                        ['4','$'],
                        ['5','%'],
                        ['6','^'],
                        ['7','&'],
                        ['8','*'],
                        ['9','('],
                        ['0',')'],
                        ['-', '_'],
                        ['=','+'],
                        'delete'
                    ],
                    [
                        'q','w','e','r','t','y','u','i','o','p',
                        ['[','{'],
                        [']','}']
                    ],
                    [
                        'capslock',
                        'a','s','d','f','g','h','j','k','l',
                        [';',':'],
                        ["'",'"'],
                        ['\\','|']
                    ],
                    [
                        'shift',
                        'z','x','c','v','b','n','m',
                        [',','<'],
                        ['.','>'],
                        ['/','?'],
                        ['@']
                    ]
                ]
            });
        });
    </script>
</body>
</html>
</code>```

Everything is working like it should but the problem is when I try send data from virtual keyboard to
 or from <input> to
 the script does not work.

```<code>      $('.softkeys').click(function() {
      $('#d').text($(this).val());
      });
</code>```

答:
```<code><script>
    $('.softkeys').click(function(event) {
        $('#d').text($("#a").val());
    });
</script>
</code>```

Put the above script after the scripts for jquery and softkeys.

Also, you can make the input#a element to be hidden.

Body:
I would like to ask if anybody know a way to send data in real time from virtual keyboard straight to
 or from <input> field when I type from virtual keyboard to div.

I've tried different methods but none seems to work. Similar questions on stackoverflow give me some idea but keyup function or getElementById is not working in my case please help.

Beneath is my code.

<!DOCTYPE html>

    <link rel="stylesheet" href="softkeys-0.0.1.css">

<input type="text" id="a" name="code" class="form-control input-lg">
</form>

Everything is working like it should but the problem is when I try send data from virtual keyboard to
 or from <input> to
 the script does not work.

      $('.softkeys').click(function() {
      $('#d').text($(this).val());
      });

Body:
<script>
    $('.softkeys').click(function(event) {
        $('#d').text($("#a").val());
    });
</script>

Put the above script after the scripts for jquery and softkeys.

Also, you can make the input#a element to be hidden.


来源: stackexchange

问:
Iterate through the same methods inside objects of the same class
I am using greenfoot and am trying to iterate something so it is more clean. The cardsPile list is the current cards in the discard pile. I am trying to be more object oriented and am struggling with how to add multiple to the ArrayList. I am also trying to call methods inside of the Card object.
I am trying to make the following process be iterable.

```<code> card1.setLocation(100,200);
 cpu2.setLocation(100,200);
 card2.setLocation(100,200);
 cpu3.setLocation(100,200);
</code>```

Since card1, etc is defined above like:

```<code> Card card1 = cards.get(1);
 Card card2 = cards.get(2);
 Card card3 = cards.get(3);
 Card card4 = cards.get(4);
 Card cpu1 = cpuCards.get(1);
 Card cpu2 = cpuCards.get(2);
 Card cpu3 = cpuCards.get(3);
 Card cpu4 = cpuCards.get(4);
</code>```

I am also trying to add them to the cardPile ArrayList by adding them by object as follows

```<code> cardsPile.add(curCard);
 cardsPile.add(card1);
 cardsPile.add(card2);
 cardsPile.add(card3);
 cardsPile.add(card4);
 cardsPile.add(cpu1);
 cardsPile.add(cpu2);
 cardsPile.add(cpu3);
 cardsPile.add(cpu4);
</code>```

Any ideas on how to iterate calling methods of the Card object are appreciated. Thank you!

答:
To iterate through all you variables you should store them in array or some kind of collection, like this:

see here

```<code>    ArrayList<Card> alCard = new ArrayList<Card>();
    for(int cardIdx = 1; cardIdx <= 4; cardIdx++) {
        alCard.add(cards.get(cardIdx));
    }
    ArrayList<Card> alCpu = new ArrayList<Card>();
    for(int cardIdx = 1; cardIdx <= 4; cardIdx++) {
        alCpu.add(cards.get(cardIdx));
    }

    ArrayList<Card> cardsPile = new ArrayList<Card>();
    cardsPile.add(curCard);
    for(int cardIdx = 0; cardIdx < alCard.size(); cardIdx++) {
        cardsPile.add(alCard.get(cardIdx));
    }
    for(int cardIdx = 0; cardIdx < alCpu.size(); cardIdx++) {
        cardsPile.add(alCpu.get(cardIdx));
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using greenfoot and am trying to iterate something so it is more clean. The cardsPile list is the current cards in the discard pile. I am trying to be more object oriented and am struggling with how to add multiple to the ArrayList. I am also trying to call methods inside of the Card object.
I am trying to make the following process be iterable.

 card1.setLocation(100,200);
 cpu2.setLocation(100,200);
 card2.setLocation(100,200);
 cpu3.setLocation(100,200);

Since card1, etc is defined above like:

 Card card1 = cards.get(1);
 Card card2 = cards.get(2);
 Card card3 = cards.get(3);
 Card card4 = cards.get(4);
 Card cpu1 = cpuCards.get(1);
 Card cpu2 = cpuCards.get(2);
 Card cpu3 = cpuCards.get(3);
 Card cpu4 = cpuCards.get(4);

I am also trying to add them to the cardPile ArrayList by adding them by object as follows

 cardsPile.add(curCard);
 cardsPile.add(card1);
 cardsPile.add(card2);
 cardsPile.add(card3);
 cardsPile.add(card4);
 cardsPile.add(cpu1);
 cardsPile.add(cpu2);
 cardsPile.add(cpu3);
 cardsPile.add(cpu4);

Any ideas on how to iterate calling methods of the Card object are appreciated. Thank you!

Body:
To iterate through all you variables you should store them in array or some kind of collection, like this:

see here

    ArrayList<Card> alCard = new ArrayList<Card>();
    for(int cardIdx = 1; cardIdx <= 4; cardIdx++) {
        alCard.add(cards.get(cardIdx));
    }
    ArrayList<Card> alCpu = new ArrayList<Card>();
    for(int cardIdx = 1; cardIdx <= 4; cardIdx++) {
        alCpu.add(cards.get(cardIdx));
    }

    ArrayList<Card> cardsPile = new ArrayList<Card>();
    cardsPile.add(curCard);
    for(int cardIdx = 0; cardIdx < alCard.size(); cardIdx++) {
        cardsPile.add(alCard.get(cardIdx));
    }
    for(int cardIdx = 0; cardIdx < alCpu.size(); cardIdx++) {
        cardsPile.add(alCpu.get(cardIdx));
    }


问:
Get the titles of all open windows using VBA
I have found a previous thread that shows how to get all open windows and their names using C# : get the titles of all open windows

However, I need to do this in VBA: does anyone know if that's possible?

Thank you so much.

Best regards

答:
```<code>Sub ListWindows()
    Dim wn As Excel.Window
    For Each wn In Application.Windows
        Debug.Print wn.Caption
    Next wn
End Sub
</code>```

if you wanted to activate any of them simply use:

```<code> wn.Activate
</code>```

Body:
Sub ListWindows()
    Dim wn As Excel.Window
    For Each wn In Application.Windows
        Debug.Print wn.Caption
    Next wn
End Sub

if you wanted to activate any of them simply use:

 wn.Activate


问:
How do I set the “all ajax stop” function for multiple ajax requests?
```<code>xhr = $.ajax;
xhr({
  success: function(){ ajaxProcess = false; },
  beforeSend : function (i) {
    if(ajaxProcess==true)
    xhr.abort();
    else
    ajaxProcess = true;
  }
});

$('.button').click(function(){
  $.getJSON('file.php', function(data){});
};

$('.button2').click(function(){
  $.getJSON('file.php', function(data){});
};
</code>```

答:
Use the global ajaxSend handler
http://api.jquery.com/ajaxSend/

EDIT

To stop all executing requests, you can do something like the following. Create an array of request objects. Then in the the global ajaxSend handler you can add the request to the array and do your check. If the check succeeds, iterate through the array and abort all of the requests. Then you can create a global ajaxStop handler that removes the requests from the request array as they finish executing.

ContentLicense: CC BY-SA 2.5


问:
Using SQL queries and php while loops to create an html table
I have 5 SQL queries. I want to display the results of those in a table in HTML. Right now, I have nested while loops reading the results of those queries. However, the resulting table repeats the first row for the first 5 columns (Route appears in all the queries). The 6th column is correct.

Here is my table declaration, queries after connecting to the database, and while loops:

```<code><table style="width:100%">
    <tr>
       <th>Route</th>
       <th>Total Cost ($)</th>
       <th>Utilization (%)</th>
       <th>Number Locations Serviced</th>
       <th>Total Time (Hrs)</th>
       <th>Cost per Item Delivered ($)</th>
    </tr>

    $query1 = "SELECT RouteID as Route, ROUND(SUM(CostTo), 2) as TotalCost FROM VehicleRoutes, ContractID WHERE ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM ContractID) AND ContractID.ContractID = VehicleRoutes.ContractID GROUP BY RouteID";

    $result1 = mysqli_query($conn, $query1);

    $query2 = "SELECT Items.RouteID as Route, ROUND((COUNT(*)/ContractID.TruckCapacity)*100, 3) as UtilizationPercentage FROM Items, ContractID WHERE Items.ContractID = ContractID.ContractID AND Items.RouteID != 'NA' AND ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM ContractID) GROUP BY Items.RouteID";

    $result2 = mysqli_query($conn, $query2);

    $query3 = "SELECT V.RouteID as Route, COUNT(V.LocationIDTo) as NumLocationsServiced FROM VehicleRoutes as V, ContractID WHERE ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM ContractID) AND V.LocationIDTo != 'Warehouse' AND V.ContractID = ContractID.ContractID GROUP BY V.RouteID";

    $result3 = mysqli_query($conn, $query3);

    $query4 = "SELECT V.RouteID as Route, ROUND(SUM(V.TravelTime + V.DeliveryTime), 3) as TotalTime FROM VehicleRoutes as V, ContractID WHERE ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM ContractID) AND ContractID.ContractID = V.ContractID GROUP BY V.RouteID";

    $result4 = mysqli_query($conn, $query4);

    $query5 = "SELECT  I.RouteID AS Route, ROUND(SUM(V.CostTo) / COUNT(I.ItemID) , 2) AS CostPerItemDelivered FROM Items AS I, VehicleRoutes AS V, ContractID WHERE  ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM  ContractID) AND  I.RouteID !=  'NA' AND  I.RouteID =  V.RouteID AND  I.ContractID =  ContractID.ContractID AND  V.ContractID =  I.ContractID GROUP BY  I.RouteID";

    $result5 = mysqli_query($conn, $query5);

    while($col1 = mysqli_fetch_array($result1)){
        while($col2 = mysqli_fetch_array($result2)){
        while($col3 = mysqli_fetch_array($result3)){
            while($col4 = mysqli_fetch_array($result4)){
                while($col5 = mysqli_fetch_array($result5)){
                echo "<tr><td>".$col1["Route"]."</td><td>".$col1["TotalCost"]."</td><td>".$col2["UtilizationPercentage"]."</td><td>".$col3["NumLocationsServiced"]."</td><td>".$col4["TotalTime"]."</td><td>".$col5["CostPerItemDelivered"]."</td></tr>";
                    }
                }
            }
        }
    }
</code>```

And here is the result I'm getting:
I checked the results individually before putting them in the loops, so I know they are correct. I'm just not sure why the first row is repeating itself for everything but "Cost/Item Delivered."

答:
You need to do is data mapping, to transform the source data (from SQL) to target data (table data). I have updated the while-loop part and this is one of the example how to transform the data:</p>

```<code>$targetData = array();

function addData(&$targetData, $routeId, $dataKey, $dataValue) {
    if (!isset($targetData[$routeId])) $targetData[$routeId] = array();
    $targetData[$routeId][$dataKey] = $dataValue;
}

while($col1 = mysqli_fetch_array($result1)) {
    addData($targetData, $col1['Route'], 'TotalCost', $col1['TotalCost']);
}

while($col2 = mysqli_fetch_array($result2)) {
    addData($targetData, $col2['Route'], 'UtilizationPercentage', $col2['UtilizationPercentage']);
}

while($col3 = mysqli_fetch_array($result3)) {
    addData($targetData, $col3['Route'], 'NumLocationsServiced', $col3['NumLocationsServiced']);
}

while($col4 = mysqli_fetch_array($result4)) {
    addData($targetData, $col4['Route'], 'TotalTime', $col4['TotalTime']);
}

while($col5 = mysqli_fetch_array($result5)) {
    addData($targetData, $col5['Route'], 'CostPerItemDelivered', $col5['CostPerItemDelivered']);
}

foreach ($targetData as $routeId => $data) {

    echo '<tr>' .
            '<td>' . $routeId . '</td>' .
            '<td>' . (isset($data['TotalCost']) ? $data['TotalCost'] : ' ') . '</td>' .
            '<td>' . (isset($data['UtilizationPercentage']) ? $data['UtilizationPercentage'] : ' ') . '</td>' .
            '<td>' . (isset($data['NumLocationsServiced']) ? $data['NumLocationsServiced'] : ' ') . '</td>' .
            '<td>' . (isset($data['TotalTime']) ? $data['TotalTime'] : ' ') . '</td>' .
            '<td>' . (isset($data['CostPerItemDelivered']) ? $data['CostPerItemDelivered'] : ' ') . '</td>' .
        '</tr>';

}
</code>```

Body:
I have 5 SQL queries. I want to display the results of those in a table in HTML. Right now, I have nested while loops reading the results of those queries. However, the resulting table repeats the first row for the first 5 columns (Route appears in all the queries). The 6th column is correct.

Here is my table declaration, queries after connecting to the database, and while loops:

       Route
       Total Cost ($)
       Utilization (%)
       Number Locations Serviced
       Total Time (Hrs)
       Cost per Item Delivered ($)

    $query1 = "SELECT RouteID as Route, ROUND(SUM(CostTo), 2) as TotalCost FROM VehicleRoutes, ContractID WHERE ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM ContractID) AND ContractID.ContractID = VehicleRoutes.ContractID GROUP BY RouteID";

    $result1 = mysqli_query($conn, $query1);

    $query2 = "SELECT Items.RouteID as Route, ROUND((COUNT(*)/ContractID.TruckCapacity)*100, 3) as UtilizationPercentage FROM Items, ContractID WHERE Items.ContractID = ContractID.ContractID AND Items.RouteID != 'NA' AND ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM ContractID) GROUP BY Items.RouteID";

    $result2 = mysqli_query($conn, $query2);

    $query3 = "SELECT V.RouteID as Route, COUNT(V.LocationIDTo) as NumLocationsServiced FROM VehicleRoutes as V, ContractID WHERE ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM ContractID) AND V.LocationIDTo != 'Warehouse' AND V.ContractID = ContractID.ContractID GROUP BY V.RouteID";

    $result3 = mysqli_query($conn, $query3);

    $query4 = "SELECT V.RouteID as Route, ROUND(SUM(V.TravelTime + V.DeliveryTime), 3) as TotalTime FROM VehicleRoutes as V, ContractID WHERE ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM ContractID) AND ContractID.ContractID = V.ContractID GROUP BY V.RouteID";

    $result4 = mysqli_query($conn, $query4);

    $query5 = "SELECT  I.RouteID AS Route, ROUND(SUM(V.CostTo) / COUNT(I.ItemID) , 2) AS CostPerItemDelivered FROM Items AS I, VehicleRoutes AS V, ContractID WHERE  ContractID.ContractID >= ALL(SELECT ContractID.ContractID FROM  ContractID) AND  I.RouteID !=  'NA' AND  I.RouteID =  V.RouteID AND  I.ContractID =  ContractID.ContractID AND  V.ContractID =  I.ContractID GROUP BY  I.RouteID";

    $result5 = mysqli_query($conn, $query5);

    while($col1 = mysqli_fetch_array($result1)){
        while($col2 = mysqli_fetch_array($result2)){
        while($col3 = mysqli_fetch_array($result3)){
            while($col4 = mysqli_fetch_array($result4)){
                while($col5 = mysqli_fetch_array($result5)){
                echo "
".$col1["Route"]."	".$col1["TotalCost"]."	".$col2["UtilizationPercentage"]."	".$col3["NumLocationsServiced"]."	".$col4["TotalTime"]."	".$col5["CostPerItemDelivered"]."
";
                    }
                }
            }
        }
    }

And here is the result I'm getting:
I checked the results individually before putting them in the loops, so I know they are correct. I'm just not sure why the first row is repeating itself for everything but "Cost/Item Delivered."

Body:
You need to do is data mapping, to transform the source data (from SQL) to target data (table data). I have updated the while-loop part and this is one of the example how to transform the data:

$targetData = array();

function addData(&$targetData, $routeId, $dataKey, $dataValue) {
    if (!isset($targetData[$routeId])) $targetData[$routeId] = array();
    $targetData[$routeId][$dataKey] = $dataValue;
}

while($col1 = mysqli_fetch_array($result1)) {
    addData($targetData, $col1['Route'], 'TotalCost', $col1['TotalCost']);
}

while($col2 = mysqli_fetch_array($result2)) {
    addData($targetData, $col2['Route'], 'UtilizationPercentage', $col2['UtilizationPercentage']);
}

while($col3 = mysqli_fetch_array($result3)) {
    addData($targetData, $col3['Route'], 'NumLocationsServiced', $col3['NumLocationsServiced']);
}

while($col4 = mysqli_fetch_array($result4)) {
    addData($targetData, $col4['Route'], 'TotalTime', $col4['TotalTime']);
}

while($col5 = mysqli_fetch_array($result5)) {
    addData($targetData, $col5['Route'], 'CostPerItemDelivered', $col5['CostPerItemDelivered']);
}

foreach ($targetData as $routeId => $data) {

    echo '<tr>' .
            '<td>' . $routeId . '</td>' .
            '<td>' . (isset($data['TotalCost']) ? $data['TotalCost'] : '&nbsp;') . '</td>' .
            '<td>' . (isset($data['UtilizationPercentage']) ? $data['UtilizationPercentage'] : '&nbsp;') . '</td>' .
            '<td>' . (isset($data['NumLocationsServiced']) ? $data['NumLocationsServiced'] : '&nbsp;') . '</td>' .
            '<td>' . (isset($data['TotalTime']) ? $data['TotalTime'] : '&nbsp;') . '</td>' .
            '<td>' . (isset($data['CostPerItemDelivered']) ? $data['CostPerItemDelivered'] : '&nbsp;') . '</td>' .
        '</tr>';

}


问:
How to check status-code of URL of the application in protractor test?
I am using request package to request the url and using deferred promise :

```<code>getMonitoredPageName = function () {
    var deferredExecutor = protractor.promise.defer();
    var defer = protractor.promise.defer();

    request('http://google.com',
    function (error, response, body) {
        if (error || response.statusCode ==400) {
            defer.reject(response.statusCode);
        } else {
            defer.fulfill(response.statusCode);
        }
    });

    return defer.promise;
}
</code>```

And i am calling above function from test as :

```<code>  it('should log the page name of every page view in the wizard', function () {

    // We opened the first page of the wizard and we expect it to have been logged
    expect(heartBeatNotification.getMonitoredPageName()).toBeTruthy(true);
    //expect(heartBeatNotification.getMonitoredPageName()).toBe(400);
    //browser.controlFlow().execute(heartBeatNotification.getMonitoredPageName);

})
</code>```

Problem is test case always succeeds no matter what url has given. Need to write test case to check Application is running or not.

答:
I was able to get the test working this way. It's a little simplified over what you were trying to do but it should help you figure it out. One thing to note, the way you have your if block setup has issues. If response is undefined the test will timeout and the promise will never return. Anyhow, here is how I was able to get your test working.

```<code>it('should return status code 200', async () => {
    const url = 'http://google.com';
    await heartBeatNotification.getMonitoredPageName(url).then(statusCode => {
        expect(statusCode).toEqual(200);
    }, () => {
        fail('app not started');
    });
});
</code>```

Here is the function:

```<code>getMonitoredPageName = (url) => {
    const defer = protractor.promise.defer();

    request(url, (err, response, body) => {
        if(err) {
            defer.reject();
        } else {
            defer.fulfill(response.statusCode);
        }
    });

    return defer.promise;
}
</code>```

Body:
I am using request package to request the url and using deferred promise :

getMonitoredPageName = function () {
    var deferredExecutor = protractor.promise.defer();
    var defer = protractor.promise.defer();

    request('http://google.com',
    function (error, response, body) {
        if (error || response.statusCode ==400) {
            defer.reject(response.statusCode);
        } else {
            defer.fulfill(response.statusCode);
        }
    });

    return defer.promise;
}

And i am calling above function from test as :

  it('should log the page name of every page view in the wizard', function () {

    // We opened the first page of the wizard and we expect it to have been logged
    expect(heartBeatNotification.getMonitoredPageName()).toBeTruthy(true);
    //expect(heartBeatNotification.getMonitoredPageName()).toBe(400);
    //browser.controlFlow().execute(heartBeatNotification.getMonitoredPageName);

})

Problem is test case always succeeds no matter what url has given. Need to write test case to check Application is running or not.

Body:
I was able to get the test working this way. It's a little simplified over what you were trying to do but it should help you figure it out. One thing to note, the way you have your if block setup has issues. If response is undefined the test will timeout and the promise will never return. Anyhow, here is how I was able to get your test working.

it('should return status code 200', async () => {
    const url = 'http://google.com';
    await heartBeatNotification.getMonitoredPageName(url).then(statusCode => {
        expect(statusCode).toEqual(200);
    }, () => {
        fail('app not started');
    });
});

Here is the function:

getMonitoredPageName = (url) => {
    const defer = protractor.promise.defer();

    request(url, (err, response, body) => {
        if(err) {
            defer.reject();
        } else {
            defer.fulfill(response.statusCode);
        }
    });

    return defer.promise;
}


问:
defaultSession,ProgrammingSession,extendedDiagnosticSession
I am not understanding about defaultSession,ProgrammingSession,extendedDiagnosticSession in UDS protocol.
How can we go from one session to another session? please help me.Thank you.</p>

答:
default session = ECU is in normal operation state, but it usualy response only to limited set of diagnostic requests. From this state you can usually switch into:

extended session to perform some diagnostic services, to talk with ECU (Read/Write values, start/stop routines etc.) Here you expect that ECU give a more or less timely response on your requests. therefore you can also switch between sessions

programming session to flash ECU memory, to update ECU SW. While updating ECU usually do not answer on diagnostic requests. Therefore it's not usual to switch from programming session into extended session or even into default session as this switch is a diagnostic request from tester. At the end of an update ECU can perform some memory checks and it will do a reset. When update was successful it will restart in default session.

There can be also other diagnostic sessions for example: dealer session, OEM session...


问:
What would be the maximum value of PHP rand() function , if we provide no parameters to it ??
I want to know what maximum value and minimum value PHP rand() function returns if we don't provide any parameter like min and max
e.g.</p>

```<code>//what will be maximum and minimum output of this
echo rand();
</code>```

答:
If we give no arguments to rand() function, random number can be generated between 0 and getrandmax() as per the PHP documentation.

grandmax() function always takes the maximum number depends upon your operating system such as Windows where the maximum number is 32767 that can be generated.

So its clear from this, In Windows when we run rand() function without arguments:

Minimum Number that can be generated is 0

Maximum Number that can be generated is 32767

Below links can help further to know rand() function but there is no documentation regarding maximum number generated in Mac or other Operating Systems:

http://php.net/manual/en/function.rand.php

https://www.w3resource.com/php/function-reference/rand.php

https://www.w3schools.com/php/func_math_rand.asp

Body:
I want to know what maximum value and minimum value PHP rand() function returns if we don't provide any parameter like min and max
e.g.

//what will be maximum and minimum output of this
echo rand();


问:
Error inserting a document in a MongoDB sharded collection created with the CLI
Using the latest azure cli (2.0.21) I am trying to create in CosmosDB a sharded MongoDB collection with the following script (from powershell) :

```<code>$resourceGroupName="RG-S01-APP-CASRWA-001"
$name="marcoolandesetest"
$databaseName="marco"
$collectionName="fromcli"
$originalThroughput=100000
$kind="MongoDB"
$partition="/TaskId"

az login
az cosmosdb create --name $name --kind $kind --resource-group
$resourceGroupName

az cosmosdb database create --name $name --db-name $databaseName --resource-
group $resourceGroupName

az cosmosdb collection create --collection-name $collectionName --name $name --db-name $databaseName --resource-group $resourceGroupName --throughput $originalThroughput --partition-key-path $partition --indexing-policy '@index.json'
</code>```

The content of the index.json is the following:

```<code>{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/*",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                },
                {
                    "kind": "Hash",
                    "dataType": "String",
                    "precision": 3
                }
            ]
        }
    ],
    "excludedPaths": []
}
</code>```

But when I try to insert a document from the UI in the portal nothing happens, the document hangs on inserting:

Inserting a document from a C# library with the MongoB.Drivers nuget package also fails, getting the error:

"document does not contain shard key"

obviously my document contains the shard key property "TaskId".

If I create the same kind of collection from the UI in the Portal everything works fine, also in C#, using the same code

Here are two screenshots of the settings of the collections, as you can see they are the same:

Collection "fromui" is created from the portal UI, and with this one everything works fine, inserting a document from the portal, and inserting from C# as well.

Collection "fromcli" is created using the CLI script above and inserting a document it's not working at all.

答:
Microsoft confirmed there is a bug in the CLI (2.0.21), they will soon roll out an update.

I created a blog post to describe how to solve this until a new CLI version will be release with a fix:

https://blog.olandese.nl/2017/12/13/create-a-sharded-mongodb-in-azure-cosmos-db/

Body:
Using the latest azure cli (2.0.21) I am trying to create in CosmosDB a sharded MongoDB collection with the following script (from powershell) :

$resourceGroupName="RG-S01-APP-CASRWA-001"
$name="marcoolandesetest"
$databaseName="marco"
$collectionName="fromcli"
$originalThroughput=100000
$kind="MongoDB"
$partition="/TaskId"

az login
az cosmosdb create --name $name --kind $kind --resource-group
$resourceGroupName

az cosmosdb database create --name $name --db-name $databaseName --resource-
group $resourceGroupName

az cosmosdb collection create --collection-name $collectionName --name $name --db-name $databaseName --resource-group $resourceGroupName --throughput $originalThroughput --partition-key-path $partition --indexing-policy '@index.json'

The content of the index.json is the following:

{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/*",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                },
                {
                    "kind": "Hash",
                    "dataType": "String",
                    "precision": 3
                }
            ]
        }
    ],
    "excludedPaths": []
}

But when I try to insert a document from the UI in the portal nothing happens, the document hangs on inserting:

Inserting a document from a C# library with the MongoB.Drivers nuget package also fails, getting the error:

"document does not contain shard key"

obviously my document contains the shard key property "TaskId".

If I create the same kind of collection from the UI in the Portal everything works fine, also in C#, using the same code

Here are two screenshots of the settings of the collections, as you can see they are the same:

Collection "fromui" is created from the portal UI, and with this one everything works fine, inserting a document from the portal, and inserting from C# as well.

Collection "fromcli" is created using the CLI script above and inserting a document it's not working at all.


问:
Openshift 3: Where are the log files and how to manage them?
I have a Openshift 3 starter app (python).  Using the web console I can see my logs.  Where is the actual file? After a while the file will be getting big and will needed to be deleted I assume.

On Openshift 2 there was a "rhc tidy" command to clean the log files out.  Is there something similar for Openshift 3? Is there a way to do this automatically? On Openshift 2 I was able to set up a cron job to do this monthly however Openshift 3 Starter does not support cron jobs.

Suggestions?

答: Logging in OpenShift 3 is to stdout, it's the standard method of logging for Docker containers. So no files to worry about keeping tidy.


问:
Blank entries in a DropDownList using an IList as a dataProvider
I'm dynamically creating an IList to use as a dataprovider for a DropDownList in Flex.

The code is creating the IList correctly, and I can access the data inside just fine.

However, when I set the dataprovider for my DropDownList, it only shows blank entries for each  item in the list.

So, if I had 30 items in my IList, I will have 30 blank spots in my dropdown.

Here's the code I'm using.

```<code>categoryXML = new XML(loader.data);

for each(var category in categoryXML.category) {
    categoryArr.addItem(category.name);
}

categoryList = categoryArr;
cats2.dataProvider = categoryList;
</code>```

What could cause this? I can't seem to find anything via Google.

答:
It's hard to tell without looking at your actual data.  But, it appears you are creating an array of Strings.  I have no idea how a Spark list handles simple values.

You might try something like this:

```<code>for each(var category in categoryXML.category) {
    var newObject : Object = new Object();
    newObject.label = category.name;
    categoryArr.addItem(newObject.);
}
</code>```

However, if category.name is a complex XML object, then you'll probably need to create a labelFunction.  Something like this:

```<code>public myLabelFunction(item:Object):String{
  return item.valueToDisplay;
}
</code>```

And set it on the list like this:

```<code>myList.labelFunction = myLabelFunction;
</code>```

Body:
I'm dynamically creating an IList to use as a dataprovider for a DropDownList in Flex.

The code is creating the IList correctly, and I can access the data inside just fine.

However, when I set the dataprovider for my DropDownList, it only shows blank entries for each  item in the list.

So, if I had 30 items in my IList, I will have 30 blank spots in my dropdown.

Here's the code I'm using.

categoryXML = new XML(loader.data);

for each(var category in categoryXML.category) {
    categoryArr.addItem(category.name);
}

categoryList = categoryArr;
cats2.dataProvider = categoryList;

What could cause this? I can't seem to find anything via Google.

Body:
It's hard to tell without looking at your actual data.  But, it appears you are creating an array of Strings.  I have no idea how a Spark list handles simple values.

You might try something like this:

for each(var category in categoryXML.category) {
    var newObject : Object = new Object();
    newObject.label = category.name;
    categoryArr.addItem(newObject.);
}

However, if category.name is a complex XML object, then you'll probably need to create a labelFunction.  Something like this:

public myLabelFunction(item:Object):String{
  return item.valueToDisplay;
}

And set it on the list like this:

myList.labelFunction = myLabelFunction;


问:
Material Icons not working via React-materialize
I have a site using Middleman, Webpack and Materialize, we have a React component in one of the pages that works ok apart from the fact that Material Icons are not rendered on Internet Explorer and Firefox; all icons in the rest of the site work fine across all browsers.
Any help would be appreciated.

Packages used

materialize-css 0.100.2 => I tried 0.97, 0.98 with the same result

webpack 3.10.0

react 16.2.0 => I tried with 15.xx versions and got the same result

react-materialize 1.1.1

In my layout I'm importing the icons according to the Docs

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="preload" as="style" onload="this.rel='stylesheet'">

what is being displayed at the moment is the icon name like alarm_off or  as I've tried both input methods

答:
After reading lots of blogs and issues on GitHub, I managed to solved the problem thanks to this Google issue, so I added this in my style.scss

```<code>@font-face {
  font-family: "Material Icons";
  font-style: normal;
  font-weight: 400;
  src: local("Material Icons"),
       local("MaterialIcons-Regular"),
       url(https://rawgit.com/google/material-design-icons/master/iconfont/MaterialIcons-Regular.woff2) format("woff2"),
       url(https://rawgit.com/google/material-design-icons/master/iconfont/MaterialIcons-Regular.woff) format("woff"),
       url(https://rawgit.com/google/material-design-icons/master/iconfont/MaterialIcons-Regular.ttf) format("truetype");
}

.material-icons {
  font-family: "Material Icons";
  font-weight: normal;
  font-style: normal;
  font-size: 24px;
  line-height: 1;
  letter-spacing: normal;
  text-transform: none;
  display: inline-block;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;

  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: "liga";
}
</code>```

Also, I updated this in my nginx

```<code>  location ~* \.(?:eot|otf|ttc|ttf|woff|woff2)$ {
  expires 1M;
  add_header Access-Control-Allow-Origin "*";
  add_header Cache-Control "public";
</code>```

Hope this help somebody else with similar issues.

Body:
After reading lots of blogs and issues on GitHub, I managed to solved the problem thanks to this Google issue, so I added this in my style.scss

@font-face {
  font-family: "Material Icons";
  font-style: normal;
  font-weight: 400;
  src: local("Material Icons"),
       local("MaterialIcons-Regular"),
       url(https://rawgit.com/google/material-design-icons/master/iconfont/MaterialIcons-Regular.woff2) format("woff2"),
       url(https://rawgit.com/google/material-design-icons/master/iconfont/MaterialIcons-Regular.woff) format("woff"),
       url(https://rawgit.com/google/material-design-icons/master/iconfont/MaterialIcons-Regular.ttf) format("truetype");
}

.material-icons {
  font-family: "Material Icons";
  font-weight: normal;
  font-style: normal;
  font-size: 24px;
  line-height: 1;
  letter-spacing: normal;
  text-transform: none;
  display: inline-block;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;

  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: "liga";
}

Also, I updated this in my nginx

  location ~* \.(?:eot|otf|ttc|ttf|woff|woff2)$ {
  expires 1M;
  add_header Access-Control-Allow-Origin "*";
  add_header Cache-Control "public";

Hope this help somebody else with similar issues.


答:
You don't/can't sort maps.  They are automatically sorted by key based on the optional third parameter to the template arguments, which is a function object class used to compare two elements to determine which should come first. (it should return true if the first should come before the second, false otherwise)

So you can use something like this:

```<code>struct myCompare
{
    bool operator() const (const map<int,int> & lhs, const map<int,int> & rhs)
    {
        return lhs.size() < rhs.size();
    }
};
</code>```

But since map<int,int> is your value, and not your key, this won't exactly work for you.

Title: Sorting map by size

Body:
I have similar map:

map<int, map<int, map<int, int> > > myMap;

order-num | id | order-num-of-relation | relation-id
-----------------------------------------------------
    0     | 1  | 0                     | 2
-----------------------------------------------------
    1     | 2  | 0                     | 1
-----------------------------------------------------
          |    | 1                     | 3
-----------------------------------------------------
    2     | 3  | 0                     | 2
-----------------------------------------------------

1(1), 2(2), 3(1)

and i need to sort (change the "order-num") this map by size of the last map (order-num-of-relation | relation-id).

I just need to do this:

order-num | id | order-num-of-relation | relation-id
-----------------------------------------------------
    0     | 1  | 0                     | 2
-----------------------------------------------------
    1     | 3  | 0                     | 2
-----------------------------------------------------
    2     | 2  | 0                     | 1
-----------------------------------------------------
          |    | 1                     | 3
-----------------------------------------------------

1(1), 3(1), 2(2)

can i use the "sort" function and pass here own sorting function (where i can checking size and returing true/false), or do i have to write explicite sorting algorithm?

Body:
You don't/can't sort maps.  They are automatically sorted by key based on the optional third parameter to the template arguments, which is a function object class used to compare two elements to determine which should come first. (it should return true if the first should come before the second, false otherwise)

So you can use something like this:

struct myCompare
{
    bool operator() const (const map<int,int> & lhs, const map<int,int> & rhs)
    {
        return lhs.size() < rhs.size();
    }
};

But since map<int,int> is your value, and not your key, this won't exactly work for you.


问:
How to reset intellisense in VS Code?
If you make a code change while VsCode is debugging, the intellisense sometimes appears to malfunction with false compile errors.  Fastest way to reset or correct it?</p>

答:
Restart VsCode.

If you find IntelliSense has stopped working, the language service may not be running. Try restarting VS Code and this should solve the issue.

Title: How to reset intellisense in VS Code?


问:
psycopg2.Data Error: invalid input syntax for integer:" "

Hi..i tried to search for an entry in my table that holds both text and integer values..my code works well on sqlite3 database...but throws Data Error on Postgresql database..

```<code>import psycopg2
class database:

    def __init__(self):

        self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
        self.cur=self.con.cursor()
        self.cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL UNIQUE,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL UNIQUE)")
        self.con.commit()

    def insert(self,title,author,year,isbn):
      try:
        self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
        self.con.commit()
      except:
          #print("already exists..")
          pass

    def view(self):
        self.cur.execute("SELECT * FROM books")
        rows=self.cur.fetchall()
        print(rows)

    def search(self,title="",author="",year="",isbn=""):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.ferchall()
        print(row)

db=database()
#db.insert("The Naughty","AparnaKumar",1995,234567654)
db.view()
db.search(year=1995)
</code>```

答:
This is what you want:</p>

```<code>def search(self, title=None, author=None, year=None, isbn=None):
    self.cursor.execute("""
        select *
        from books
        where
            (title = %(title)s or %(title)s is null)
            and
            (author = %(author)s or %(author)s is null)
            and
            (year = %(year)s or %(year)s is null)
            and
            (isbn = %(isbn)s or %(isbn)s is null)
        """,
        {'title': title, 'author': author, 'year': year, 'isbn': isbn}
    )
</code>```

Body:
Hi..i tried to search for an entry in my table that holds both text and integer values..my code works well on sqlite3 database...but throws Data Error on Postgresql database..

import psycopg2
class database:

    def __init__(self):

        self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
        self.cur=self.con.cursor()
        self.cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL UNIQUE,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL UNIQUE)")
        self.con.commit()

    def insert(self,title,author,year,isbn):
      try:
        self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
        self.con.commit()
      except:
          #print("already exists..")
          pass

    def view(self):
        self.cur.execute("SELECT * FROM books")
        rows=self.cur.fetchall()
        print(rows)

    def search(self,title="",author="",year="",isbn=""):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.ferchall()
        print(row)

db=database()
#db.insert("The Naughty","AparnaKumar",1995,234567654)
db.view()
db.search(year=1995)

Body:
This is what you want:

def search(self, title=None, author=None, year=None, isbn=None):
    self.cursor.execute("""
        select *
        from books
        where
            (title = %(title)s or %(title)s is null)
            and
            (author = %(author)s or %(author)s is null)
            and
            (year = %(year)s or %(year)s is null)
            and
            (isbn = %(isbn)s or %(isbn)s is null)
        """,
        {'title': title, 'author': author, 'year': year, 'isbn': isbn}
    )


问:
Deploy Spring Boot jar on Azure App Service
I'm having trouble getting a Spring Boot API to work on an Azure app service. I've followed the Microsoft guide on https://learn.microsoft.com/en-us/java/azure/spring-framework/deploy-spring-boot-java-web-app-on-azure but having no luck so far.

The application does start (I can see the app boot up in the log file) but http requests to the app service url always end in a timeout.

I've read that Azure app services only pick up embedded tomcat servers that run on port 80 or 8080, but had no luck with that as well.

The app is deployed in the www root and an appropriate web.config is deployed as well.

I've tried running the App Service with and without an application server (Tomcat and Jetty, that is not needed because the server is embedded in the application), but both approaches failed.

Am I missing some other configuration part? Or could this be related to the type of plan I'm using on azure? Maybe some issue with the resource?

Any pointers?

Thx,

Bert

答:
In order to get a Springboot application running you need to upload your JAR file and add the web.config file.

To communicate to the service what you are trying to run, you need to add a web.config file to the site\wwwroot folder of the app service. As you have already created web.config file, use Maven to add the following and get a project / release dynamically included on package.

```<code><build>
    <resources>
        <resource>
            <directory>${project.basedir}/wwwroot</directory>
            <filtering>true</filtering>
            <targetPath>${basedir}/target</targetPath>
        </resource>
    </resources>
</build>
</code>```

Now place the jar file and the web.config within the Azure App Service.

You can just check once whether you have created the web.config file as below,

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
        </handlers>
        <httpPlatform processPath="%JAVA_HOME%\bin\java.exe"
        arguments="-Djava.net.preferIPv4Stack=true -Dserver.port=%HTTP_PLATFORM_PORT% -jar "%HOME%\site\wwwroot\@project.artifactId@-@project.version@.jar"">
        </httpPlatform>
    </system.webServer>
</configuration>
</code>```

Body:
In order to get a Springboot application running you need to upload your JAR file and add the web.config file.

To communicate to the service what you are trying to run, you need to add a web.config file to the site\wwwroot folder of the app service. As you have already created web.config file, use Maven to add the following and get a project / release dynamically included on package.

<build>
    <resources>
        <resource>
            <directory>${project.basedir}/wwwroot</directory>
            <filtering>true</filtering>
            <targetPath>${basedir}/target</targetPath>
        </resource>
    </resources>
</build>

Now place the jar file and the web.config within the Azure App Service.

You can just check once whether you have created the web.config file as below,

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
        </handlers>
        <httpPlatform processPath="%JAVA_HOME%\bin\java.exe"
        arguments="-Djava.net.preferIPv4Stack=true -Dserver.port=%HTTP_PLATFORM_PORT% -jar &quot;%HOME%\site\wwwroot\@project.artifactId@-@project.version@.jar&quot;">
        </httpPlatform>
    </system.webServer>
</configuration>


问:
change django application directory in PyCharm
I have set up a Django project in PyCharm using pipenv.

I have used pipenv to create the virtual environment in my project directory.
Within the virtual environment directory, I have created src directory to place my Django project.

The directory structure is like

```<code>/ Project Directory
|- src
   |- django_app
   |- other_app
   |- manage.py
   |- db.sqlite3
|- Pipfile
|- Pipfile.lock
</code>```

In PyCharm IDE, I have opened the Project Directory as a project.

When I use Alt+Enter to auto import modules from other apps. The import line is prefixed with src. like

```<code>from src.other_app.models import ModelName
</code>```

Whereas It should be

```<code>from other_app.models import ModelName
</code>```

How can I reconfigure Django path in PyCharm to use src directory as root for Dango apps/modules?

答: In pycharm when you open a project you are setting the path environment var in the folder that you opened, in this case Project Directory, but you can change path in pycharm doing something like is described in this answer. Only add /src/ at the end of the path marked by (added by user)

Body:
I have set up a Django project in PyCharm using pipenv.

I have used pipenv to create the virtual environment in my project directory.
Within the virtual environment directory, I have created src directory to place my Django project.

The directory structure is like

/ Project Directory
|- src
   |- django_app
   |- other_app
   |- manage.py
   |- db.sqlite3
|- Pipfile
|- Pipfile.lock

In PyCharm IDE, I have opened the Project Directory as a project.

When I use Alt+Enter to auto import modules from other apps. The import line is prefixed with src. like

from src.other_app.models import ModelName

Whereas It should be

from other_app.models import ModelName

How can I reconfigure Django path in PyCharm to use src directory as root for Dango apps/modules?


问:
How can I differentiate the data coming from multiple HTTP client origins in StreamSets
I have 6 pipelines each have the HTTP client origin connected to the SDCRPC destinations, my plan is to make another pipeline with SDCRPC origin and destination to hive tables.

My question is after connecting to the SDCRPC origin how can I differentiate the data because each HTTP pipeline pulls the data related to one identical table.

Any examples or online resources will be appreciated.

答: Add an expression evaluator to each of the 6 HTTP->SDCRPC pipelines, each of them adding a different header attribute value to the records. Now your SDCRPC origin pipeline can look at that header attribute to figure out which pipeline it came from.</p>


问:
What do spaCy's part-of-speech and dependency tags mean?
spaCy tags up each of the Tokens in a Document with a part of speech (in two different formats, one stored in the pos and pos_ properties of the Token and the other stored in the tag and tag_ properties) and a syntactic dependency to its .head token (stored in the dep and dep_ properties).

Some of these tags are self-explanatory, even to somebody like me without a linguistics background:

```<code>>>> import spacy
>>> en_nlp = spacy.load('en')
>>> document = en_nlp("I shot a man in Reno just to watch him die.")
>>> document[1]
shot
>>> document[1].pos_
'VERB'
</code>```

Others... are not:

```<code>>>> document[1].tag_
'VBD'
>>> document[2].pos_
'DET'
>>> document[3].dep_
'dobj'
</code>```

Worse, the official docs don't contain even a list of the possible tags for most of these properties, nor the meanings of any of them. They sometimes mention what tokenization standard they use, but these claims aren't currently entirely accurate and on top of that the standards are tricky to track down.

What are the possible values of the tag_, pos_, and dep_ properties, and what do they mean?

答:
At present, dependency parsing and tagging in SpaCy appears to be implemented only at the word level, and not at the phrase (other than noun phrase) or clause level. This means SpaCy can be used to identify things like nouns (NN, NNS), adjectives (JJ, JJR, JJS), and verbs (VB, VBD, VBG, etc.), but not adjective phrases (ADJP), adverbial phrases (ADVP), or questions (SBARQ, SQ).

For illustration, when you use SpaCy to parse the sentence "Which way is the bus going?", we get the following tree.

By contrast, if you use the Stanford parser you get a much more deeply structured syntax tree.

Body:
spaCy tags up each of the Tokens in a Document with a part of speech (in two different formats, one stored in the pos and pos_ properties of the Token and the other stored in the tag and tag_ properties) and a syntactic dependency to its .head token (stored in the dep and dep_ properties).

Some of these tags are self-explanatory, even to somebody like me without a linguistics background:

>>> import spacy
>>> en_nlp = spacy.load('en')
>>> document = en_nlp("I shot a man in Reno just to watch him die.")
>>> document[1]
shot
>>> document[1].pos_
'VERB'

Others... are not:

>>> document[1].tag_
'VBD'
>>> document[2].pos_
'DET'
>>> document[3].dep_
'dobj'

Worse, the official docs don't contain even a list of the possible tags for most of these properties, nor the meanings of any of them. They sometimes mention what tokenization standard they use, but these claims aren't currently entirely accurate and on top of that the standards are tricky to track down.

What are the possible values of the tag_, pos_, and dep_ properties, and what do they mean?


问:
How to use a WITH block with dynamic sql query
I've got a plpgsql function that needs to prepare data from 3 tables based on user input, and export the data using COPY TO. The data are road accidents, so the 3 tables are accident, casualty and vehicle, each accident links to zero or more records in the vehicle and casualty tables via an accidentid column that exists in all three tables. severity and local_authorities are input parameters (both text []).

```<code>sql_query = 'SELECT COUNT(*) FROM accident WHERE severity = ANY(' || quote_literal(severity)
 || ') AND local_auth = ANY (' || quote_literal(local_authorities) || ')';

EXECUTE sql_query INTO result_count;

IF result_count > 0 THEN
   -- replace Select Count(*) With Select *
   sql_query = Overlay(sql_query placing '*' from 8 for 8);

   -- copy the accident data first
   EXECUTE 'COPY (' || sql_query || ') TO ' || quote_literal(file_path || file_name_a) ||
     ' CSV';
</code>```

This first bit will get the relevant accidents, so I'm now looking for the most efficient way to use the accidentid's from the first query to download the related vehicle and casualty data.

I thought I'd be able to use a WITH block like this:

```<code>-- replace * with accidentid
sql_query = Overlay(sql_query placing 'accidentid' from 8 for 1);

WITH acc_ids AS (sql_query)
  EXECUTE 'COPY (SELECT * FROM vehicle WHERE accidentid IN (SELECT accidentid FROM
  acc_ids)) TO ' || out_path_and_vfilename || ' CSV';
  EXECUTE 'COPY (SELECT * FROM casualty WHERE accidentid IN (SELECT accidentid FROM
  acc_ids)) TO ' || out_path_and_cfilename || ' CSV';
</code>```

but get an error:

ERROR:  syntax error at or near "$1"

LINE 1: WITH acc_ids AS ( $1 ) EXECUTE 'COPY (SELECT * FROM accident....

I have tried the above in a non-dynamic test case e.g.

```<code>WITH acc_ids AS (
    SELECT accidentid FROM accident
    WHERE severity = ANY ('{3,2}')
    AND local_auth = ANY ('{E09000001,E09000002}')
    )
    SELECT * FROM vehicle
    WHERE accidentid IN (
    SELECT accidentid FROM acc_ids);
</code>```

which works. Unfortunately the server is still running Postgres 8.4 so I can't use format() for the time being.

Perhaps this isn't possible with a WITH block, but I hope it at least illustrates what I'm trying to achieve.

Edit/Update

The main goal is to get the relevant data from the 3 tables in 3 separate csv files, ideally without having to run the selection on the accident table 3 times

答:
If you want to run a query (part) that is stored in a string variable, you need a dynamic query like

```<code>EXECUTE 'WITH acc_ids AS (' || sql_query || ')'
   'SELECT ... ';
</code>```

Either the whole query is a string executed by EXECUTE, or the whole query is static SQL. You cannot mix them.

Do you need a CTE? If you can express the query as a join, the optimizer has more options.

Body:
I've got a plpgsql function that needs to prepare data from 3 tables based on user input, and export the data using COPY TO. The data are road accidents, so the 3 tables are accident, casualty and vehicle, each accident links to zero or more records in the vehicle and casualty tables via an accidentid column that exists in all three tables. severity and local_authorities are input parameters (both text []).

sql_query = 'SELECT COUNT(*) FROM accident WHERE severity = ANY(' || quote_literal(severity)
 || ') AND local_auth = ANY (' || quote_literal(local_authorities) || ')';

EXECUTE sql_query INTO result_count;

IF result_count > 0 THEN
   -- replace Select Count(*) With Select *
   sql_query = Overlay(sql_query placing '*' from 8 for 8);

   -- copy the accident data first
   EXECUTE 'COPY (' || sql_query || ') TO ' || quote_literal(file_path || file_name_a) ||
     ' CSV';

This first bit will get the relevant accidents, so I'm now looking for the most efficient way to use the accidentid's from the first query to download the related vehicle and casualty data.

I thought I'd be able to use a WITH block like this:

-- replace * with accidentid
sql_query = Overlay(sql_query placing 'accidentid' from 8 for 1);

WITH acc_ids AS (sql_query)
  EXECUTE 'COPY (SELECT * FROM vehicle WHERE accidentid IN (SELECT accidentid FROM
  acc_ids)) TO ' || out_path_and_vfilename || ' CSV';
  EXECUTE 'COPY (SELECT * FROM casualty WHERE accidentid IN (SELECT accidentid FROM
  acc_ids)) TO ' || out_path_and_cfilename || ' CSV';

but get an error:

ERROR:  syntax error at or near "$1"

LINE 1: WITH acc_ids AS ( $1 ) EXECUTE 'COPY (SELECT * FROM accident....

I have tried the above in a non-dynamic test case e.g.

WITH acc_ids AS (
    SELECT accidentid FROM accident
    WHERE severity = ANY ('{3,2}')
    AND local_auth = ANY ('{E09000001,E09000002}')
    )
    SELECT * FROM vehicle
    WHERE accidentid IN (
    SELECT accidentid FROM acc_ids);

which works. Unfortunately the server is still running Postgres 8.4 so I can't use format() for the time being.

Perhaps this isn't possible with a WITH block, but I hope it at least illustrates what I'm trying to achieve.

Edit/Update

The main goal is to get the relevant data from the 3 tables in 3 separate csv files, ideally without having to run the selection on the accident table 3 times

Body:
If you want to run a query (part) that is stored in a string variable, you need a dynamic query like

EXECUTE 'WITH acc_ids AS (' || sql_query || ')'
   'SELECT ... ';

Either the whole query is a string executed by EXECUTE, or the whole query is static SQL. You cannot mix them.

Do you need a CTE? If you can express the query as a join, the optimizer has more options.


问:
Shuffle randomly values in array - python
I have the following array

```<code>a = [1, 2, 5, 4, 3, 6, 1]
</code>```

And I want to know how I can shuffle any two values randomly within an array that isn't either the first or last value. Some examples of the desired results below:

```<code>Output =

[1, 4, 5, 2, 3, 6, 1]

[1, 2, 3, 4, 5, 6, 1]

[1, 6, 5, 4, 3, 2, 1]

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

Is there a way to do this in python?

答:
Try this,</p>

```<code>import random
from random import shuffle

a = [1, 2, 5, 4, 3, 6, 1]
hold = a[1:-1]
random.shuffle(hold)
shuffled_list = [a[0]] + hold + [a[-1]]
shuffled_list
>>
Out[87]:
[1, 5, 4, 3, 6, 2, 1]
</code>```

Body:
I have the following array

a = [1, 2, 5, 4, 3, 6, 1]

And I want to know how I can shuffle any two values randomly within an array that isn't either the first or last value. Some examples of the desired results below:

Output =

[1, 4, 5, 2, 3, 6, 1]

[1, 2, 3, 4, 5, 6, 1]

[1, 6, 5, 4, 3, 2, 1]

[1, 3, 5, 4, 2, 6, 1]

Is there a way to do this in python?

Body:
Try this,

import random
from random import shuffle

a = [1, 2, 5, 4, 3, 6, 1]
hold = a[1:-1]
random.shuffle(hold)
shuffled_list = [a[0]] + hold + [a[-1]]
shuffled_list
>>
Out[87]:
[1, 5, 4, 3, 6, 2, 1]


问:
HTML POST Submit button not working
I got my page which is a simple password unlocker, but the post submit form button won't work...

```<code><div class="content">
            <form action="/action_page.php" method="post">
                <div class="user-profile">
                    <div class="author">
                        <img class="avatar" src="../../assets/img/default-avatar.png" alt="...">
                    </div>
                    <h4>User Unlock</h4>
                    <div class="form-group">
                        <input type="password" placeholder="Enter Password" class="form-control">
                    </div>
                    <button type="button" class="btn btn-neutral btn-round btn-fil btn-wd">Unlock</button>
                </div>
            </form>
        </div>
</code>```

When I click the button nothing happens..

It does not redirect to action_page.php nor sends any data.

答:
if action_page.php is in the same folder as the current page, you don't need backslash. So change it into

```<code><form action="action_page.php" method="post">
</code>```

also, you must declare the button as submit if you want to get redirected to action_page.php

```<code><button type="submit" class="btn btn-neutral btn-round btn-fil btn-wd">Unlock</button>
</code>```

Title: HTML POST Submit button not working

Body:
I got my page which is a simple password unlocker, but the post submit form button won't work...

            <form action="/action_page.php" method="post">

User Unlock

                        <input type="password" placeholder="Enter Password" class="form-control">

                    <button type="button" class="btn btn-neutral btn-round btn-fil btn-wd">Unlock</button>

            </form>

When I click the button nothing happens..

It does not redirect to action_page.php nor sends any data.

Body:
if action_page.php is in the same folder as the current page, you don't need backslash. So change it into

<form action="action_page.php" method="post">

also, you must declare the button as submit if you want to get redirected to action_page.php

<button type="submit" class="btn btn-neutral btn-round btn-fil btn-wd">Unlock</button>


问:
Check If Local Branch Exists On Remote Git
I would like to see if one of my newly created local branches exists on the remote with a one line command. Like making an alias or function that would allow me to type

```<code>git remoteExists <branchName>
</code>```

Right now I manually list off every branch on the remote and check to see if my local branch is there. This is not as easy as I would like since our remote has hundreds of branches, many with similar names.

I'm switching branches often working on different things, maybe 6-7 at a time, and it's difficult to remember if I've completed and pushed a branch or if I still need to finish it up.

I've searched and found some ways to do things similar to this, but many seemed unnecessarily complicated, is there a simpler way to do this?

EDIT

To be clear on what I'm doing. I'm starting from a remote branch and making a local branch off that. I'm making changes to my local branch and pushing. I do not want to set an upstream branch, since I will not be using this branch again; the person handling the remote branch will look at my changes and integrate them into the remote version.

This works:

```<code>git diff <branchName> remotes/origin/<branchName>
</code>```

fatal: ambiguous argument 'remotes/origin/TestReadyBranch': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git  [...] -- [...]'

Upon seeing this error I would know that the branch doesn't exist on the remote. Is there a cleaner way to do this?

答:
This will set exit code to 2 if current branch does not exist on remote:

```<code>git ls-remote --heads --exit-code origin "$(git symbolic-ref --short HEAD)"
</code>```

Then you can check in shell:

```<code>if [ $? -eq 2 ]
</code>```

Or in ruby:

```<code>if $?.exitstatus == 2
</code>```

Or similarly in any other language.

Body:
I would like to see if one of my newly created local branches exists on the remote with a one line command. Like making an alias or function that would allow me to type

git remoteExists <branchName>

Right now I manually list off every branch on the remote and check to see if my local branch is there. This is not as easy as I would like since our remote has hundreds of branches, many with similar names.

I'm switching branches often working on different things, maybe 6-7 at a time, and it's difficult to remember if I've completed and pushed a branch or if I still need to finish it up.

I've searched and found some ways to do things similar to this, but many seemed unnecessarily complicated, is there a simpler way to do this?

EDIT

To be clear on what I'm doing. I'm starting from a remote branch and making a local branch off that. I'm making changes to my local branch and pushing. I do not want to set an upstream branch, since I will not be using this branch again; the person handling the remote branch will look at my changes and integrate them into the remote version.

This works:

git diff <branchName> remotes/origin/<branchName>

fatal: ambiguous argument 'remotes/origin/TestReadyBranch': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git  [...] -- [...]'

Upon seeing this error I would know that the branch doesn't exist on the remote. Is there a cleaner way to do this?

Body:
This will set exit code to 2 if current branch does not exist on remote:

git ls-remote --heads --exit-code origin "$(git symbolic-ref --short HEAD)"

Then you can check in shell:

if [ $? -eq 2 ]

Or in ruby:

if $?.exitstatus == 2

Or similarly in any other language.


问:
What is the exact chain of events when GNU make updates the .d files?
Consider the following simple makefile:

```<code>#------------------------------#
#    List all object files     #
#------------------------------#
objects := main.o foo.o bar.o baz.o

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)
</code>```

If you give the command make all, GNU make will start at the target myApp.elf. It looks at all the prerequisites main.o, foo.o, bar.o and baz.o and attempts to update them.

To do that, make uses the pattern rule defined in the middle of the makefile. This pattern rule expands like this:

```<code>main.o: main.c
    $(CC) -c $(CFLAGS) main.c -o main.o

foo.o: foo.c
    $(CC) -c $(CFLAGS) foo.c -o foo.o

bar.o: bar.c
    $(CC) -c $(CFLAGS) bar.c -o bar.o

baz.o: baz.c
    $(CC) -c $(CFLAGS) baz.c -o baz.o
</code>```

So far, so good. But you can clearly see that dependencies (included h-files) are missing.

I found some sources that recommend the following approach:

```<code>#------------------------------#
#    List all object files     #
#    and all dependency files  #
#------------------------------#
objects := main.o foo.o bar.o baz.o
deps := $(objects:.o=.d)

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) -MMD -MP $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)

-include $(deps)
</code>```

I'm trying to wrap my head around this approach. First GNU make reads the makefile and looks for other included makefiles (see GNU make manual paragraph 3.5 "How Makefiles Are Remade"). Make attempts to update each included makefile it can find (in this case the dependency files main.d, foo.d, bar.d and baz.d) before starting execution of the makefiles. I've summarized this in the following figure:

Exactly. I don't see any rule where the dependency files are specified as targets.

Please help me to understand what actually happens next. Please, write your answer as a step-by-step chain of events. That would be great to gain insight in the matter.

Note:

Of course, the -MMD and -MP arguments in the compilation command (see pattern rule in the middle) lead to dependency files getting created. But the targets of this pattern rule are the object-files, not the dependency-files.

Note:

I had wrongly assumed that GNU make has an implicit rule getting activated here. But thanks to your comments and answers, I now know this was wrong :-)

答:
There is no built-in make rule for .d files. You can see that that make does consider rebuilding .d files with make -d, but there is no rule, e.g:

Reading makefile 'test/debug/library.d' (search path) (don't care) (no ~ expansion)...
Updating makefiles....
 Considering target file 'test/debug/library.d'.
  File 'test/debug/library.d' does not exist.
  Looking for an implicit rule for 'test/debug/library.d'.
  No implicit rule found for 'test/debug/library.d'.
  Finished prerequisites of target file 'test/debug/library.d'.
 Must remake target 'test/debug/library.d'.
 Failed to remake target file 'test/debug/library.d'.
```

In the above output make checks whether library.d needs to be updated. Failing to find a rule for it, make skips updating it, see How Makefiles Are Remade:

... after reading in all makefiles, make will consider each as a goal target and attempt to update it. If a makefile has a rule which says how to update it (found either in that very makefile or in another one) or if an implicit rule applies to it, it will be updated if necessary.

And this is why it does not compile each .c twice.

You can print all the rules, including the built-ins, using make --print-data-base.

Body:
Consider the following simple makefile:

#------------------------------#
#    List all object files     #
#------------------------------#
objects := main.o foo.o bar.o baz.o

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)

If you give the command make all, GNU make will start at the target myApp.elf. It looks at all the prerequisites main.o, foo.o, bar.o and baz.o and attempts to update them.

To do that, make uses the pattern rule defined in the middle of the makefile. This pattern rule expands like this:

main.o: main.c
    $(CC) -c $(CFLAGS) main.c -o main.o

foo.o: foo.c
    $(CC) -c $(CFLAGS) foo.c -o foo.o

bar.o: bar.c
    $(CC) -c $(CFLAGS) bar.c -o bar.o

baz.o: baz.c
    $(CC) -c $(CFLAGS) baz.c -o baz.o

So far, so good. But you can clearly see that dependencies (included h-files) are missing.

I found some sources that recommend the following approach:

#------------------------------#
#    List all object files     #
#    and all dependency files  #
#------------------------------#
objects := main.o foo.o bar.o baz.o
deps := $(objects:.o=.d)

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) -MMD -MP $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)

-include $(deps)

I'm trying to wrap my head around this approach. First GNU make reads the makefile and looks for other included makefiles (see GNU make manual paragraph 3.5 "How Makefiles Are Remade"). Make attempts to update each included makefile it can find (in this case the dependency files main.d, foo.d, bar.d and baz.d) before starting execution of the makefiles. I've summarized this in the following figure:

Exactly. I don't see any rule where the dependency files are specified as targets.

Please help me to understand what actually happens next. Please, write your answer as a step-by-step chain of events. That would be great to gain insight in the matter.

Note:

Of course, the -MMD and -MP arguments in the compilation command (see pattern rule in the middle) lead to dependency files getting created. But the targets of this pattern rule are the object-files, not the dependency-files.

Note:

I had wrongly assumed that GNU make has an implicit rule getting activated here. But thanks to your comments and answers, I now know this was wrong :-)

Body:
There is no built-in make rule for .d files. You can see that that make does consider rebuilding .d files with make -d, but there is no rule, e.g:

Reading makefile 'test/debug/library.d' (search path) (don't care) (no ~ expansion)...
Updating makefiles....
 Considering target file 'test/debug/library.d'.
  File 'test/debug/library.d' does not exist.
  Looking for an implicit rule for 'test/debug/library.d'.
  No implicit rule found for 'test/debug/library.d'.
  Finished prerequisites of target file 'test/debug/library.d'.
 Must remake target 'test/debug/library.d'.
 Failed to remake target file 'test/debug/library.d'.

In the above output make checks whether library.d needs to be updated. Failing to find a rule for it, make skips updating it, see How Makefiles Are Remade:

... after reading in all makefiles, make will consider each as a goal target and attempt to update it. If a makefile has a rule which says how to update it (found either in that very makefile or in another one) or if an implicit rule applies to it, it will be updated if necessary.

And this is why it does not compile each .c twice.

You can print all the rules, including the built-ins, using make --print-data-base.


问:
document.on('load') is not firing in jQuery
Here is my code:

```<code>$(document).on('load', function(){
    $("html").removeClass("wf-loading");
    $("body").css("opacity", 1);
    console.log('Load Triggered');
});
</code>```

I have tried putting this code inside and outside $(document).ready() block but that doesn't change anything.

答:
The load event fires on the window object, not document.

```<code>$(window).on('load', function() {
    ...
})
</code>```

It doesn't matter whether you put this inside $(document).ready(). The window object is created before running any Javascript.

Body:
Here is my code:

$(document).on('load', function(){
    $("html").removeClass("wf-loading");
    $("body").css("opacity", 1);
    console.log('Load Triggered');
});

I have tried putting this code inside and outside $(document).ready() block but that doesn't change anything.

Body:
The load event fires on the window object, not document.

$(window).on('load', function() {
    ...
})

It doesn't matter whether you put this inside $(document).ready(). The window object is created before running any Javascript.


问:
C++ operator overloading <double> - <Matrix>
Let's suppose that we want to subtract some  value from a given matrix.
How could/should I overload that operator.

main.cpp

```<code>Matrix<double> m(10, 5);

auto r = 1.0 - m; //error: return type specified for 'operator double'
</code>```

matrix.hpp

```<code>template <typename T>
class Matrix {
public:
  Matrix operator double(T val) {
    Matrix tmp(rows, cols);

    for (unsigned int i = 0; i < rows; i++)
      for (unsigned int j = 0; j < cols; j++) {
        const unsigned int idx = VecToIdx({i, j});
        tmp[idx] = val - this[idx];
      }

    return tmp;
  }
}
</code>```

答:
Your code is trying to subtract a Matrix from a double, but your question asks to subtract a double from a Matrix instead. Those are two different operations. What do you really want to do?

In the latter case, you need to overload the subtraction operator, not the conversion operator, eg:

```<code>template <typename T>
class Matrix {
public:
    Matrix operator- (T val) {
        Matrix tmp(rows, cols);
        for (unsigned int i = 0; i < rows; i++)
            for (unsigned int j = 0; j < cols; j++) {
                const unsigned int idx = VecToIdx({i, j});
                tmp[idx] = (*this)[idx] - val;
            }
        return tmp;
    }
};
</code>```

```<code>Matrix<double> m(10, 5);

auto r = m - 1.0;
</code>```

Body:
Let's suppose that we want to subtract some  value from a given matrix.
How could/should I overload that operator.

main.cpp

Matrix<double> m(10, 5);

auto r = 1.0 - m; //error: return type specified for 'operator double'

matrix.hpp

template <typename T>
class Matrix {
public:
  Matrix operator double(T val) {
    Matrix tmp(rows, cols);

    for (unsigned int i = 0; i < rows; i++)
      for (unsigned int j = 0; j < cols; j++) {
        const unsigned int idx = VecToIdx({i, j});
        tmp[idx] = val - this[idx];
      }

    return tmp;
  }
}

Body:
Your code is trying to subtract a Matrix from a double, but your question asks to subtract a double from a Matrix instead. Those are two different operations. What do you really want to do?

In the latter case, you need to overload the subtraction operator, not the conversion operator, eg:

template <typename T>
class Matrix {
public:
    Matrix operator- (T val) {
        Matrix tmp(rows, cols);
        for (unsigned int i = 0; i < rows; i++)
            for (unsigned int j = 0; j < cols; j++) {
                const unsigned int idx = VecToIdx({i, j});
                tmp[idx] = (*this)[idx] - val;
            }
        return tmp;
    }
};

Matrix<double> m(10, 5);

auto r = m - 1.0;


问:
How do you check if IDENTITY_INSERT is set to ON or OFF in SQL Server?
I've searched for this, but threads in which it appeared tended to have answers from people who didn't understand the question.

Take the following syntax:

```<code>SET IDENTITY_INSERT Table1 ON
</code>```

How do you do something more like this:

```<code>GET IDENTITY_INSERT Table1
</code>```

I don't want to do anything whatsoever to the data in the database or to the settings to get this information though.  Thanks!

答:
You can discover whether or not identity_insert is on, and if so for what table using the code below.</p>

```<code>declare @tableWithIdentity varchar(max) = '';
SET IDENTITY_INSERT ExampleTable ON

begin try
  create table #identityCheck (id int identity(1,1))
  SET IDENTITY_INSERT #identityCheck ON
  drop table #identityCheck
end try
begin catch
  declare @msg varchar(max) = error_message()
  set @tableWithIdentity= @msg;
  set @tableWithIdentity =
  SUBSTRING(@tableWithIdentity,charindex('''',@tableWithIdentity,1)+1, 10000)

  set @tableWithIdentity = SUBSTRING(@tableWithIdentity,1, charindex('''',@tableWithIdentity,1)-1)

  print @msg;
  drop table #identityCheck
end catch

if @tableWithIdentity<>''
begin
  print ('Name of table with Identity_Insert set to ON: ' + @tableWithIdentity)
end
else
begin
  print 'No table currently has Identity Insert Set to ON'
end
</code>```

Body:
I've searched for this, but threads in which it appeared tended to have answers from people who didn't understand the question.

Take the following syntax:

SET IDENTITY_INSERT Table1 ON

How do you do something more like this:

GET IDENTITY_INSERT Table1

I don't want to do anything whatsoever to the data in the database or to the settings to get this information though.  Thanks!

Body:
You can discover whether or not identity_insert is on, and if so for what table using the code below.

declare @tableWithIdentity varchar(max) = '';
SET IDENTITY_INSERT ExampleTable ON

begin try
  create table #identityCheck (id int identity(1,1))
  SET IDENTITY_INSERT #identityCheck ON
  drop table #identityCheck
end try
begin catch
  declare @msg varchar(max) = error_message()
  set @tableWithIdentity= @msg;
  set @tableWithIdentity =
  SUBSTRING(@tableWithIdentity,charindex('''',@tableWithIdentity,1)+1, 10000)

  set @tableWithIdentity = SUBSTRING(@tableWithIdentity,1, charindex('''',@tableWithIdentity,1)-1)

  print @msg;
  drop table #identityCheck
end catch

if @tableWithIdentity<>''
begin
  print ('Name of table with Identity_Insert set to ON: ' + @tableWithIdentity)
end
else
begin
  print 'No table currently has Identity Insert Set to ON'
end


问:
Saving x, and y from `curve()` in a for loop R?
I have a function called all.priors (see R code below). My goal is to get the x and y from the curve() call inside the for loop, and save these xs and ys as object h.

(I want to have 101 rows, and 2*length(d) columns in h. This way, each 2 columns, contain x and y from a curve() run in the for loop.)

Question:

how can I correctly save the xs and ys from the curve() call? [I get the error: incorrect number of subscripts on matrix]

```<code>all.priors = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

h = matrix(NA, 101, 2*length(d))

for(i in 1:length(d)){
         p = function(x) get(d[i])(x, a, b)
     prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
likelihood = function(x) dbinom(Bi, n, x)
 posterior = function(x) prior(x)*likelihood(x)
     h[i,] = curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n")
     }
}
#Example of use:
all.priors(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dlogis"))
</code>```

答:
You just need to carefully place the values in the matrix, and then return the matrix from your function. try this</p>

```<code>all.priors = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

  h = matrix(NA, 101, 2*length(d))

  for(i in 1:length(d)){
    p = function(x) get(d[i])(x, a, b)
    prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
    likelihood = function(x) dbinom(Bi, n, x)
    posterior = function(x) prior(x)*likelihood(x)
    cv <- curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n")
    h[,i*2-1] <- cv$x
    h[,i*2] <- cv$y
  }
  h
}
all.priors(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dlogis"))
</code>```

Body:
I have a function called all.priors (see R code below). My goal is to get the x and y from the curve() call inside the for loop, and save these xs and ys as object h.

(I want to have 101 rows, and 2*length(d) columns in h. This way, each 2 columns, contain x and y from a curve() run in the for loop.)

Question:

how can I correctly save the xs and ys from the curve() call? [I get the error: incorrect number of subscripts on matrix]

all.priors = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

h = matrix(NA, 101, 2*length(d))

for(i in 1:length(d)){
         p = function(x) get(d[i])(x, a, b)
     prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
likelihood = function(x) dbinom(Bi, n, x)
 posterior = function(x) prior(x)*likelihood(x)
     h[i,] = curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n")
     }
}
#Example of use:
all.priors(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dlogis"))

Body:
You just need to carefully place the values in the matrix, and then return the matrix from your function. try this

all.priors = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

  h = matrix(NA, 101, 2*length(d))

  for(i in 1:length(d)){
    p = function(x) get(d[i])(x, a, b)
    prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
    likelihood = function(x) dbinom(Bi, n, x)
    posterior = function(x) prior(x)*likelihood(x)
    cv <- curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n")
    h[,i*2-1] <- cv$x
    h[,i*2] <- cv$y
  }
  h
}
all.priors(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dlogis"))


问:
Returning name of the concrete implementation of a func<> delegate
tl;dr version: nameof(ToCelsius) returns ToCelsius. I want something that returns the name of the underlying function, ToCelsiusByA, though.

My ToCelsius is assigned a concrete implementation thus:

```<code> Func<decimal,decimal> ToCelsius = ToCelsiusByA;
</code>```

I then call the ToCelsius function:

```<code>var degreesC = ToCelsius(degreesF);
</code>```

I'd like to name of the implemented function (ToCelsiusByA) returned, so I'm trying this:

```<code>Console.WriteLine(degreesF + " degrees F is " + degreesC + " degrees C! using " + nameof(ToCelsius));
</code>```

but, of course, this shows 'ToCelsuis' in the string.

答:
```<code>Console.WriteLine(theDelegate.Method.Name);
</code>```

but note: this won't work well for a range of scenarios involving delegates such as combined delegates or lambdas / anonymous methods.

Body:
tl;dr version: nameof(ToCelsius) returns ToCelsius. I want something that returns the name of the underlying function, ToCelsiusByA, though.

My ToCelsius is assigned a concrete implementation thus:

 Func<decimal,decimal> ToCelsius = ToCelsiusByA;

I then call the ToCelsius function:

var degreesC = ToCelsius(degreesF);

I'd like to name of the implemented function (ToCelsiusByA) returned, so I'm trying this:

Console.WriteLine(degreesF + " degrees F is " + degreesC + " degrees C! using " + nameof(ToCelsius));

but, of course, this shows 'ToCelsuis' in the string.

Body:
Console.WriteLine(theDelegate.Method.Name);

but note: this won't work well for a range of scenarios involving delegates such as combined delegates or lambdas / anonymous methods.


问:
Jquery datatable - Table header and columns width mismatching
I'm looking for help jquery data-tables header and columns width size mismatching. i mean columns size is varying based on the text lenght(datatable values).How to fix the columns should be standard width and match with tale header.

Another issue is pagination.I'm looking pagination style like Example of pagination , but i'm not getting same style in my table.Please help me.

And another request for apply same theme which given example (theme redmond) to datatable.

Please find the below my datatable in jsfiddle JSFIDDLE

```<code>$("#products1").dataTable({
       "aaData": newarray,
       "bProcessing": true,
       "bDeferRender": true,
       "bFilter": false,
       "bJQueryUI": true,
       "sPaginationType": "full_numbers",
       "bRetrieve": true,
       "bPaginate": true,
       "bSort": true,
       "aaSorting": [[4, "desc"]],
       "iDisplayLength": 5,
       "oLanguage":{
                "sInfo":"_START_-_END_ of _TOTAL_",
                "oPaginate":{
                    "sFirst": "<<",
                    "sLast": ">>",
                    "sNext": ">",
                    "sPrevious": "<"
                },
                "sLengthMenu":"Show _MENU_"
            },
       "aoColumns": [{"sWidth": "100%","sClass": "center","bSortable": false},
             {
            "sWidth": "150%","sClass": "center","bSortable": false},
             {
            "sWidth": "150%","sClass": "center","bSortable": false},
             {
            "sWidth": "150%","sClass": "center","bSortable": false}

            ],
        "aoColumnDefs": [{ "fnRender": function (o, val) {
            return o.aData[0];
        },
            "sClass": "HEADER","aTargets": [0]
    }, {
        "fnRender": function (o, val) {

            return o.aData[1];
        },
            "sClass": "list","aTargets": [1]
    }, {
    "fnRender": function (o, val) {

            return o.aData[2];
        },
            "sClass": " Number","aTargets": [2]
    },{
    "fnRender": function (o, val) {

            return o.aData[3];
        },
            "sClass": "Name","aTargets": [3]
    }]

});
</code>```

答:
$('table.dataTable').wrap('

')

with following css

.datatableWrapperdiv{
    overflow-x:auto;
    width:100%;
}

Body:
I'm looking for help jquery data-tables header and columns width size mismatching. i mean columns size is varying based on the text lenght(datatable values).How to fix the columns should be standard width and match with tale header.

Another issue is pagination.I'm looking pagination style like Example of pagination , but i'm not getting same style in my table.Please help me.

And another request for apply same theme which given example (theme redmond) to datatable.

Please find the below my datatable in jsfiddle JSFIDDLE

$("#products1").dataTable({
       "aaData": newarray,
       "bProcessing": true,
       "bDeferRender": true,
       "bFilter": false,
       "bJQueryUI": true,
       "sPaginationType": "full_numbers",
       "bRetrieve": true,
       "bPaginate": true,
       "bSort": true,
       "aaSorting": [[4, "desc"]],
       "iDisplayLength": 5,
       "oLanguage":{
                "sInfo":"_START_-_END_ of _TOTAL_",
                "oPaginate":{
                    "sFirst": "<<",
                    "sLast": ">>",
                    "sNext": ">",
                    "sPrevious": "<"
                },
                "sLengthMenu":"Show _MENU_"
            },
       "aoColumns": [{"sWidth": "100%","sClass": "center","bSortable": false},
             {
            "sWidth": "150%","sClass": "center","bSortable": false},
             {
            "sWidth": "150%","sClass": "center","bSortable": false},
             {
            "sWidth": "150%","sClass": "center","bSortable": false}

            ],
        "aoColumnDefs": [{ "fnRender": function (o, val) {
            return o.aData[0];
        },
            "sClass": "HEADER","aTargets": [0]
    }, {
        "fnRender": function (o, val) {

            return o.aData[1];
        },
            "sClass": "list","aTargets": [1]
    }, {
    "fnRender": function (o, val) {

            return o.aData[2];
        },
            "sClass": " Number","aTargets": [2]
    },{
    "fnRender": function (o, val) {

            return o.aData[3];
        },
            "sClass": "Name","aTargets": [3]
    }]

});

Body:
$('table.dataTable').wrap('<div class="datatableWrapperdiv"></div>')

with following css

.datatableWrapperdiv{
    overflow-x:auto;
    width:100%;
}


问:
Tableau: Switching worksheet
I have a tableau report that has a "Style" parameter that controls which worksheet to view. For example, if the Style="Chart" it will display the Chart worksheet, and if the Style="Summary" it will display the summary worksheet.  I got this feature working as a charm.  What if I want to add another dropdown data to the Style parameter "Both" that will display both "Chart" & "Summary". Is this possible? Can anyone provide me insights on how to accomplish this in tableau?

答:
If you filtered your worksheets by the Style parameter, you could instead filter with a formula condition.  Go to the Condition tab in the filter, and select By Formula.  Something like this may work for your Chart worksheet:

```<code>[Style] = 'Both' OR [Style] = 'Chart'
</code>```

If you used something other than filters to select the appropriate worksheet, please either explain how you're doing it or share a tdx.

Title: Tableau: Switching worksheet

Body:
If you filtered your worksheets by the Style parameter, you could instead filter with a formula condition.  Go to the Condition tab in the filter, and select By Formula.  Something like this may work for your Chart worksheet:

[Style] = 'Both' OR [Style] = 'Chart'

If you used something other than filters to select the appropriate worksheet, please either explain how you're doing it or share a tdx.


问:
Most efficient way to create a zero filled JavaScript array?
What is the most efficient way to create an arbitrary length zero filled array in JavaScript?</p>

Body:
ES6 solution:

[...new Array(5)].map(x => 0); // [0, 0, 0, 0, 0]


问:
CSS Reset, default styles for common elements
After applying a CSS reset, I want to get back to 'normal' behavior for html elements like: p, h1..h6, strong, ul and li.

Now when I say normal I mean e.g. the p element adds spacing or a carriage return like result when used, or the size of the font and boldness for a h1 tag, along with the spacing.

I realize it is totally up to me how I want to set the style, but I want to get back to normal behavior for some of the more common elements (at least as a starting point that I can tweak later on).

答:
Check out YUI (Yahoo's open source user interface conventions).

They have a base stylesheet that undoes their own reset css.
They dont actaully recommend you use it in production - since its counter productive but definitely might be worth checking out the file to get relevant snippets for what you want to 'undo'.

I recommend you watch the 40 minute talk to get up to speed.

Heres a short snippet of their base.css file :

```<code>ol li {
    /*giving OL's LIs generated numbers*/
    list-style: decimal outside;
}
ul li {
    /*giving UL's LIs generated disc markers*/
    list-style: disc outside;
}
dl dd {
    /*giving UL's LIs generated numbers*/
    margin-left:1em;
}
th,td {
    /*borders and padding to make the table readable*/
    border:1px solid #000;
    padding:.5em;
}
th {
    /*distinguishing table headers from data cells*/
    font-weight:bold;
    text-align:center;
}
</code>```

Download the full stylesheets below or read full documentation.

Yahoo reset css | Yahoo base (undo) reset css

OwnerDisplayName: public static

LastEditorDisplayName: Sam Hasler

Body:
Check out YUI (Yahoo's open source user interface conventions).

They have a base stylesheet that undoes their own reset css.
They dont actaully recommend you use it in production - since its counter productive but definitely might be worth checking out the file to get relevant snippets for what you want to 'undo'.

I recommend you watch the 40 minute talk to get up to speed.

Heres a short snippet of their base.css file :

ol li {
    /*giving OL's LIs generated numbers*/
    list-style: decimal outside;
}
ul li {
    /*giving UL's LIs generated disc markers*/
    list-style: disc outside;
}
dl dd {
    /*giving UL's LIs generated numbers*/
    margin-left:1em;
}
th,td {
    /*borders and padding to make the table readable*/
    border:1px solid #000;
    padding:.5em;
}
th {
    /*distinguishing table headers from data cells*/
    font-weight:bold;
    text-align:center;
}

Download the full stylesheets below or read full documentation.

Yahoo reset css | Yahoo base (undo) reset css

OwnerDisplayName: Simon

LastEditorDisplayName: Simon


问:
selecting using nth child selector jquery
I want to make a selection in jquery using nth child selector I have the index number as a variable suggestions;
but  $('.search_filter:nth-child('+suggestions+')').focus();
does not focus the 2 element if suggestions=1
so please tell me what I am doing wrong here.

答: My understanding of the nth-child selector is that, when it's used with a class, it only applies to an element if it is the nth element and has the class. Without seeing any of your code, my guess is you're actually trying to target the nth occurrence of an element with the class "search_filter."


问:
jQuery: find the previous sibling with a class name?
I have a HTML code like this:

```<code><div class="buildExMain">
    Select An Option
        <i class="fa fa-check-circle" aria-hidden="true"></i>
        <div class="buildExDrop">
            <p class="pSelection">Number 1</p>
            <p class="pSelection">Number 2</p>
        </div>
</div>
</code>```

Now, I'm trying to show(); the .fa element when a .pSelection is clicked on.

I tried this jquery code with no luck:

```<code>$(document).on('click','.pSelection', function(e){
    //This doesn't work////
    $(this).prev(".fa").show();

    //doesn't work either///
    $(this).prevAll(".buildExMain.fa:first").show();
});
</code>```

答:
you need to understand the this scope

by looking your code that this element can only be one of those
 elements so if you search for the sibling of this it will only look for the other
 element you have to do something like

```<code>$('.fa').show()
or
$(this).parent().prev().show() //this is because it's exactly the previous sibling
or
$(this).parent().prev('.fa').show()
</code>```

Body:
I have a HTML code like this:

    Select An Option

Number 1

Number 2

Now, I'm trying to show(); the .fa element when a .pSelection is clicked on.

I tried this jquery code with no luck:

$(document).on('click','.pSelection', function(e){
    //This doesn't work////
    $(this).prev(".fa").show();

    //doesn't work either///
    $(this).prevAll(".buildExMain.fa:first").show();
});

Body:
you need to understand the this scope

by looking your code that this element can only be one of those <p> elements so if you search for the sibling of this it will only look for the other <p> element you have to do something like

$('.fa').show()
or
$(this).parent().prev().show() //this is because it's exactly the previous sibling
or
$(this).parent().prev('.fa').show()