问:
Php Script works fully in localhost and only part works on server
I made a script that gets data from my database then uses that data for each player in my databse to calculate there skill level and other parameters that are added to a array. Then from that array all data is entered into a table in my database for toplist.

Now my problem is it works on localhost with 0 errors but when i run it on my server it seems to only run to:

```<code>echo $calculatediamondgrade." + ".$calculatediamondgradeforamted." + ".$summonerData->name."<br>";
</code>```

I am trying to get it to work and I dont see any problem with in my coding as when, could someone take a look and let me think your thoughts.

```<code><?php
set_time_limit(0);

require_once 'connect_db.php';

$emptyQuery = "TRUNCATE top_list;";
if ($conn->query($emptyQuery)) {

    $sql = "SELECT summoner_info, tier_info, ranked_champs_info FROM players_data";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {

        $players = array();
        $champsPoints = array();

        while ($row = $result->fetch_assoc()) {
            $summonerData = unserialize($row['summoner_info']);
            $tierData = unserialize($row['tier_info']);
            if ($tierData == NULL || !isset($tierData)) {
                $tierData = new stdClass();
                $tierData->tier = 'UNRANKED';
                $tierEntry = new stdClass();
                $tierEntry->division = '';
            } else {
                $tierData = $tierData[0];
                $tierEntry = $tierData->entries[0];
            }

            $ranked_champs_infoData = unserialize($row['ranked_champs_info']);

            if ($row['summoner_info'] !== "N;") {
                if ($row['ranked_champs_info'] !== "N;") {
                    foreach ($ranked_champs_infoData->champions as $champData) {
                        $champIDs = $champData->id;

                        if (!$champIDs == 0) {
                            $totalsessionsplayedwithachampion = $champData->stats->totalSessionsPlayed;

                            if ($totalsessionsplayedwithachampion >= 10) {

                                $champstotalSessionsWon = $champData->stats->totalSessionsWon;
                                $champstotalSessionsLost = $champData->stats->totalSessionsLost;

                                $getMiniomskillsNamelistside = $champData->stats->totalMinionKills;
                                $KDAMinniomsSide = $getMiniomskillsNamelistside / ($totalsessionsplayedwithachampion);

                                if (isset($champData->stats) && isset($champData->stats->totalChampionKills)) {
                                    /* Champion total kills */
                                    $champsdatazkillz = $champData->stats->totalChampionKills;
                                } else {
                                    $champsdatazkillz = 0;
                                }

                                if (isset($champData->stats) && isset($champData->stats->totalAssists)) {
                                    /* Champion total assists */
                                    $champsdatazassitsz = $champData->stats->totalAssists;
                                } else {
                                    $champsdatazassitsz = 0;
                                }

                                if (isset($champData->stats) && isset($champData->stats->totalDeathsPerSession)) {
                                    /* Champion total deaths */
                                    $champsdatazdeathz = $champData->stats->totalDeathsPerSession;
                                } else {
                                    $champsdatazdeathz = 0;
                                }

                                if ($champsdatazdeathz == 0) {
                                    $KDAsidechamps = ($champsdatazkillz + $champsdatazassitsz);
                                } else {
                                    $KDAsidechamps = ($champsdatazkillz + $champsdatazassitsz) / $champsdatazdeathz;
                                }

                                if ($tierData->tier == "CHALLENGER") {
                                    $championrankMOD = '1.9';
                                    $championrankKDA = 0.95;
                                    $championrankKDAminniom = 0.0095;
                                } else if ($tierData->tier == "MASTER") {
                                    $championrankMOD = '1.85';
                                    $championrankKDA = 0.93;
                                    $championrankKDAminniom = 0.0093;
                                } else if ($tierData->tier == "DIAMOND") {
                                    $championrankMOD = '1.8';
                                    $championrankKDA = 0.9;
                                    $championrankKDAminniom = 0.0090;
                                } else if ($tierData->tier == "PLATINUM") {
                                    $championrankMOD = '1.7';
                                    $championrankKDA = 0.86;
                                    $championrankKDAminniom = 0.0087;
                                } else if ($tierData->tier == "GOLD") {
                                    $championrankMOD = '1.65';
                                    $championrankKDA = 0.82;
                                    $championrankKDAminniom = 0.0085;
                                } else if ($tierData->tier == "SILVER") {
                                    $championrankMOD = '1.55';
                                    $championrankKDA = 0.75;
                                    $championrankKDAminniom = 0.0083;
                                } else if ($tierData->tier == "BRONZE") {
                                    $championrankMOD = '1.45';
                                    $championrankKDA = 0.71;
                                    $championrankKDAminniom = 0.0080;
                                } else if ($tierData->tier == "UNRANKED") {
                                    $championrankMOD = '1.55';
                                    $championrankKDA = 0.75;
                                    $championrankKDAminniom = 0.0083;
                                }

                                $calculatediamondgrade = ((pow(number_format((float)$KDAsidechamps, 2, '.', ''), 1 / 2) * $championrankKDA) + (pow(number_format((float)$KDAMinniomsSide, 2, '.', ''), 1 / 20) * $championrankKDAminniom)) * pow((($champstotalSessionsWon + 0.5) / (($champstotalSessionsWon + 0.4) + ($champstotalSessionsLost + 0.3))), 1 / 1.1) * pow((($champstotalSessionsWon) + ($champstotalSessionsLost - 0.4)), 1 / 8) * $championrankMOD;

                                $calculatediamondgradeforamted = number_format((float)$calculatediamondgrade, 3, '.', '') * (1000);

                                echo $calculatediamondgrade . " + " . $calculatediamondgradeforamted . " + " . $summonerData->name . "<br>";

                                array_push($players, array(
                                    'champId' => $champData->id,
                                    'profileiconid' => $summonerData->profileIconId,
                                    'playerName' => $summonerData->name,
                                    'tier' => $tierData->tier,
                                    'division' => $tierEntry->division,
                                    'championPoints' => $calculatediamondgradeforamted,
                                    'gamesplayed' => $totalsessionsplayedwithachampion
                                ));
                                array_push($champsPoints, $calculatediamondgradeforamted);
                            }
                        }
                    }
                }
            }
        }

        rsort($champsPoints);

        usort($players, function ($a, $b) use ($champsPoints) {
            $pos_a = array_search($a['championPoints'], $champsPoints);
            $pos_b = array_search($b['championPoints'], $champsPoints);
            return $pos_a - $pos_b;
        });

        $championsPoints = array_values(array_unique($champsPoints));
        $playersByCP = array();

        foreach ($championsPoints as $champsPoint) {
            $sameCPs = array();
            foreach ($players as $player) {
                $sameCP = array();
                if ($player['championPoints'] == $champsPoint) {
                    switch ($player['tier']) {
                        case 'BRONZE':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'z5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'z4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'z3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'z2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'z1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Bronze';
                                    break;
                            }
                            break;
                        case 'SILVER':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'y5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'y4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'y3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'y2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'y1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Silver';
                                    break;
                            }
                            break;
                        case 'GOLD':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'x5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'x4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'x3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'x2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'x1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Gold';
                                    break;
                            }
                            break;
                        case 'PLATINUM':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'w5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'w4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'w3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'w2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'w1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Platinum';
                                    break;
                            }
                            break;
                        case 'DIAMOND':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'v5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'v4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'v3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'v2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'v1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Diamond';
                                    break;
                            }
                            break;
                        case 'MASTER':
                            $sameCP['tier'] = 'u';
                            break;
                        case 'CHALLENGER':
                            $sameCP['tier'] = 'u';
                            break;
                        default:
                            $sameCP['tier'] = 'Error Tier';
                            break;
                    }
                    $sameCP['player'] = $player;
                    array_push($sameCPs, $sameCP);
                }
            }
            sort($sameCPs);
            foreach ($sameCPs as $sameCP) {
                array_push($playersByCP, $sameCP['player']);
            }
        }

        foreach ($playersByCP as $position => $playerByCP) {
            $tableRow = serialize($playerByCP);

            if ($playerByCP['gamesplayed'] >= 10) {
                $sql2 = 'INSERT INTO top_list (position, table_row, sum_name, champ_id) VALUES (' . $position . ', \'' . $tableRow . '\', \'' . mb_strtolower(str_replace(' ', '', $playerByCP['playerName']), 'UTF-8') . '\', \'' . mb_strtolower(str_replace(' ', '', $playerByCP['champId']), 'UTF-8') . '\')';

                if ($conn->query($sql2)) {
                    echo 'Insert: ' . mb_strtolower(str_replace(' ', '', $playerByCP['playerName']), 'UTF-8') . '<br>';
                } else {
                    echo 'Failed: ' . $conn->error . '<br>';
                }
            }
        }
    }
}
?>
</code>```

答:
When editing the php.ini, make sure that it's the correct file you are editing.
Take a look here: How to know which php.ini is used?

Try setting the execution time explicitly in the server configuration file:

```<code>max_execution_time = 360
</code>```

The specific server configuration could be handling the defaults different from your local host.

Body:
I made a script that gets data from my database then uses that data for each player in my databse to calculate there skill level and other parameters that are added to a array. Then from that array all data is entered into a table in my database for toplist.

Now my problem is it works on localhost with 0 errors but when i run it on my server it seems to only run to:

echo $calculatediamondgrade." + ".$calculatediamondgradeforamted." + ".$summonerData->name."
";

I am trying to get it to work and I dont see any problem with in my coding as when, could someone take a look and let me think your thoughts.

<?php
set_time_limit(0);

require_once 'connect_db.php';

$emptyQuery = "TRUNCATE top_list;";
if ($conn->query($emptyQuery)) {

    $sql = "SELECT summoner_info, tier_info, ranked_champs_info FROM players_data";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {

        $players = array();
        $champsPoints = array();

        while ($row = $result->fetch_assoc()) {
            $summonerData = unserialize($row['summoner_info']);
            $tierData = unserialize($row['tier_info']);
            if ($tierData == NULL || !isset($tierData)) {
                $tierData = new stdClass();
                $tierData->tier = 'UNRANKED';
                $tierEntry = new stdClass();
                $tierEntry->division = '';
            } else {
                $tierData = $tierData[0];
                $tierEntry = $tierData->entries[0];
            }

            $ranked_champs_infoData = unserialize($row['ranked_champs_info']);

            if ($row['summoner_info'] !== "N;") {
                if ($row['ranked_champs_info'] !== "N;") {
                    foreach ($ranked_champs_infoData->champions as $champData) {
                        $champIDs = $champData->id;

                        if (!$champIDs == 0) {
                            $totalsessionsplayedwithachampion = $champData->stats->totalSessionsPlayed;

                            if ($totalsessionsplayedwithachampion >= 10) {

                                $champstotalSessionsWon = $champData->stats->totalSessionsWon;
                                $champstotalSessionsLost = $champData->stats->totalSessionsLost;

                                $getMiniomskillsNamelistside = $champData->stats->totalMinionKills;
                                $KDAMinniomsSide = $getMiniomskillsNamelistside / ($totalsessionsplayedwithachampion);

                                if (isset($champData->stats) && isset($champData->stats->totalChampionKills)) {
                                    /* Champion total kills */
                                    $champsdatazkillz = $champData->stats->totalChampionKills;
                                } else {
                                    $champsdatazkillz = 0;
                                }

                                if (isset($champData->stats) && isset($champData->stats->totalAssists)) {
                                    /* Champion total assists */
                                    $champsdatazassitsz = $champData->stats->totalAssists;
                                } else {
                                    $champsdatazassitsz = 0;
                                }

                                if (isset($champData->stats) && isset($champData->stats->totalDeathsPerSession)) {
                                    /* Champion total deaths */
                                    $champsdatazdeathz = $champData->stats->totalDeathsPerSession;
                                } else {
                                    $champsdatazdeathz = 0;
                                }

                                if ($champsdatazdeathz == 0) {
                                    $KDAsidechamps = ($champsdatazkillz + $champsdatazassitsz);
                                } else {
                                    $KDAsidechamps = ($champsdatazkillz + $champsdatazassitsz) / $champsdatazdeathz;
                                }

                                if ($tierData->tier == "CHALLENGER") {
                                    $championrankMOD = '1.9';
                                    $championrankKDA = 0.95;
                                    $championrankKDAminniom = 0.0095;
                                } else if ($tierData->tier == "MASTER") {
                                    $championrankMOD = '1.85';
                                    $championrankKDA = 0.93;
                                    $championrankKDAminniom = 0.0093;
                                } else if ($tierData->tier == "DIAMOND") {
                                    $championrankMOD = '1.8';
                                    $championrankKDA = 0.9;
                                    $championrankKDAminniom = 0.0090;
                                } else if ($tierData->tier == "PLATINUM") {
                                    $championrankMOD = '1.7';
                                    $championrankKDA = 0.86;
                                    $championrankKDAminniom = 0.0087;
                                } else if ($tierData->tier == "GOLD") {
                                    $championrankMOD = '1.65';
                                    $championrankKDA = 0.82;
                                    $championrankKDAminniom = 0.0085;
                                } else if ($tierData->tier == "SILVER") {
                                    $championrankMOD = '1.55';
                                    $championrankKDA = 0.75;
                                    $championrankKDAminniom = 0.0083;
                                } else if ($tierData->tier == "BRONZE") {
                                    $championrankMOD = '1.45';
                                    $championrankKDA = 0.71;
                                    $championrankKDAminniom = 0.0080;
                                } else if ($tierData->tier == "UNRANKED") {
                                    $championrankMOD = '1.55';
                                    $championrankKDA = 0.75;
                                    $championrankKDAminniom = 0.0083;
                                }

                                $calculatediamondgrade = ((pow(number_format((float)$KDAsidechamps, 2, '.', ''), 1 / 2) * $championrankKDA) + (pow(number_format((float)$KDAMinniomsSide, 2, '.', ''), 1 / 20) * $championrankKDAminniom)) * pow((($champstotalSessionsWon + 0.5) / (($champstotalSessionsWon + 0.4) + ($champstotalSessionsLost + 0.3))), 1 / 1.1) * pow((($champstotalSessionsWon) + ($champstotalSessionsLost - 0.4)), 1 / 8) * $championrankMOD;

                                $calculatediamondgradeforamted = number_format((float)$calculatediamondgrade, 3, '.', '') * (1000);

                                echo $calculatediamondgrade . " + " . $calculatediamondgradeforamted . " + " . $summonerData->name . "
";

                                array_push($players, array(
                                    'champId' => $champData->id,
                                    'profileiconid' => $summonerData->profileIconId,
                                    'playerName' => $summonerData->name,
                                    'tier' => $tierData->tier,
                                    'division' => $tierEntry->division,
                                    'championPoints' => $calculatediamondgradeforamted,
                                    'gamesplayed' => $totalsessionsplayedwithachampion
                                ));
                                array_push($champsPoints, $calculatediamondgradeforamted);
                            }
                        }
                    }
                }
            }
        }

        rsort($champsPoints);

        usort($players, function ($a, $b) use ($champsPoints) {
            $pos_a = array_search($a['championPoints'], $champsPoints);
            $pos_b = array_search($b['championPoints'], $champsPoints);
            return $pos_a - $pos_b;
        });

        $championsPoints = array_values(array_unique($champsPoints));
        $playersByCP = array();

        foreach ($championsPoints as $champsPoint) {
            $sameCPs = array();
            foreach ($players as $player) {
                $sameCP = array();
                if ($player['championPoints'] == $champsPoint) {
                    switch ($player['tier']) {
                        case 'BRONZE':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'z5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'z4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'z3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'z2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'z1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Bronze';
                                    break;
                            }
                            break;
                        case 'SILVER':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'y5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'y4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'y3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'y2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'y1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Silver';
                                    break;
                            }
                            break;
                        case 'GOLD':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'x5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'x4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'x3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'x2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'x1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Gold';
                                    break;
                            }
                            break;
                        case 'PLATINUM':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'w5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'w4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'w3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'w2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'w1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Platinum';
                                    break;
                            }
                            break;
                        case 'DIAMOND':
                            switch ($player['division']) {
                                case 'I':
                                    $sameCP['tier'] = 'v5';
                                    break;
                                case 'II':
                                    $sameCP['tier'] = 'v4';
                                    break;
                                case 'III':
                                    $sameCP['tier'] = 'v3';
                                    break;
                                case 'IV':
                                    $sameCP['tier'] = 'v2';
                                    break;
                                case 'V':
                                    $sameCP['tier'] = 'v1';
                                    break;
                                default:
                                    $sameCP['tier'] = 'Error Diamond';
                                    break;
                            }
                            break;
                        case 'MASTER':
                            $sameCP['tier'] = 'u';
                            break;
                        case 'CHALLENGER':
                            $sameCP['tier'] = 'u';
                            break;
                        default:
                            $sameCP['tier'] = 'Error Tier';
                            break;
                    }
                    $sameCP['player'] = $player;
                    array_push($sameCPs, $sameCP);
                }
            }
            sort($sameCPs);
            foreach ($sameCPs as $sameCP) {
                array_push($playersByCP, $sameCP['player']);
            }
        }

        foreach ($playersByCP as $position => $playerByCP) {
            $tableRow = serialize($playerByCP);

            if ($playerByCP['gamesplayed'] >= 10) {
                $sql2 = 'INSERT INTO top_list (position, table_row, sum_name, champ_id) VALUES (' . $position . ', \'' . $tableRow . '\', \'' . mb_strtolower(str_replace(' ', '', $playerByCP['playerName']), 'UTF-8') . '\', \'' . mb_strtolower(str_replace(' ', '', $playerByCP['champId']), 'UTF-8') . '\')';

                if ($conn->query($sql2)) {
                    echo 'Insert: ' . mb_strtolower(str_replace(' ', '', $playerByCP['playerName']), 'UTF-8') . '
';
                } else {
                    echo 'Failed: ' . $conn->error . '
';
                }
            }
        }
    }
}
?>

Body:
When editing the php.ini, make sure that it's the correct file you are editing.
Take a look here: How to know which php.ini is used?

Try setting the execution time explicitly in the server configuration file:

max_execution_time = 360

The specific server configuration could be handling the defaults different from your local host.


来源: stackexchange

问:
Restarting numbering within partition once value change
I'm struggling with quite simple (I think) topic, which I can not get to run.

An example data:

```<code>|ready_signal|timestamp          |
|4           |2017-03-17 17:58:25|
|4           |2017-03-17 17:58:24|
|4           |2017-03-17 17:58:23|
|0           |2017-03-17 17:58:22|
|0           |2017-03-17 17:58:21|
|0           |2017-03-17 17:58:19|
|4           |2017-03-17 17:58:18|
|4           |2017-03-17 17:58:15|
|0           |2017-03-17 17:58:10|
|0           |2017-03-17 17:58:09|
|0           |2017-03-17 17:58:04|
|4           |2017-03-17 17:58:03|
</code>```

Now what I'm trying to achieve is, to get maximal value of timestamp, within every ready_signal change.
So the result should look like:

```<code>|ready_signal|timestamp          |
|4           |2017-03-17 17:58:25|
|0           |2017-03-17 17:58:22|
|4           |2017-03-17 17:58:18|
|0           |2017-03-17 17:58:10|
|4           |2017-03-17 17:58:09|
</code>```

I was trying with partitioning function, with ROW_NUMBER etc. but without success. I can not partition over none of this columns. Partitioning over ready_signal, will return only two values (and with use of ORDER BY within partition).

I think, somebody definitely have had the same issue. Is like, I would need a single unique partition number, but every time ready_signal value will change.

Sorry, for not posting the example code.
This is what I was experimenting with:

```<code>SELECT ready,
    timestamp,
    ROW_NUMBER() OVER(PARTITION BY ready ORDER BY timestamp DESC) AS readyTime
FROM bubu
ORDER BY timestamp DESC
</code>```

I also tried to pick up some max values:

```<code>SELECT ready,
    timestamp,
    ROW_NUMBER() OVER(PARTITION BY ready ORDER BY timestamp DESC) AS readyTime
FROM bubu
ORDER BY timestamp DESC
</code>```

答:
This is close but suffers from the issue I have commented on the question - because the timestamps aren't unique, it's possible to get different result sets. In this case, I frequently get another 0 row for 2017-03-17 17:58:09 since it's conceivable that one of them occurred before the 4.

Anyhow, the way to write this is that you want to select the rows that either have no successor or where the successor has a different value for ready_state. Once you re-state the question like that, the code practically writes itself:

```<code>declare @t table (ready_signal int,timestamp datetime)
insert into @t(ready_signal,timestamp) values
(4,'2017-03-17T17:58:25'),
(4,'2017-03-17T17:58:24'),
(4,'2017-03-17T17:58:23'),
(0,'2017-03-17T17:58:22'),
(0,'2017-03-17T17:58:21'),
(0,'2017-03-17T17:58:19'),
(4,'2017-03-17T17:58:18'),
(4,'2017-03-17T17:58:15'),
(0,'2017-03-17T17:58:10'),
(0,'2017-03-17T17:58:09'),
(0,'2017-03-17T17:58:09'),
(4,'2017-03-17T17:58:09')

;With Numbered as (
    select ready_signal,timestamp,
        ROW_NUMBER() OVER (ORDER BY timestamp) as rn
    from @t
)
select
    t1.ready_signal,t1.timestamp
from
    Numbered t1
        left join
    Numbered t2
        on
            t1.rn = t2.rn - 1
where
    t2.rn is null or --No successor
    t2.ready_signal != t1.ready_signal --Successor different
</code>```

Results:

```<code>ready_signal timestamp
------------ -----------------------
0            2017-03-17 17:58:09.000
4            2017-03-17 17:58:09.000
0            2017-03-17 17:58:10.000
4            2017-03-17 17:58:18.000
0            2017-03-17 17:58:22.000
4            2017-03-17 17:58:25.000
</code>```

(You can add an explicit ORDER BY if the order of the result set is important to you)

ContentLicense: CC BY-SA 3.0

Body:
I'm struggling with quite simple (I think) topic, which I can not get to run.

An example data:

|ready_signal|timestamp          |
|4           |2017-03-17 17:58:25|
|4           |2017-03-17 17:58:24|
|4           |2017-03-17 17:58:23|
|0           |2017-03-17 17:58:22|
|0           |2017-03-17 17:58:21|
|0           |2017-03-17 17:58:19|
|4           |2017-03-17 17:58:18|
|4           |2017-03-17 17:58:15|
|0           |2017-03-17 17:58:10|
|0           |2017-03-17 17:58:09|
|0           |2017-03-17 17:58:04|
|4           |2017-03-17 17:58:03|

Now what I'm trying to achieve is, to get maximal value of timestamp, within every ready_signal change.
So the result should look like:

|ready_signal|timestamp          |
|4           |2017-03-17 17:58:25|
|0           |2017-03-17 17:58:22|
|4           |2017-03-17 17:58:18|
|0           |2017-03-17 17:58:10|
|4           |2017-03-17 17:58:09|

I was trying with partitioning function, with ROW_NUMBER etc. but without success. I can not partition over none of this columns. Partitioning over ready_signal, will return only two values (and with use of ORDER BY within partition).

I think, somebody definitely have had the same issue. Is like, I would need a single unique partition number, but every time ready_signal value will change.

Sorry, for not posting the example code.
This is what I was experimenting with:

SELECT ready,
    timestamp,
    ROW_NUMBER() OVER(PARTITION BY ready ORDER BY timestamp DESC) AS readyTime
FROM bubu
ORDER BY timestamp DESC

I also tried to pick up some max values:

SELECT ready,
    timestamp,
    ROW_NUMBER() OVER(PARTITION BY ready ORDER BY timestamp DESC) AS readyTime
FROM bubu
ORDER BY timestamp DESC

Body:
This is close but suffers from the issue I have commented on the question - because the timestamps aren't unique, it's possible to get different result sets. In this case, I frequently get another 0 row for 2017-03-17 17:58:09 since it's conceivable that one of them occurred before the 4.

Anyhow, the way to write this is that you want to select the rows that either have no successor or where the successor has a different value for ready_state. Once you re-state the question like that, the code practically writes itself:

declare @t table (ready_signal int,timestamp datetime)
insert into @t(ready_signal,timestamp) values
(4,'2017-03-17T17:58:25'),
(4,'2017-03-17T17:58:24'),
(4,'2017-03-17T17:58:23'),
(0,'2017-03-17T17:58:22'),
(0,'2017-03-17T17:58:21'),
(0,'2017-03-17T17:58:19'),
(4,'2017-03-17T17:58:18'),
(4,'2017-03-17T17:58:15'),
(0,'2017-03-17T17:58:10'),
(0,'2017-03-17T17:58:09'),
(0,'2017-03-17T17:58:09'),
(4,'2017-03-17T17:58:09')

;With Numbered as (
    select ready_signal,timestamp,
        ROW_NUMBER() OVER (ORDER BY timestamp) as rn
    from @t
)
select
    t1.ready_signal,t1.timestamp
from
    Numbered t1
        left join
    Numbered t2
        on
            t1.rn = t2.rn - 1
where
    t2.rn is null or --No successor
    t2.ready_signal != t1.ready_signal --Successor different

Results:

ready_signal timestamp
------------ -----------------------
0            2017-03-17 17:58:09.000
4            2017-03-17 17:58:09.000
0            2017-03-17 17:58:10.000
4            2017-03-17 17:58:18.000
0            2017-03-17 17:58:22.000
4            2017-03-17 17:58:25.000

(You can add an explicit ORDER BY if the order of the result set is important to you)


问:
How to implement Headless JS in react native android application?
I need implement Headless JS in my React Native Android Application, but I got following issue :

Here is My Code :

index.android.js :

```<code>import React, { Component } from 'react';
import {AppRegistry} from 'react-native';
import SomeTaskName from './SomeTaskName'
AppRegistry.registerComponent('SomeTaskName', () => SomeTaskName);
</code>```

SomeTaskName.js

```<code>module.exports = async (taskData) => {
   alert('test');
}
</code>```

MyTaskService.java

```<code>import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.HeadlessJsTaskService;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;
public class MyTaskService extends HeadlessJsTaskService {
   @Override
   protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
   Bundle extras = intent.getExtras();
     if (extras != null) {
        return new HeadlessJsTaskConfig(
          "MyTaskService",
          Arguments.fromBundle(extras),
         5000);
     }
     return null;
  }
}
</code>```

and add service in AndroidManifest.xml

```<code><service android:name=".MyTaskService" android:enabled="true" android:label="MyTaskService" />
</code>```

Please , Anyone help to fix this issue.

答:
You have to register a headless task. So replace the following code:

```<code>AppRegistry.registerComponent('SomeTaskName', () => SomeTaskName);
</code>```

with:

```<code>AppRegistry.registerHeadlessTask('SomeTaskName', () => SomeTaskName);
</code>```

And you need to call the task from your service, so replace:

```<code>if (extras != null) {
    return new HeadlessJsTaskConfig(
      "MyTaskService",
      Arguments.fromBundle(extras),
     5000);
 }
 return null;
</code>```

with:

```<code>// Following line just to be sure it does not silently fail
WritableMap data = extras != null ? Arguments.fromBundle(extras) : null;
return new HeadlessJsTaskConfig(
    "SomeTaskName", // Use the registered headless Task here
    data,
    5000);
</code>```

Body:
I need implement Headless JS in my React Native Android Application, but I got following issue :

Here is My Code :

index.android.js :

import React, { Component } from 'react';
import {AppRegistry} from 'react-native';
import SomeTaskName from './SomeTaskName'
AppRegistry.registerComponent('SomeTaskName', () => SomeTaskName);

SomeTaskName.js

module.exports = async (taskData) => {
   alert('test');
}

MyTaskService.java

import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.HeadlessJsTaskService;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;
public class MyTaskService extends HeadlessJsTaskService {
   @Override
   protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
   Bundle extras = intent.getExtras();
     if (extras != null) {
        return new HeadlessJsTaskConfig(
          "MyTaskService",
          Arguments.fromBundle(extras),
         5000);
     }
     return null;
  }
}

and add service in AndroidManifest.xml

<service android:name=".MyTaskService" android:enabled="true" android:label="MyTaskService" />

Please , Anyone help to fix this issue.

Body:
You have to register a headless task. So replace the following code:

AppRegistry.registerComponent('SomeTaskName', () => SomeTaskName);

with:

AppRegistry.registerHeadlessTask('SomeTaskName', () => SomeTaskName);

And you need to call the task from your service, so replace:

if (extras != null) {
    return new HeadlessJsTaskConfig(
      "MyTaskService",
      Arguments.fromBundle(extras),
     5000);
 }
 return null;

with:

// Following line just to be sure it does not silently fail
WritableMap data = extras != null ? Arguments.fromBundle(extras) : null;
return new HeadlessJsTaskConfig(
    "SomeTaskName", // Use the registered headless Task here
    data,
    5000);


问:
how to change csv file by condition in for loop using pandas in python?
this is the code that i'm using to do this, but i know that this is bad and it can be done in for loop:

```<code>df=pd.read_csv('file.csv',sep=',')
if "c[1]=2" in text:
 df.loc[df.id==1,'r']=254
 df.loc[df.id==1,'g']=0
 df.loc[df.id==1,'b']=0
else:
  if "c[2]=3" in text:
    df.loc[df.id==2,'r']=254
    df.loc[df.id==2,'g']=0
    df.loc[df.id==2,'b']=0
  else:
     if "c[3]=4" in text:
       df.loc[df.id==3,'r']=254
       df.loc[df.id==3,'g']=0
       df.loc[df.id==3,'b']=0
</code>```

....

until:

```<code>if "c[34]=35" in text:
  df.loc[df.id==34,'r']=254
  df.loc[df.id==34,'g']=0
  df.loc[df.id==34,'b']=0
else: #this is the final else
  df.r=0
  df.g=254
  df.r=0
df.to_csv("file.csv",index=False, sep=',')
</code>```

i can't do this if i have more and more indexes.
this is all about to change values in csv using python and with conditions.
can it be done in loop ?
thank you.

答:
For the 35 as maximum</p>

```<code>for i in range(1,35)
    if "c["+str(i)+"="+str(i+1) in text:
        df.loc[df.id==i+1,'r']=254
        df.loc[df.id==i+1,'g']=0
        df.loc[df.id==i+1,'b']=0
    else :
        df.r=0
        df.g=254
        df.r=0
</code>```

Body:
this is the code that i'm using to do this, but i know that this is bad and it can be done in for loop:

df=pd.read_csv('file.csv',sep=',')
if "c[1]=2" in text:
 df.loc[df.id==1,'r']=254
 df.loc[df.id==1,'g']=0
 df.loc[df.id==1,'b']=0
else:
  if "c[2]=3" in text:
    df.loc[df.id==2,'r']=254
    df.loc[df.id==2,'g']=0
    df.loc[df.id==2,'b']=0
  else:
     if "c[3]=4" in text:
       df.loc[df.id==3,'r']=254
       df.loc[df.id==3,'g']=0
       df.loc[df.id==3,'b']=0

....

until:

if "c[34]=35" in text:
  df.loc[df.id==34,'r']=254
  df.loc[df.id==34,'g']=0
  df.loc[df.id==34,'b']=0
else: #this is the final else
  df.r=0
  df.g=254
  df.r=0
df.to_csv("file.csv",index=False, sep=',')

i can't do this if i have more and more indexes.
this is all about to change values in csv using python and with conditions.
can it be done in loop ?
thank you.

Body:
For the 35 as maximum

for i in range(1,35)
    if "c["+str(i)+"="+str(i+1) in text:
        df.loc[df.id==i+1,'r']=254
        df.loc[df.id==i+1,'g']=0
        df.loc[df.id==i+1,'b']=0
    else :
        df.r=0
        df.g=254
        df.r=0


问:
scala reflection
I want to create a hashmap to store parameters names and their values. The parameters however are with different types. I could use HashMap[String, Any], but I wouldn't know which types they are later on.  Is there anyway I can recovery the type information? Or is there any better way to store  pair?</p>

答: If you don't have too many values, you may consider using a HList of Pairs or similar constructs.</p>

ContentLicense: CC BY-SA 2.5

Title: scala reflection


问:
Consuming/reading data from sharepoint url
I have a sharepoint URL whose endpoint is .aspx page after browsing it into web page returns me list of names but when I am using it in my code it returns me entire HTML which is bit tricky to parse that information.
Can anyone suggest good approach to solve this

Edit:

I found below code on google

```<code>import java.io.FileInputStream;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;

public class SharPointClient {

    public static void main(String[] args) {

        try{

        //Load Property
        Properties prop = new Properties();
        prop.load(new FileInputStream("config.properties"));

        //Get exchange service object
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

        String passWd = prop.getProperty("mailPwd");
        String sharePointUser = prop.getProperty("sharePointUser");

        String BaseUrl = "http://server/default.aspx";

        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());

        /*Credentials useJaasCredentials = new Credentials() {
            public String getPassword() { return null; }
            public String getUserPrincipal() { return null; }
        };

        httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(null, -1, null),
            useJaasCredentials
        );*/

        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,new NTCredentials(sharePointUser, passWd, "","mydomain"));

        HttpUriRequest request = new HttpGet(BaseUrl);
        request.addHeader("Accept", "application/json;odata=verbose");

        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        String results = EntityUtils.toString(entity);
        System.out.println(results);

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
</code>```

this returns me response as entire HTML of that response which very tricky to parse so I tried to go through JSoupe but  that also seems to useless for me.

答:
You need to use the sharepoint REST Service interface. I guess what you need is List interface implementation. Can you check if the page returns a list. Else you have to scrape the html page which is a pain.

http://server_name/_vti_bin/Lists.asmx shows up methods for working with lists and list data.

Check examples here and refer to this question.

Body:
I have a sharepoint URL whose endpoint is .aspx page after browsing it into web page returns me list of names but when I am using it in my code it returns me entire HTML which is bit tricky to parse that information.
Can anyone suggest good approach to solve this

Edit:

I found below code on google

import java.io.FileInputStream;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;

public class SharPointClient {

    public static void main(String[] args) {

        try{

        //Load Property
        Properties prop = new Properties();
        prop.load(new FileInputStream("config.properties"));

        //Get exchange service object
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

        String passWd = prop.getProperty("mailPwd");
        String sharePointUser = prop.getProperty("sharePointUser");

        String BaseUrl = "http://server/default.aspx";

        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());

        /*Credentials useJaasCredentials = new Credentials() {
            public String getPassword() { return null; }
            public String getUserPrincipal() { return null; }
        };

        httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(null, -1, null),
            useJaasCredentials
        );*/

        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,new NTCredentials(sharePointUser, passWd, "","mydomain"));

        HttpUriRequest request = new HttpGet(BaseUrl);
        request.addHeader("Accept", "application/json;odata=verbose");

        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        String results = EntityUtils.toString(entity);
        System.out.println(results);

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

this returns me response as entire HTML of that response which very tricky to parse so I tried to go through JSoupe but  that also seems to useless for me.


问:
A better way how to make Eclipse resistant to Java updates
It is a know problem, when you update Java, JDK or JRE, on Windows Eclipse will likely to fail to start as it points to outdated JDK/JRE folder. Fix is relatively simple, it was discussed and solved on several threads like here or here.

But I found those solutions unsatisfyingly inflexible. This solutions suggest to manually fix path in eclipse.ini to something like:

```<code>-vm C:\Program Files\Java\<jdk-version-just-installed>\bin\javaw.exe
</code>```

This means you have to do it after every update, again and again. If you update JDK frequently, and everyone should to have latest security patches, that makes it very annoying.

I expect that after a smart installation every Java program would just run out of box without any manual step involved; any solution less than that I would not consider satisfactory.

I can think of two ways:

using environmental (system) variable like JAVA_HOME. Can eclipse.ini reference environmental variables?

using symbolic link pointing to the latest JDK. And if you wonder, yes, Windows with NTFS support symlinks.

Both ways however need some cooperation from the installer, both JAVA_HOME or symlink as to be updated to the new value. Automatically of course, otherwise there would be no reason why to have them in the first place.
Please correct me if I am wrong, but JDK/JRE installation on linux does exactly that, provides and updates symlink to latest JDK/JRE. Why not Windows installer?

Is there a hidden parameter, option or a toggle in Java install tool doing that?

If not, is there a better, an alternative installation tool?

Can Eclipse launcher itself find a latest Java?

Is there a better eclipse.ini parameter for that?

答:
Older Windows JDK installers used to copy java.exe and javaw.exe (and also javavm.dll I think) in c:\windows\system32 to make them available in the default path.

In recent installers, a symbolic link is created for java.exe, javaw.exe and javaws.exe in C:\ProgramData\Oracle\Java\javapath. This means that these executables will point always to the most recent JDK update.

Body:
It is a know problem, when you update Java, JDK or JRE, on Windows Eclipse will likely to fail to start as it points to outdated JDK/JRE folder. Fix is relatively simple, it was discussed and solved on several threads like here or here.

But I found those solutions unsatisfyingly inflexible. This solutions suggest to manually fix path in eclipse.ini to something like:

-vm C:\Program Files\Java\<jdk-version-just-installed>\bin\javaw.exe

This means you have to do it after every update, again and again. If you update JDK frequently, and everyone should to have latest security patches, that makes it very annoying.

I expect that after a smart installation every Java program would just run out of box without any manual step involved; any solution less than that I would not consider satisfactory.

I can think of two ways:

using environmental (system) variable like JAVA_HOME. Can eclipse.ini reference environmental variables?

using symbolic link pointing to the latest JDK. And if you wonder, yes, Windows with NTFS support symlinks.

Both ways however need some cooperation from the installer, both JAVA_HOME or symlink as to be updated to the new value. Automatically of course, otherwise there would be no reason why to have them in the first place.
Please correct me if I am wrong, but JDK/JRE installation on linux does exactly that, provides and updates symlink to latest JDK/JRE. Why not Windows installer?

Is there a hidden parameter, option or a toggle in Java install tool doing that?

If not, is there a better, an alternative installation tool?

Can Eclipse launcher itself find a latest Java?

Is there a better eclipse.ini parameter for that?


问:
How to convert a html table obtained as a parameter on success of a Jquery $.get method
I have a Jquery $.get function which calls a controller which in turn returns a View containing a html table.

```<code> $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
 }
</code>```

This works fine and displays the table as intended. But i cant get this returned table to convert to a datatable using Jquery datatable() method as shown below.

```<code> $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
        $('#mytable').datatable();
 }
</code>```

I get an error Uncaught TypeError: $(...).datatable is not a function
Any way to get this working ? Also, i tried converting the table in the view itself and that didnt work either.

答: So i could solve this by adding the $("#mytable").datatable() in the view itself and in the Document.ready method. Still unsure why it didn't work in the success response function</p>

Body:
I have a Jquery $.get function which calls a controller which in turn returns a View containing a html table.

 $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
 }

This works fine and displays the table as intended. But i cant get this returned table to convert to a datatable using Jquery datatable() method as shown below.

 $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
        $('#mytable').datatable();
 }

I get an error Uncaught TypeError: $(...).datatable is not a function
Any way to get this working ? Also, i tried converting the table in the view itself and that didnt work either.


问:
Call function after function return
i have the folowing situation:
I have a function "foo" and want the the foo-return the function bar sould be call. Here a little example what i mean:

```<code>function foo() {
     echo "FOO";
     return "1";
}
function bar() {
    echo "BAR";
}
echo foo();
</code>```

And the output should be display this

FOO

  1

  BAR

All this in PHP!!!
Have anyone a idea how to can realise this WITHOUT call bar() in after each foo()?

答:
What you want isn't possible that way. What you actually ask for is, to automatically execute an statement, after you leave the function AND after you called echo.

Calling an statement after return is possible using finally, but it would be easier (and cleaner) to store the result of calling something else and return it later.

```<code>function b() {
    echo "bar";
    return 2;
}

function a() {
    try {
        echo "foo";
        return b();
    }
    finally {
        echo "finally";
    }
}

echo a();
</code>```

What you really should do, to get your result is just call bar, after you called foo.

```<code>echo foo();
bar();
</code>```

Title: Call function after function return

Body:
i have the folowing situation:
I have a function "foo" and want the the foo-return the function bar sould be call. Here a little example what i mean:

function foo() {
     echo "FOO";
     return "1";
}
function bar() {
    echo "BAR";
}
echo foo();

And the output should be display this

FOO

  1

  BAR

All this in PHP!!!
Have anyone a idea how to can realise this WITHOUT call bar() in after each foo()?

Body:
What you want isn't possible that way. What you actually ask for is, to automatically execute an statement, after you leave the function AND after you called echo.

Calling an statement after return is possible using finally, but it would be easier (and cleaner) to store the result of calling something else and return it later.

function b() {
    echo "bar";
    return 2;
}

function a() {
    try {
        echo "foo";
        return b();
    }
    finally {
        echo "finally";
    }
}

echo a();

What you really should do, to get your result is just call bar, after you called foo.

echo foo();
bar();


问:
Edit text cursor show bottom line
I have apply an style to my EditText to change bottom line when no selected, I do it like this:

```<code><style name="JoinMeetingEditText" parent="Widget.AppCompat.EditText">
    <item name="colorControlNormal">@color/edit_text_no_selected_color</item>
    <item name="android:textCursorDrawable">@null</item>
    <item name="android:theme">@style/JoinMeetingEditText</item>
</style>
</code>```

But the cursor in the EditText is displayed like this

If I remove <item name="android:theme">@style/JoinMeetingEditText</item> then that line is not displayed but my edit text doesn't display correct color when no selected

This is how I definde EditText in XMl

```<code> <android.support.design.widget.TextInputLayout
        style="@style/JoinMeetingTextInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/email"
            android:theme="@style/JoinMeetingEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            android:inputType="number"
            android:textColor="@color/white"
            android:textSize="16sp">

            <requestFocus />
        </EditText>
</code>```

答:
Change parent of your custom theme on global "AppTheme" like this:

parent="AppTheme"

or common theme, for example:

parent="Theme.AppCompat.Light.NoActionBar"

In your case custom theme is used as theme for all EditText child views (including cursor view). When you set AppTheme as parent, it overlap special attributes for cursor view over EditText attributes.

I hope this helps you.

Title: Edit text cursor show bottom line

Body:
I have apply an style to my EditText to change bottom line when no selected, I do it like this:

But the cursor in the EditText is displayed like this

If I remove <item name="android:theme">@style/JoinMeetingEditText</item> then that line is not displayed but my edit text doesn't display correct color when no selected

This is how I definde EditText in XMl

 <android.support.design.widget.TextInputLayout
        style="@style/JoinMeetingTextInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/email"
            android:theme="@style/JoinMeetingEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            android:inputType="number"
            android:textColor="@color/white"
            android:textSize="16sp">

            <requestFocus />
        </EditText>


问:
Compare smoothed signal to the input signal
I smooth a series of data points using the algorithm described here: http://www.scipy.org/Cookbook/SignalSmooth .

How could I compare the smoothed signal with the input signal afterward? I'm hoping I could get a scalar describing how "close" the output is from the input. Is there any standard way to do this? Some term I could look for?

I have no idea what to even look for. Thanks!

答: I used normalized root mean squared deviation. That gives me a number between 0 and 1. The bigger the number, the further away the two data series are. 0 means perfect match between the signal and the smoothed signal.</p>


问:
Segmentation fault when accessing array via pointer
I have a global array declared as

```<code>int Team1[12][8];
</code>```

When I call the function

```<code>int readLineupB(int teamNr){

      int (*teamToRead)[12][8];
      teamToRead = &Team1;

      for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
        for (int otherNumber = 1; otherNumber<7; otherNumber++) {
            *teamToRead[currentPlayersNumber][otherNumber] = 20;
        }
    }
    return 1;
}
</code>```

it fills the array until position [10],[3], then seemingly for [10],[4] I get a segmentation fault, and I cannot understand why.

答:
Check the data types.

teamToRead is a pointer to int [12][8] array.

Due to operator precedence, the subscript operator binds higher that the dereference.

So, in case of

```<code>  *teamToRead[currentPlayersNumber][otherNumber] = 20;
</code>```

you're trying to say something like

```<code>  *(* ( teamToRead + currentPlayersNumber ) ) [otherNumber] = 20;
</code>```

where, the pointer arithmetic becomes illegal as they honor the pointer type and thereby ventures out of bounds.

To solve that, you need to enforce the precedence of the dereference by explicit parentheses, like

```<code> (*teamToRead)[currentPlayersNumber][otherNumber] = 20;
</code>```

Body:
I have a global array declared as

int Team1[12][8];

When I call the function

int readLineupB(int teamNr){

      int (*teamToRead)[12][8];
      teamToRead = &Team1;

      for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
        for (int otherNumber = 1; otherNumber<7; otherNumber++) {
            *teamToRead[currentPlayersNumber][otherNumber] = 20;
        }
    }
    return 1;
}

it fills the array until position [10],[3], then seemingly for [10],[4] I get a segmentation fault, and I cannot understand why.

Body:
Check the data types.

teamToRead is a pointer to int [12][8] array.

Due to operator precedence, the subscript operator binds higher that the dereference.

So, in case of

  *teamToRead[currentPlayersNumber][otherNumber] = 20;

you're trying to say something like

  *(* ( teamToRead + currentPlayersNumber ) ) [otherNumber] = 20;

where, the pointer arithmetic becomes illegal as they honor the pointer type and thereby ventures out of bounds.

To solve that, you need to enforce the precedence of the dereference by explicit parentheses, like

 (*teamToRead)[currentPlayersNumber][otherNumber] = 20;


问:
Trying to change the content of a page without reloading after passing a value to a variable on submit
Retrieving data from an API using Php. This my code:

```<code><?php
if(isset($_POST['search']))
{
    $login = 'something';
    $password = 'something';
    $query = urlencode( $_POST[ "search"]);
    $url = 'something' . $query;;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
    $result = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($result, true);

    foreach ($output['response']['customers']['customer'] as $r)
        {
            $inner = $r['lifetime_points'];
        };
 }
  else
 {
      echo ("No search query has received");
 }
?>
</code>```

Html code:

```<code> <div id="get_text" >
<div><em>CHECK YOUR POINTS</em></div>
<div ><em>Enter mobile number</em></div>
<form action='' method='POST' id='search-form'>
<div>
<input type='search' name='search' id="sub1" />
</div>
<div>
<button type="submit"  id="sub" >Submit</button>
</div>
</form>
</div>

<div id="show_text" >
<div><em>YOUR CURRENT POINTS ARE </em></div>
<form action='' method='GET' id='result'>
<div>
<input type='text' name='points' value="<?php echo $inner; ?>"/>
</div>
</form>
</div>
</code>```

So through AJAX I'm initially displaying my div tag with ID=get_text in which I'm retrieving data from an API and storing it in a variable after pressing submit. After pressing submit I'm hiding the div tag with id=get_text and displaying the div tag with id=show_text.

```<code> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script type="text/javascript">
     $(document).ready(function () {
    $("#show_text").hide();
    $("#sub").on("click", function (e) {
        e.preventDefault();
        $.ajax({
            url: 'aristocracy-test.php',
            method: 'POST',
            data : $("#get_text").serialize(), //pass your form elements as key-value pairs
            success: function (response) {
                $("#show_text").show();
                $("#get_text").hide();
            }
        });
    });
});
 </script>
</code>```

The problem I'm facing is that the value is not getting passed to div tag with ID=show_text after pressing the submit button on hiding the div tag with id=get_text. There isn't anything wrong with my API code, as I have tested it before implementing AJAX.

答:
I think you forgot to set the response to the div after showing the div .
Please add $("#show_text").html(response); after showing the div.

If you want to show the result in textbox . Use

```<code>$('input[name="textboxname"]').val( response ) ;
</code>```

then your code will be like.

```<code>success: function (response) {
                $("#show_text").show();
                $('input[name="textboxname"]').val(response) ;
                $("#get_text").hide();
            }
</code>```

Body:
Retrieving data from an API using Php. This my code:

<?php
if(isset($_POST['search']))
{
    $login = 'something';
    $password = 'something';
    $query = urlencode( $_POST[ "search"]);
    $url = 'something' . $query;;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
    $result = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($result, true);

    foreach ($output['response']['customers']['customer'] as $r)
        {
            $inner = $r['lifetime_points'];
        };
 }
  else
 {
      echo ("No search query has received");
 }
?>

Html code:

CHECK YOUR POINTS

Enter mobile number

<form action='' method='POST' id='search-form'>

<input type='search' name='search' id="sub1" />

<button type="submit"  id="sub" >Submit</button>

</form>

YOUR CURRENT POINTS ARE

<form action='' method='GET' id='result'>

<input type='text' name='points' value="<?php echo $inner; ?>"/>

</form>

So through AJAX I'm initially displaying my div tag with ID=get_text in which I'm retrieving data from an API and storing it in a variable after pressing submit. After pressing submit I'm hiding the div tag with id=get_text and displaying the div tag with id=show_text.

The problem I'm facing is that the value is not getting passed to div tag with ID=show_text after pressing the submit button on hiding the div tag with id=get_text. There isn't anything wrong with my API code, as I have tested it before implementing AJAX.

Body:
I think you forgot to set the response to the div after showing the div .
Please add $("#show_text").html(response); after showing the div.

If you want to show the result in textbox . Use

$('input[name="textboxname"]').val( response ) ;

then your code will be like.

success: function (response) {
                $("#show_text").show();
                $('input[name="textboxname"]').val(response) ;
                $("#get_text").hide();
            }


问:
Why do C++17 structured bindings not use { }?
I found the original proposal for *C++ structured bindings here. It proposes a way to easily bind multiple return values, i.e.:

```<code>auto {a, b} = minmax(data);
</code>```

But now I see that everyone points to the C++17/C++1z proposal syntax of

```<code>auto [a, b] = minmax(data);
</code>```

Now that I learned "lists are written { like, this }" there comes a new list-syntax? Why? What is the problem with curly braces here?

答:
@SebastianWahl only commented with a link. I will quickly summarize the content behind the link.

Chandler Carruth's answer to this question: youtu.be/430o2HMODj4?t=15m50s

```<code>auto [a,b,c] = f();
</code>```

is ok with auto. But you can also do this:

```<code>tuple<int,float,string> [a,b,c] = f();
</code>```

So when you use {...} this would become

```<code>tuple<int,float,string> {a,b,c} = f();  //<<< not C++17
</code>```

which is bad, because the piece tuple<int,float,string> {a,b,c} also has a meaning in C++ and thus would be a difficult ambiguity, difficult to solve.

Body:
I found the original proposal for *C++ structured bindings here. It proposes a way to easily bind multiple return values, i.e.:

auto {a, b} = minmax(data);

But now I see that everyone points to the C++17/C++1z proposal syntax of

auto [a, b] = minmax(data);

Now that I learned "lists are written { like, this }" there comes a new list-syntax? Why? What is the problem with curly braces here?

Body:
@SebastianWahl only commented with a link. I will quickly summarize the content behind the link.

Chandler Carruth's answer to this question: youtu.be/430o2HMODj4?t=15m50s

auto [a,b,c] = f();

is ok with auto. But you can also do this:

tuple<int,float,string> [a,b,c] = f();

So when you use {...} this would become

tuple<int,float,string> {a,b,c} = f();  //<<< not C++17

which is bad, because the piece tuple<int,float,string> {a,b,c} also has a meaning in C++ and thus would be a difficult ambiguity, difficult to solve.


问:
Remove the last comma in a csv file linux
cdp_data.csv

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

So i'm making this csv processor. When i compile it on windows there is no "," at the end of the line inside the csv. However when i run this on the server there was an extra "," in the line. They have the same python version though.

```<code>#!/usr/bin/python
import re
import datetime

now = datetime.datetime.now()
day_minus_one = now + datetime.timedelta(days=-1)
new_date = day_minus_one.strftime('%Y%m%d')

f = open('/tmp/cdp_data.csv','rb')
fo = open('/tmp/cdp_out.csv','wb')

fo.writelines("{},".format(new_date))

for line in f:
    bits = line.split(',')
    bits[0] = re.sub(r'\n', ",", bits[0])
    bits[0] = re.sub(r'\r', "", bits[0])
    fo.write( ','.join(bits) )

f.close()
fo.close()
</code>```

Windows result:

```<code>20170329,1,2,3,4
</code>```

Linux Results:

```<code>20170329,1,2,3,4,
</code>```

答:
If you really want to hard-code CSV, use bits = line.strip().split(','). The strip() method removes trailing white spaces and will eliminate the empty string at the end of your list.

Otherwise, the recommended approach would be to use the csv module to handle all read, writing and parsing automatically.

```<code>import csv
with open('/tmp/cdp_data.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    with open('/tmp/cdp_out.csv', 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
        for row in spamreader:
            spamwriter.writerow(row)
</code>```

Body:
cdp_data.csv

1
2
3
4

So i'm making this csv processor. When i compile it on windows there is no "," at the end of the line inside the csv. However when i run this on the server there was an extra "," in the line. They have the same python version though.

#!/usr/bin/python
import re
import datetime

now = datetime.datetime.now()
day_minus_one = now + datetime.timedelta(days=-1)
new_date = day_minus_one.strftime('%Y%m%d')

f = open('/tmp/cdp_data.csv','rb')
fo = open('/tmp/cdp_out.csv','wb')

fo.writelines("{},".format(new_date))

for line in f:
    bits = line.split(',')
    bits[0] = re.sub(r'\n', ",", bits[0])
    bits[0] = re.sub(r'\r', "", bits[0])
    fo.write( ','.join(bits) )

f.close()
fo.close()

Windows result:

20170329,1,2,3,4

Linux Results:

20170329,1,2,3,4,

Body:
If you really want to hard-code CSV, use bits = line.strip().split(','). The strip() method removes trailing white spaces and will eliminate the empty string at the end of your list.

Otherwise, the recommended approach would be to use the csv module to handle all read, writing and parsing automatically.

import csv
with open('/tmp/cdp_data.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    with open('/tmp/cdp_out.csv', 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
        for row in spamreader:
            spamwriter.writerow(row)


问:
Passing Datetime from JSON to WCF POST
i have a class like this:

```<code>public class BudgetTransactionRequest
    {
        [DataMember]
        public string transaction_code { get; set; }
        [DataMember]
        public double? amount { get; set; }

        public DateTime request_date { get; set; }

        [DataMember(Name = "request_date")]
        public string req_date { get; set; }

        [OnSerializing]
        void OnSerializing(StreamingContext context)
        {
            this.req_date = this.request_date.ToString("MM/dd/yyyy h:mm tt", CultureInfo.InvariantCulture);
        }

        [OnDeserialized]
        void OnDeserialized(StreamingContext context)
        {
            DateTime value;
            if (DateTime.TryParseExact(this.req_date, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
            {
                this.request_date = value;
            }
        }
}
</code>```

Using fiddler, i tried to call this web service by sending JSON  like below:

```<code>{"transaction_code":"MCN34", "amount":2000.000,"request_date":"/Date(1235764800000)/"}
</code>```

But i got this following error:

```<code>{"ErrorDetails":"DateTime is less than minumum value supported by CrmDateTime. Actual value: 01\/01\/0001 00:00:00, Minimum value supported: 01\/01\/1753 00:00:00\"}
</code>```

What am i missing here ?

答:
i implemented a method with your class and its works just fine.
here is my method:

```<code>[OperationContract]
[WebInvoke(Method = "*", UriTemplate = @"/BudgetTransaction")]
[Description("use this method to add an Employee Account")]
BudgetTransactionRequest BudgetTransaction(BudgetTransactionRequest ws);
</code>```

my request with Fiddler:

```<code>POST localhost/BudgetTransaction HTTP/1.1
User-Agent: Fiddler
Content-Length: 86
Content-Type: application/json

{"transaction_code":"MCN34", "amount":2000.000,"request_date":"/Date(1235764800000)/"}
</code>```

response:

```<code>{"amount":2000,"req_date":"02\/27\/2009 8:00 PM","request_date":"\/Date(1235764800000)\/","transaction_code":"MCN34"}
</code>```

Title: Passing Datetime from JSON to WCF POST

Body:
i have a class like this:

public class BudgetTransactionRequest
    {
        [DataMember]
        public string transaction_code { get; set; }
        [DataMember]
        public double? amount { get; set; }

        public DateTime request_date { get; set; }

        [DataMember(Name = "request_date")]
        public string req_date { get; set; }

        [OnSerializing]
        void OnSerializing(StreamingContext context)
        {
            this.req_date = this.request_date.ToString("MM/dd/yyyy h:mm tt", CultureInfo.InvariantCulture);
        }

        [OnDeserialized]
        void OnDeserialized(StreamingContext context)
        {
            DateTime value;
            if (DateTime.TryParseExact(this.req_date, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
            {
                this.request_date = value;
            }
        }
}

Using fiddler, i tried to call this web service by sending JSON  like below:

{"transaction_code":"MCN34", "amount":2000.000,"request_date":"/Date(1235764800000)/"}

But i got this following error:

{"ErrorDetails":"DateTime is less than minumum value supported by CrmDateTime. Actual value: 01\/01\/0001 00:00:00, Minimum value supported: 01\/01\/1753 00:00:00\"}

What am i missing here ?

Body:
i implemented a method with your class and its works just fine.
here is my method:

[OperationContract]
[WebInvoke(Method = "*", UriTemplate = @"/BudgetTransaction")]
[Description("use this method to add an Employee Account")]
BudgetTransactionRequest BudgetTransaction(BudgetTransactionRequest ws);

my request with Fiddler:

POST localhost/BudgetTransaction HTTP/1.1
User-Agent: Fiddler
Content-Length: 86
Content-Type: application/json

{"transaction_code":"MCN34", "amount":2000.000,"request_date":"/Date(1235764800000)/"}

response:

{"amount":2000,"req_date":"02\/27\/2009 8:00 PM","request_date":"\/Date(1235764800000)\/","transaction_code":"MCN34"}


问:
CodeIgniter custom validation library function not working
I've created custom validation library class MY_Form_validation as MY_Form_validation.php in application/libraries as follows.

```<code><?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

    public function __construct($rules = array()) {
          parent::__construct($rules);
    }

    public function file_required($file) {

          if($file['size']===0) {
              $this->set_message('file_required', 'Uploading a file for %s is required.');
              return false;
          }

          return true;
    }
}

?>
</code>```

In my validation function I've included following rules as follows.

```<code>public function validate() {

    $this->load->library('form_validation');

    $config = array(
        array(
            'field' => 'name',
            'label' => 'Name',
            'rules' => 'trim|required|xss_clean'
        ),
        array(
            'field' => 'display_photo',
            'label' => 'Display Photo',
            'rules' => 'trim|good|file_required|xss_clean'
        ),
    );

    $this->form_validation->set_rules($config);

    if ($this->form_validation->run()) {
        return true;
    }
    return false;

}
</code>```

The core validation rules are working fine but custom rule is not working. So please help me to get the soultion and Its literally wasting my time. The work would be more appreciated.

答:
I had the same problem and found the cause while looking in CodeIgniter's source code. It seems the writers thought that if a field didn't have "required", then it would just skip all the rules and always return that the form has validated. See it for yourself from their code:

```<code>// If the field is blank, but NOT required, no further tests are necessary
if ( ! in_array('required', $rules) AND is_null($postdata))
</code>```

However, if you add "callback_" in front of your rule, you can still make it run, for the procedure, look here:
https://www.codeigniter.com/userguide2/libraries/form_validation.html#callbacks

Body:
I've created custom validation library class MY_Form_validation as MY_Form_validation.php in application/libraries as follows.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

    public function __construct($rules = array()) {
          parent::__construct($rules);
    }

    public function file_required($file) {

          if($file['size']===0) {
              $this->set_message('file_required', 'Uploading a file for %s is required.');
              return false;
          }

          return true;
    }
}

?>

In my validation function I've included following rules as follows.

public function validate() {

    $this->load->library('form_validation');

    $config = array(
        array(
            'field' => 'name',
            'label' => 'Name',
            'rules' => 'trim|required|xss_clean'
        ),
        array(
            'field' => 'display_photo',
            'label' => 'Display Photo',
            'rules' => 'trim|good|file_required|xss_clean'
        ),
    );

    $this->form_validation->set_rules($config);

    if ($this->form_validation->run()) {
        return true;
    }
    return false;

}

The core validation rules are working fine but custom rule is not working. So please help me to get the soultion and Its literally wasting my time. The work would be more appreciated.

Body:
I had the same problem and found the cause while looking in CodeIgniter's source code. It seems the writers thought that if a field didn't have "required", then it would just skip all the rules and always return that the form has validated. See it for yourself from their code:

// If the field is blank, but NOT required, no further tests are necessary
if ( ! in_array('required', $rules) AND is_null($postdata))

However, if you add "callback_" in front of your rule, you can still make it run, for the procedure, look here:
https://www.codeigniter.com/userguide2/libraries/form_validation.html#callbacks


问:
DataTables search on multiple columns
I'm trying to search my table on multiple columns at the same time.
Example

```<code>----------------------------
|  Col1  |  Col2  |  Col3  |
----------------------------
|  abcd  |  efgh  |   12   |
|  bcde  |  efgh  |   34   |
|  cdef  |  efgh  |   56   |
----------------------------
</code>```

I want to search "cd" in Col1 and "34" in Col3, so that the result would be

```<code>----------------------------
|  Col1  |  Col2  |  Col3  |
----------------------------
|  bcde  |  efgh  |   34   |
----------------------------
</code>```

I've added some input fields in my table's thead and when my custom event is triggered, Here is what I came up with:

```<code>$('#datatable_ajax thead').on( 'doneTyping', '.search-on-type', function(e){
    if ( $(this).val() ) {
        var colX = [];
        var values = [];
        $('#datatable_ajax thead .search-on-type').each(function(){
            if($(this).val() == "")
                return;
            var visIdx = $(this).closest('th').index();
            var idx = dTable.column.index( 'fromVisible', visIdx );
            colX.push(idx);
            values.push($(this).val());
        });
        if( colX.length == 3){
            dTable.clearPipeline().columns( colX[0] ).search( values[0] ).columns( colX[1] ).search( values[1] ).columns( colX[2] ).search( values[2] ).draw();
        } else if ( colX.length == 2){
            dTable.clearPipeline().columns( colX[0] ).search( values[0] ).columns( colX[1] ).search( values[1] ).draw();
        } else {
            dTable.clearPipeline().columns( colX[0] ).search( values[0] ).draw();
        }
    }
});
</code>```

this code is working as expected.

But as you can see, the if-elseif-else is quite a bad solution, since I could have more than 3 fields which I want to search together, but I don't want to manually add an elseif each time I add a new searchable column.

I tried to find a better solution but I only found solutions for searching multiple columns with the same value, which is not what I need.

I noticed that .columns() accept an array as arguments, but .search() doesn't.. ( or at least, it does accept arrays, but they are transformed into comma separated string, which will be searched on the selected columns)

Is there any workaround for this?

答:
One thing you could do, is  fill up your values array with a regex pattern like (.*?) (that matches anything) for all columns for which no search filter has been defined.

This would allow you to reduce your if-elseif-else to a single statement :

```<code>$('#datatable_ajax thead').on( 'doneTyping', '.search-on-type', function(e) {
    if ($(this).val()) {
        var colX = [], values = [], filter;

        $('#datatable_ajax thead .search-on-type').each(function() {
            filter = $(this).val();
            if(filter == "") {
                values.push("(.*?)"); // Regex that matches anything
            } else {
                values.push(filter);
            }
            colX.push(dTable.column.index( 'fromVisible', $(this).closest('th').index() ));
        });

        dTable.clearPipeline().columns( colX[0] ).search( values[0], true, false )
                              .columns( colX[1] ).search( values[1], true, false )
                              .columns( colX[2] ).search( values[2], true, false )
                              .draw();
    }
});
</code>```

Title: DataTables search on multiple columns

Body:
I'm trying to search my table on multiple columns at the same time.
Example

----------------------------
|  Col1  |  Col2  |  Col3  |
----------------------------
|  abcd  |  efgh  |   12   |
|  bcde  |  efgh  |   34   |
|  cdef  |  efgh  |   56   |
----------------------------

I want to search "cd" in Col1 and "34" in Col3, so that the result would be

----------------------------
|  Col1  |  Col2  |  Col3  |
----------------------------
|  bcde  |  efgh  |   34   |
----------------------------

I've added some input fields in my table's thead and when my custom event is triggered, Here is what I came up with:

$('#datatable_ajax thead').on( 'doneTyping', '.search-on-type', function(e){
    if ( $(this).val() ) {
        var colX = [];
        var values = [];
        $('#datatable_ajax thead .search-on-type').each(function(){
            if($(this).val() == "")
                return;
            var visIdx = $(this).closest('th').index();
            var idx = dTable.column.index( 'fromVisible', visIdx );
            colX.push(idx);
            values.push($(this).val());
        });
        if( colX.length == 3){
            dTable.clearPipeline().columns( colX[0] ).search( values[0] ).columns( colX[1] ).search( values[1] ).columns( colX[2] ).search( values[2] ).draw();
        } else if ( colX.length == 2){
            dTable.clearPipeline().columns( colX[0] ).search( values[0] ).columns( colX[1] ).search( values[1] ).draw();
        } else {
            dTable.clearPipeline().columns( colX[0] ).search( values[0] ).draw();
        }
    }
});

this code is working as expected.

But as you can see, the if-elseif-else is quite a bad solution, since I could have more than 3 fields which I want to search together, but I don't want to manually add an elseif each time I add a new searchable column.

I tried to find a better solution but I only found solutions for searching multiple columns with the same value, which is not what I need.

I noticed that .columns() accept an array as arguments, but .search() doesn't.. ( or at least, it does accept arrays, but they are transformed into comma separated string, which will be searched on the selected columns)

Is there any workaround for this?

Body:
One thing you could do, is  fill up your values array with a regex pattern like (.*?) (that matches anything) for all columns for which no search filter has been defined.

This would allow you to reduce your if-elseif-else to a single statement :

$('#datatable_ajax thead').on( 'doneTyping', '.search-on-type', function(e) {
    if ($(this).val()) {
        var colX = [], values = [], filter;

        $('#datatable_ajax thead .search-on-type').each(function() {
            filter = $(this).val();
            if(filter == "") {
                values.push("(.*?)"); // Regex that matches anything
            } else {
                values.push(filter);
            }
            colX.push(dTable.column.index( 'fromVisible', $(this).closest('th').index() ));
        });

        dTable.clearPipeline().columns( colX[0] ).search( values[0], true, false )
                              .columns( colX[1] ).search( values[1], true, false )
                              .columns( colX[2] ).search( values[2], true, false )
                              .draw();
    }
});


问:
Inserting dates within an array with PHP
I am getting the starting and ending dates from a form.

I need to put within an array all the date between the former two, including themselves.

I'm using a normal for loop and, at the same time, printing the result, to verify.

Everything appear to be alright.

But when I print_r the very array, I get only a series of equal dates. Which are all the same: last date + 1.

This is the code:

```<code>$date1 = date_create("2013-03-15");
$date2 = date_create("2013-03-22");
$diff  = date_diff($date1, $date2);
echo $diff->format("%R%a days");
$diffDays = $diff->days;
echo $diffDays;

$dates = array();

$addDay = $date1;

for ($i = 0; $i < $diffDays; $i++) {
    $dates[$i] = $addDay;
    date_add($addDay, date_interval_create_from_date_string("1 day"));
    echo "array: " . $i . " : " . date_format($dates[$i], 'Y-m-d');
}

print_r($dates);
</code>```

答:
PHP code demo</p>

```<code><?php

$dates = array();
$datetime1 = new DateTime("2013-03-15");
$datetime2 = new DateTime("2013-03-22");
$interval = $datetime1->diff($datetime2);
$days = (int) $interval->format('%R%a');
$currentTimestamp = $datetime1->getTimestamp();
$dates[] = date("Y-m-d H:i:s", $currentTimestamp);
for ($x = 0; $x < $days; $x++)
{
    $currentTimestamp = strtotime("+1 day", $currentTimestamp);
    $dates[] = date("Y-m-d H:i:s", $currentTimestamp);
}
print_r($dates);
</code>```

Body:
I am getting the starting and ending dates from a form.

I need to put within an array all the date between the former two, including themselves.

I'm using a normal for loop and, at the same time, printing the result, to verify.

Everything appear to be alright.

But when I print_r the very array, I get only a series of equal dates. Which are all the same: last date + 1.

This is the code:

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-03-22");
$diff  = date_diff($date1, $date2);
echo $diff->format("%R%a days");
$diffDays = $diff->days;
echo $diffDays;

$dates = array();

$addDay = $date1;

for ($i = 0; $i < $diffDays; $i++) {
    $dates[$i] = $addDay;
    date_add($addDay, date_interval_create_from_date_string("1 day"));
    echo "array: " . $i . " : " . date_format($dates[$i], 'Y-m-d');
}

print_r($dates);

Body:
PHP code demo

<?php

$dates = array();
$datetime1 = new DateTime("2013-03-15");
$datetime2 = new DateTime("2013-03-22");
$interval = $datetime1->diff($datetime2);
$days = (int) $interval->format('%R%a');
$currentTimestamp = $datetime1->getTimestamp();
$dates[] = date("Y-m-d H:i:s", $currentTimestamp);
for ($x = 0; $x < $days; $x++)
{
    $currentTimestamp = strtotime("+1 day", $currentTimestamp);
    $dates[] = date("Y-m-d H:i:s", $currentTimestamp);
}
print_r($dates);


问:
error while running python command on ubuntu terminal
bash: /home/asif/anaconda/bin/python: No such file or directory

i am getting this error while running python command on ubuntu terminal

答:
try the following command:</p>

```<code>sudo ln -s /usr/bin/python2.7 /home/asif/anaconda/bin/python
</code>```

Body:
try the following command:

sudo ln -s /usr/bin/python2.7 /home/asif/anaconda/bin/python


问:
one line layout lambda if statement
I have a certain piece of code that looks pretty ugly, and I'm wondering if there is a prettier way of doing this.

This is what my normal "pretty" one line lambda's look like:

```<code>Boolean settingsChanged = key.pollEvents().stream()
        .filter(e -> e.kind() == ENTRY_MODIFY) // Negate OVERFLOW
        .anyMatch(e -> ((Path) e.context()).toAbsolutePath().equals(path));
</code>```

But then I have this ugly line:

```<code>if (settingsChanged)
    read().setHandler(arRead -> { if (arRead.succeeded()) handler.handle(arRead.result()); });
</code>```

I tried writing this as follows:

```<code>read().setHandler(arRead -> if (arRead.succeeded()) handler.handle(arRead.result()));
</code>```

But the compiler doesn't like this. Is there any way to pretty the code up?

答:
Are you asking for suggestions to format the code?

I know that you asked for one line layout. But this often decreases readability of your code. Most companies prefer readability over "one line wonder"

```<code>//This doesnt look that bad?
if (settingsChanged){
    read().setHandler(arRead -> {
        if (arRead.succeeded()) handler.handle(arRead.result());
    });
}
</code>```

Title: one line layout lambda if statement

Body:
I have a certain piece of code that looks pretty ugly, and I'm wondering if there is a prettier way of doing this.

This is what my normal "pretty" one line lambda's look like:

Boolean settingsChanged = key.pollEvents().stream()
        .filter(e -> e.kind() == ENTRY_MODIFY) // Negate OVERFLOW
        .anyMatch(e -> ((Path) e.context()).toAbsolutePath().equals(path));

But then I have this ugly line:

if (settingsChanged)
    read().setHandler(arRead -> { if (arRead.succeeded()) handler.handle(arRead.result()); });

I tried writing this as follows:

read().setHandler(arRead -> if (arRead.succeeded()) handler.handle(arRead.result()));

But the compiler doesn't like this. Is there any way to pretty the code up?

Body:
Are you asking for suggestions to format the code?

I know that you asked for one line layout. But this often decreases readability of your code. Most companies prefer readability over "one line wonder"

//This doesnt look that bad?
if (settingsChanged){
    read().setHandler(arRead -> {
        if (arRead.succeeded()) handler.handle(arRead.result());
    });
}