text:
Q: How can I constrain a table cell (td) height based on a neighbouring cell height? I'm using XSL to generate a report based on an XML flowchart, resulting in a large HTML table from the data showing the following columns:

*

*a node's name

*a list of information about that node

*its preceding neighbours

*its following neighbours and

*every route through the flowchart that involves the given node

Thus I have a large table with five columns, the first four cells in a row are important and I need to show all of the data in each of these cells, but the final cell can be huge (usually hundreds of lines) and is less important so I want to constrain its size and set its max-height to be that of the highest other cell in the row (usually less than 10 lines, but occasionally a hundred or so).
I can use the max-height property of a DIV inside the final cell to constrain this to a fixed pixel height, but this leaves gaps if other cells in the row are higher than the Max-Height that I've set, and also I'd really like the row to shrink down to the height of the other cells if their height is less than the height of the final cell.
I'd like to do this as static HTML using CSS to size the cell - I realise that this could be done using JS, I'd rather avoid that if possible (it's a big table), but could swap over to using DIVs all round if that makes this easier.  I'm using Firefox 4 - cross-browser support is not terribly important.
tl;dr; - Want to constrain the last TD in a TR to be the size of its neighbours regardless of its content.
Code is as follows.

Flowchart Report

        NODE	INFO	Preceding Nodes	Following Nodes	Usage

            N100

            Text

            Some more text

            Even more text

            Blah Blah Blah

            Much more text

            Still more text

            I can't believe it's more text

            N12

            N14

            N16

            N17

            N18

            N10

            N1

            N27

            N28

            N20

            N2

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n14 - n10 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n14 - n10 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n11 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n11 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n11 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n12

            N100

            Text

            Some more text

            N12

            N14

            N27

            N28

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n14 - n10 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n14 - n10 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n11 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n11 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n11 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n12

A: try this,

Flowchart Report

        NODE	INFO	Preceding Nodes	Following Nodes	Usage

            N100

            Text

            Some more text

            Even more text

            Blah Blah Blah

            Blah Blah Blah

            Blah Blah Blah

            Blah Blah Blah

            Blah Blah Blah

            Blah Blah Blah

            Blah Blah Blah

            Blah Blah Blah

            Much more text

            Still more text

            I can't believe it's more text

            N12

            N14

            N16

            N17

            N18

            N10

            N1

            N27

            N28

            N20

            N2

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n14 - n10 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n14 - n10 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n11 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n11 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n11 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n12

            N100

            Text

            Some more text

            N12

            N14

            N27

            N28

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n14 - n10 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n14 - n10 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n11 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n11 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n13

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n10 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n11 - n12

                n54 - n35 - n62 - n3 - n8 - n9 - n67 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n14 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n14 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n10 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n11 - n12

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n11 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n13

                n54 - n28 - n62 - n3 - n8 - n9 - n15 - n12


text:
Q: header() is not redirecting to the page in PHP I have the following PHP printExam.php page:
    <?php
    $logins = array(
        'user' => 'pass',
        'user1' => 'pass1',
        'user2' => 'pass2',
        'user3' => 'pass3',
        'user4' => 'pass4'
    );

    // Clean up the input values
    foreach($_POST as $key => $value) {
        $_POST[$key] = stripslashes($_POST[$key]);

        $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
    }

    /******************************************************************************/
       if (isset($_POST['submit'])){

          $user = isset($_POST['user']) ? strtolower($_POST['user']) : '';
          $pass = isset($_POST['pass']) ? $_POST['pass'] : '';
          $report = $_POST['typereport'];

          if ((!array_key_exists($user, $logins))||($logins[$user] != $pass)) {
             showForm("Wrong Username/Password");
             exit();
          }
          else {
    if ($report == "Clinical") {
?>

CLINICAL PAGE

<?php
    }
    elseif ($report == "Annual Education") {
?>

ANNUAL EDUCATION PAGE

<?php
    }
          }
       } else {
          showForm();
          exit();
       }

    function showForm($error=""){
    ?>
    <!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    <title>Certificate Printing :: Login</title>

    <form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="pwd">

Log In

        <fieldset id="inputs">
            <input id="user" name="user" placeholder="Username" autofocus="" required="" type="text">
            <input id="pass" name="pass" placeholder="Password" required="" type="password">
        </fieldset>
        <fieldset id="actions">
            <input type="radio" name="typereport" id="cbox" value="Clinical" checked="yes" /> Clinical
            <input type="radio" name="typereport" id="cbox" value="Annual Education" /> Annual Education
        </fieldset>
        <fieldset id="actions">
            <input id="submit" name="submit" value="Log in" type="submit">
        </fieldset>

<?php echo $error; ?>

    </form>

    <?php
    }
    ?>

For printCert.php and printCertHR.php, the very first line is:
<?php require_once('printExam.php'); ?>

What it is suppose to do is call the printExam.php page each time the user visits either pages. If the username AND password matches and depending on the selection, whether it's clinical or annual education, it should take the user to the correct page. I know the form is working correctly, because if I enter wrong username/password it shows me the error but once correct, it doesnt redirect. Any idea how to resolve it?
Please Note: the username/password is simplified for the example only!

A: The 'Location' header command in PHP should be followed with an exit;
Otherwise the code below is executed, ie any output is sent to the browser.
See the examples from the PHP header page:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;

A: Location (or any other header) needs to be the first thing echoed by your script. Remove the blank lines in your script.

A: You have contents being displayed before the header is being called (as for your comment to Rob W). The way to get around it is, put ob_start(); at the top of your php code, and ob_end_flush(); at the end of your code so the header can be called anywhere in between your code.

A: After your elseif ($report == "Annual Education") { block, try print_r($report) - ensure it's what you are expecting...
if ($report == "Clinical") {
    header ("Location: printCert.php");
}
elseif ($report == "Annual Education") {
    header ("Location: printCertHR.php");
}
print_r($report);

Also, try monitoring FireBug's NET tab (or CHROME's)

A: Is it possible that you might need to use PHP's Output Buffer to fix that? When the script is parsed, having the output of the form in a function might be throwing it off, as the function will be parsed before the rest of the script is run.
Also, you should use strcmp for comparing strings, not the == sign. strcmp vs ==
Try using the output buffer functions and see if that fixes it. it's gonna look something like this:
function showForm($error=""){
ob_start(); ?>
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Certificate Printing :: Login</title>

<form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="pwd">

Log In

    <fieldset id="inputs">
        <input id="user" name="user" placeholder="Username" autofocus="" required="" type="text">
        <input id="pass" name="pass" placeholder="Password" required="" type="password">
    </fieldset>
    <fieldset id="actions">
        <input type="radio" name="typereport" id="cbox" value="Clinical" checked="yes" /> Clinical
        <input type="radio" name="typereport" id="cbox" value="Annual Education" /> Annual Education
    </fieldset>
    <fieldset id="actions">
        <input id="submit" name="submit" value="Log in" type="submit">
    </fieldset>

<?php echo $error; ?>

</form>

<?php
return ob_get_flush();
}

Output Buffers (php.net)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace nulls in a merge and add I have two Dataframes,
DF1
+----+-------+------+------+
|id  | pnl   |value2|value3|
+----+-------+------+------+
|  1 |10     |20    |30    |
|  2 |20     |30    |40    |
|  3 |30     |40    |50    |
+----+-------+------+------+

DF2
+----+-------+------+------+
|id  | pnl   |value2|value3|
+----+-------+------+------+
|  1 |100    |200   |300   |
|  2 |200    |300   |400   |
|  3 |300    |400   |500   |
+----+-------+------+------+

I am trying to merge these two dataframes by id and add the value columns together. So get something like this.
+----+-------+------+------+
|id  | pnl   |value2|value3|
+----+-------+------+------+
|  1 |100+10 |200+20|300+30|
|  2 |200+20 |300+30|400+40|
|  3 |300+30 |400+40|500+50|
+----+-------+------+------+

This works fine when I use
// extract the names of the columns to sum
val cols = df1.columns.filter(_!="id")

// join and sum
val result = df1
    .join(df2,Seq("id"), "full_outer")
    .select( col("id") +: cols.map(c=>df1(c)+df2(c) as c) : _*)

But when one id is missing in one of the dataframes. For example
DF1
+----+-------+------+------+
|id  | pnl   |value2|value3|
+----+-------+------+------+
|  1 |10     |20    |30    |
|  2 |20     |30    |40    |
|  3 |30     |40    |50    |
|  4 |40     |40    |40
+----+-------+------+------+

DF2
+----+-------+------+------+
|id  | pnl   |value2|value3|
+----+-------+------+------+
|  1 |100    |200   |300   |
|  2 |200    |300   |400   |
|  3 |300    |400   |500   |
+----+-------+------+------+

I get following values after I merge using the operation I mentioned above.
+----+-------+------+------+
|id  | pnl   |value2|value3|
+----+-------+------+------+
|  1 |100+10 |200+20|300+30|
|  2 |200+20 |300+30|400+40|
|  3 |300+30 |400+40|500+50|
|  4 |null   |null  |null  |
+----+-------+------+------+

I understand that I am getting this because I don't have that id in df2. So one way I thought of solving this is by using .na.fill(0.0) after the merge
// join and sum
val result = df1
    .join(df2,Seq("id"), "full_outer").na.fill(0.0)
    .select( col("id") +: cols.map(c=>df1(c)+df2(c) as c) : _*)

But spark doesn't seem to like that and I get the following error.
org.apache.spark.sql.AnalysisException: Reference 'pnl' is ambiguous, could be: pnl, pnl.;
Anyone know a workaround for this? Thanks

A: You could use cols.map(c => coalesce(df1(c), lit(0)) + coalesce(df2(c), lit(0)) as c)


text:
Q: Setting platform specific icons in Ionic Okay, so this might be either a really simple question and I'll come away feeling sheepish but I've just gotten started using Ionic and I'm just playing around with detailing the UI with icons.
My question is whether or not you can set the icons in an element and have them render differently depending on which platform you build for?
For example, I had a menu item like so
<ion-content scroll="false">

Login

</ion-content>

In Ionicons, there is a ion-locked icon for both android (ion-android-locked) and ios (ion-ios-locked)and I was wondering if there is a way to set icons to match their platform during the build process?
It may just be that I end up having seperate branches in git for this, but I'd rather not if there is a simple way to implement this?

A: Since Ionic Framework is built on Apache Cordova you can make use of the Apache Cordova Device plugin which ships standard with new projects:
https://github.com/apache/cordova-plugin-device/blob/master/doc/index.md
You can then do something like this:
yourApp.controller("ExampleController", function($scope) {
   $scope.devicePlatform = device.platform;
});

Then in your HTML you can reference the controller and show the icon based on the platform:

Notice the ng-if.  Depending on what the $scope.devicePlatform is will decide which of the  tags will show.
Regards,

A: Alternatively to Nic Robody's approch you can use ng-class:
app.controller("appCtrl", function($scope) {
    $scope.devicePlatform = device.platform;
});

HTML (using ng-class):

A: You could customize you scss file.
Take a look you platform assets, index.html has a class
class="platform-android platform-cordova   platform-webview"
//default
.your-search{
  @extend .ion-android-search;
}
.platform-android {
  .your-search{
    @extend .ion-android-search;
  }
}

.platform-ios {
  .your-search {
    @extend .ion-ios7-search;
  }
}

A: You could use a cordova CLI hook that replaces certain placeholders with the actual platform or a platform specific value. A prepare hook for example would be called every time you build. Like the "platform add to body" hook that is generated by yeoman for a cordova project. The hook is part of the project, so it's under your control.
Here is a nice overview concerning cordova build hooks: http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/

A: A better solution is to use the ionic.Platform.platform() method to get device platform below:
In your controller:
angular.module('App', ['ionic'])
.app.controller("appCtrl", function($scope) {
    $scope.devicePlatform = ionic.Platform.platform();
});

In your html:
 Back

A: Note to future Ionic 2 users who run across this question: As of Ionic 2 RC2, the simplest way to accomplish this is with the "ios" and "md" attributes for the ion-icon tag. Here's an example with different icons for iOS and Android ("md" AKA Material Design):
<ion-icon ios="ios-outline-lock" md="md-lock"></ios-icon>

A: For what it's worth almost 3 years later. Just make your own version of the v2 directive.
function icon() {
  return {
    restrict: 'A',
    scope: {},
    compile: function(element, attrs) {
      //change here for specific device default
      var platform = ionic.Platform.platform() || 'ios';
      var iconClass = (platform === 'ios') ? attrs.ios : attrs.droid;
      element[0].classList.add(iconClass);
    }
  };
}

angular
  .module('common.directives')
  .directive('icon', icon);


text:
Q: AWX file copy cannot find local files and files copied to local don't exist A playbook that ran perfectly on earlier versions of Awx now fails after we've upgraded AWX to 4.0.0 (with Ansible 2.8.1) in that "Copy" cannot find any local files.
When copying a file to a remote server using Copy, Ansible complains it cannot find that file. I have tried various locations, including within the virtualenv dirs such as /var/opt/rh/rh-python36/ and /opt/rh/rh-python36/root/tmp/  (rh-python36 is the env selected for this playbook, others fail much earlier)
As an experiment, I created a uniquely named file on the remote server and used remote_src to copy that file to the AWX host. AWX succeeded in doing this and completed the playbook. "Great", I thought, and then searched for the file (using mlocate: updatedb && locate testfile) as well as find /|grep testfile - and that file simply does not exist.
It's like AWX is creating a temporary file structure for the session of this playbook and them removing it, which seems to make Copy a difficult thing to use in either direction.
Can someone please shed some light?

- hosts: "all"
  become: true

- name: Copy a test file
  hosts: "all"
  tasks:
  - name: copy a test file
    copy:
      src: /tmp/testfile
      dest: /tmp/testfile
      owner: root
      group: root
      mode: '0644'

Traceback (most recent call last):
  File "/opt/rh/rh-python36/root/lib/python3.6/site-packages/ansible/plugins/action/copy.py", line 464, in run
    source = self._find_needle('files', source)
  File "/opt/rh/rh-python36/root/lib/python3.6/site-packages/ansible/plugins/action/init.py", line 1166, in _find_needle
    return self._loader.path_dwim_relative_stack(path_stack, dirname, needle)
  File "/opt/rh/rh-python36/root/lib/python3.6/site-packages/ansible/parsing/dataloader.py", line 319, in path_dwim_relative_stack
    raise AnsibleFileNotFound(file_name=source, paths=[to_text(p) for p in search])
ansible.errors.AnsibleFileNotFound: Could not find or access '/tmp/testfile' on the Ansible Controller.
If you are using a module and expect the file to exist on the remote, see the remote_src option

A: Before running the playbook, Ansible AWX makes a copy of the files from the project path to the path  /tmp path. If your project is large, it can cause a delay when starting the job.
If your playbook uses absolute paths, problems can also occur, as the job will actually run the playbook from /tmp.
Run any playbook and check the awx_task container, the path /tmp will temporarily receive a copy of your project files

A: Ah. After many hours of fighting it, I have a solution, but it doesn't feel like the right one.
I tried removing the leading / from the src, making it "tmp/testfile" and re-ran the playbook.
THIS time AWX/Ansible gave a more useful error message:
   ansible.errors.AnsibleFileNotFound: Could not find or access 'tmp/satestfile'
    Searched in:
        /var/lib/awx/projects/simon/files/tmp/satestfile
        /var/lib/awx/projects/simon/tmp/satestfile
        /var/lib/awx/projects/simon/files/tmp/satestfile…

So it is saving things on the main directory structure, but doesn't like absolute paths, which seems odd.
I then created the testfile in one of the named directories and AWX completed the task successfully.
Would still like an explanation if anyone understands this better than I.


text:
Q: Find distortion coefficients from known pixel coordinates and real world coordinates I have been searching for days after a possible (alternative) solution to determine a camera's distortion coefficients WITHOUT the use chessboards/checkerboard. The reason for this is that I have sufficiently many points for which I know both the real-world position and the 2D-image position and I image it could be done using this information.
So, here is what I know about:
Camera
focal_length  = 3.9
image_height  = 3456
image_width   = 4608
esl_height    = 35
sensor_height = 4.69
sensor_width  = 6.26
pixel_size    = 1.34/1000
FOV_x         = 71.9
FOV_y         = 56.7

F_x = image_width /(2 * tan(FOV_x* pi / 360))
F_y = image_height /(2 * tan(FOV_y* pi / 360))

C_x = image_width / 2
C_y = image_height / 2

row1 = [F_x,0,C_x]
row2 = [0,F_y, C_y]
row3 = [0,0,1]

camera_matrix = np.matrix([row1,row2,row3])

which gives:
matrix([[3.17701054e+03, 0.00000000e+00, 2.30400000e+03],
        [0.00000000e+00, 3.20254589e+03, 1.72800000e+03],
        [0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])

 Data
I have a dataset containing 49 points for which I have both the real-world (x,y) positions (I also have the z values, but I am really only interested in the (x,y) position. Also, I have the pixel positions for all these points in an image (They are the bounding box centers in the object deterction I perform.
  id  manual.location.x  manual.location.y  manual.location.z  \
0    0            32.9878            41.9033              0.215
1    1            32.9878            44.4404              0.215
2    2            32.9878            44.4404              0.215
3    3            32.9878            44.4404              0.565
4    4            32.9878            44.4404              0.565
5    5            32.9878            44.4404              0.565
6    6            32.9878            44.4404              0.565
7    7            32.9878            44.4404              0.565
8    8            32.9878            41.9033              0.753
9    9            32.9878            44.4404              0.779
10  10            32.9878            44.4404              0.779
11  11            32.9878            44.4404              0.779
12  12            32.9878            41.9033              1.024
13  13            32.9878            44.4404              1.024
14  14            32.9878            42.7490              1.100
15  15            32.9878            43.5947              1.100
16  16            32.9878            43.5947              1.100
17  17            32.9878            43.5947              1.100
18  18            32.9878            43.5947              1.100
19  19            32.9878            44.4404              1.231
20  20            32.9878            44.4404              1.231
21  21            32.9878            44.4404              1.231
22  22            32.9878            44.4404              1.231
23  23            32.9878            42.7490              1.320
24  24            32.9878            43.5947              1.412
25  25            32.9878            42.7490              1.412
26  26            32.9878            43.5947              1.412
27  27            32.9878            44.4404              1.412
28  28            32.9878            44.4404              1.458
29  29            32.9878            44.4404              1.458
30  30            32.9878            44.4404              1.458
31  31            32.9878            44.4404              1.458
32  32            32.9878            42.7490              1.620
33  33            32.9878            42.7490              1.620
34  34            32.9878            43.5947              1.620
35  35            32.9878            43.5947              1.620
36  36            32.9878            42.7490              1.620
37  37            32.9878            44.4404              1.651
38  38            32.9878            44.4404              1.651
39  39            32.9878            44.4404              1.651
40  40            32.9878            44.4404              1.651
41  41            32.9878            44.4404              1.651
42  42            32.9878            42.7490              1.850
43  43            32.9878            42.7490                NaN
44  44            32.9878            44.4404                NaN
45  45            32.9878            44.4404                NaN
46  46            32.9878            44.4404              1.850
47  47            32.9878            43.5947              1.850
48  48            32.9878            44.4404              1.850

    bbox_center_x  bbox_center_y
0          4269.5         2914.0
1          1035.0         2883.5
2           843.5         2880.0
3          1516.5         2529.0
4          1247.5         2527.0
5          1730.0         2525.5
6           987.0         2522.0
7           765.5         2520.0
8          4435.0         2356.5
9          1196.0         2257.0
10          938.5         2255.0
11          704.5         2250.0
12         4547.0         1998.0
13         1291.0         1980.0
14         3681.0         1864.5
15         2394.0         1856.0
16         1931.5         1854.0
17         2043.0         1853.5
18         2043.0         1853.5
19         1620.0         1676.0
20         1267.0         1675.5
21          847.0         1672.5
22          593.5         1669.5
23         3783.5         1452.0
24         1931.5         1446.5
25         3346.5         1443.5
26         2878.0         1443.0
27         1632.0         1350.0
28         1409.0         1346.5
29          945.0         1339.5
30          727.0         1334.0
31          534.5         1332.0
32         4349.0         1109.0
33         3859.0         1101.0
34         1920.5         1097.5
35         2878.0         1090.5
36         3364.0         1087.0
37         1460.5         1037.0
38         1290.5         1036.0
39         1065.5         1034.0
40          748.0         1032.5
41          473.0         1029.0
42         4262.0          726.0
43         3683.5          713.0
44         1375.0          710.0
45         1094.5          708.0
46          850.0          705.0
47         3103.5          702.5
48          375.5          701.5

 Pixel to real world without distortion taken into account
I have managed to get the real world positions from the pixels, but as you can imagine, the farther away I am from the image center (C_x, C_y) the farther the result of the transformation is. I assume it is due to distortion. So, what I do is this:
I define four points in a quadrilater in my image and their real-world counterparts
import numpy as np
import cv2
import scipy

coords = {
    "realworld": np.array([
        [32.9878,41.9033],
        [32.9878,44.4404],
        [32.9878,42.7490],
        [32.9878,44.4404]
    ]),
    "pixel": np.array([
        [4269.5,2914.0],
        [843.5,2880.0],
        [4262.0,726.0],
        [375.5,701.5] #
    ])
}

realworld_array = coords['realworld']
pixel_array= coords['pixel']

and find the Perspective Transform using opencv:
M = cv2.getPerspectiveTransform(np.float32(pixel_array),np.float32(realworld_array))

I define my function from pixels to real-world points
def R2_to_R3(pixel):

    if type(pixel) != np.ndarray:
        pixel = np.array(pixel).reshape(1,2)
    assert pixel.shape[1]==2, "Need (N,2) input array"
    pixel = np.concatenate([pixel, np.ones((pixel.shape[0],1))], axis=1)
    lonlat = np.dot(M,pixel.T)

    return (lonlat[:2,:]/lonlat[2,:]).T

Now, for the center of the image:
pixel = (C_x,C_y)=(2304.0, 1728.0)
R2_to_R3((C_x,C_y))
array([[32.98780048, 43.50150617]])

Real world coordinates [32.98780048, 43.5314615]

But for a point further away
pixel = (4435.0,2356.5)
R2_to_R3(pixel)
array([[32.98780025, 42.11436824]])

Real world coordinates: [32.98780025, 41.9033]

which is rather bad.
Now, note that I never use my camera matrix and this is due to the fact that I do not know how to compute the distortion coefficient. Is there a way to do this without the painful process of doing the chessboard exercice?
Grateful for anything that would improve my work.
 Update
After some searching (i.e. googling), I found that this could be achieved using cv.calibrateCamera() in the following way:
image_height  = 3456
image_width   = 4608
w = image_width
h = image_height
rvec = (0, 0, 0)  # rotation relative to the frame: Static
tvec = (0, 0, 0)  # translation relative to the frame: Static
size = (w,h)

cv.calibrateCamera(
[pts3d], [pts2d],
size,camera_matrix,np.float32([0,0,0,0,0]),
flags=0
| cv.CALIB_FIX_K1
| cv.CALIB_FIX_K2
| cv.CALIB_FIX_K3
| cv.CALIB_FIX_K4
| cv.CALIB_FIX_K5
,rvec,tvec)

However, this returns:
File "<ipython-input-319-af5936255ea4>", line 31
    ,rvec,tvec)
              ^
SyntaxError: positional argument follows keyword argument

What does this mean?


text:
Q: jQuery AJAX function not doing anything I have a form and I want to insert the value of this form as soon as someone clicks a radio button. No better excuse than that I am not good at jQuery at all. This is what I've got so far.
HTML:
<form>
    <input type="radio" checked="true" id="q1r1" name="q1" value="Awesome">
    Awesome

    <input type="radio" id="q1r2" name="q1" value="Ok">
    Ok

    <input type="radio" id="q1r3" name="q1" value="Awful">
    Awful
</form>

get.JSON:
$('#q1r1').on('click',function(){
    var get_var_name = $(this).val();
        $.getJSON('json/question1.php?team=<?php echo $teamid ?>',{q1:get_var_name},function(data,status){
            console.log(data);
            if(status == 'success'){
                console.log(data);
            } else {
                alert('Status: ' + status);
            }
            });
        });

...json/question1.php:
<?php
    require('db_connect.php');
    session_start();
    $uid = $_SESSION['uid'];

    if($_GET['q1']) {

        $teamid = $_GET['team'];
        $insertq1 = $_GET['q1'];

        $sql = "UPDATE result
        SET q1='$insertq1'
        WHERE userid='$uid' AND teamid='$teamid' ";

        $result = $mysqli->query($sql);

    }
?>

As you probably see, I'm really no good at this at all, but this is what I had planned to happen:

*

*The logged in user selects an option, Awesome, OK or Awful.

*Without the page refreshing or a submit button being clicked, the get.JSON will automatically nudge the question1.php with the values teamid (saved in $teamid) and q1 (the value of the users choice).

*The php file silently updates the users database with the values, everybody happy.

Thing is that nothing happens when I click on "Awesome" as of right now, and I don't know why. I've been trying to follow multiple guides, but I'm just not sure how to go about solving this one. Any advice or help is much appreciated.
Kind regards, Mo.
P.s!

is included.

A: just add onchange() in your input(radio type in this case) to call a javascript function that get data from url with no need to refresh the page,
i've modified your code and tested it with a php of my own.
your html must be like
  <form>
      <input type="radio" checked="true" id="q1r1" name="q1" value="Awesome" onchange="GrabData(this)">
      Awesome

      <input type="radio" id="q1r2" name="q1" value="Ok" onchange="GrabData(this)">
      Ok

      <input type="radio" id="q1r3" name="q1" value="Awful" onchange="GrabData(this)">
      Awful
  </form>

then you can either write this javascript code inside the html by adding

or put it in another file .js (dont forget to call it from you html page)
JS CODE-->
function GrabData(Passeddata){
  var radioValue = Passeddata.value;
  var URL = "json/question1.php?q1="  + radioValue + "&teamid="<?php echo $teamid; ?>;
  $.ajax( {
      url : URL,
      type : "GET",
      dataType: 'json',
      success : function(data) {
        if (data == "") {
          alert("data is empty");
        }else{
          console.log('got your data back sir');
        }
      }
  });
}

please let me know if it worked or if there is some other problems


text:
Q: Best way to handle exceptions with a lot of exceptions to handle What's the best way to C# exception handling if I have a lot of exceptions to handle?
Will I put all of them in the try block or put as many try blocks as I can?
For example, when I was connecting to a database as follows,
what is the best way to put the try...catch...finally blocks?
OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=school.mdb");
conn.Open();
string sql = "select * from sheet1 where student='stu2'";
OleDbCommand command;
command = new OleDbCommand(sql, conn);
OleDbDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    for (int i = 0; i < reader.FieldCount; i++)
    {
        Console.Write("{0} ", reader[i]);
    }

    Console.WriteLine();
}

reader.Close();
conn.Close();

A: One little exception-handling hint: your code is not cleaning up after itself in case an exception is thrown. The following code will clean up, whether or not an exception is thrown:
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=school.mdb"))
{
    conn.Open();
    string sql = "select * from sheet1 where student='stu2'";
    using (OleDbCommand command = new OleDbCommand(sql, conn))
    {
        using (OleDbDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    Console.Write("{0} ", reader[i]);
                }

                Console.WriteLine();
            }
        }
    }
    conn.Close();
}


text:
Q: Downloading osm data in geospatial format I am trying to download osm data from this relation for a waterway. https://www.openstreetmap.org/relation/3396950#map=10/13.0280/75.8894
The option to download XML is available, and I have used QuickOSM plugin in QGIS, and used Overpass Turbo interface to download in a geospatial format but in vain.
Is there a way to download osm data based on the relation?
Thank you.

A: Overpass Turbo allows you to export the results of Overpass queries as geojson files that you can open in QGIS or ArcMap/ArcGIS Pro. By default, the query returns XML data, but the toolbar in the upper left of Overpass Turbo has an Export option that allows for geojson downloads.
Here is the proper Overpass query: https://overpass-turbo.eu/s/149i. Since you're only interested in one relation, it's pretty straightforward--just query by OSM ID. More information on query syntax is available in the Overpass Query Language docs.


text:
Q: DynamoDB: How to set FilterExpression for scan api where values in ExpressionAttributeValues depend on a result of some processing on multiple fields? So I want to scan the table and filter the result by the sum of values stored in 2 fields.
Currently my js code looks like this
var params = {
    TableName : "core-atv-quota-table-dev",
    FilterExpression: "#info.#branch = :branchId AND {{#info.#points / #info.#location}} > :score",
    ExpressionAttributeNames:{
         "#info": "matching_info",
         "#branch": "branch",
         "#points": "points",
         "#location": "location"
    },
    ExpressionAttributeValues: {
        ":branchId": "3",
        ":score": "8"
    },
    ReturnConsumedCapacity: 'TOTAL'
};
docClient.scan(params, function(err, data) {
    if (err) console.error(err); // an error occurred
    else console.log(data); // successful response
});

As you can see, {{#points/#location}} would not work. In this particular case, I can probably compute and store the value on insert and compare to that but in my use case I don't know which fields from matching_info will be used to filter the results.
I am looking for a way to get dynamodb to grab values from an item, process them (addition, subtraction etc) and use the processed info to match to a value given to filter.

A: Unfortunately, this isn't possible. FilterExpression doesn't allow for arithmetic operations.

The syntax for a filter expression is identical to that of a condition
  expression. Filter expressions can use the same comparators,
  functions, and logical operators as a condition expression.

FilterExpression Docs
Comparison Operator and Function Reference


text:
Q: Problem with Profile object in ASP.NET Global.asax file I have a global.asax file with the following code:
using System;
using System.Web.Security;
using System.Web.Profile;
using System.Configuration;

namespace Pueblo411 {
    public class Global : System.Web.HttpApplication {

        void Application_Start ( object sender, EventArgs e ) {
            Application ["SessionCount"] = 0;
        }

        void Session_Start ( object sender, EventArgs e ) {
            Application.Lock ( );
            int count = (int)Application["SessionCount"];
            Application ["SessionCount"] = count + 1;
            Application.UnLock ( );
        }

        void Session_End ( object sender, EventArgs e ) {
            Application.Lock ( );
            int count = (int)Application["SessionCount"];
            Application ["SessionCount"] = count - 1;
            Application.UnLock ( );
        }

        public void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs args)
        {
            ProfileCommon anonProfile = Profile.GetProfile(args.AnonymousID);
            foreach (SettingsProperty prop in ProfileBase.Properties)
                Profile[prop.Name] = anonProfile[prop.Name];
            ProfileManager.DeleteProfile(args.AnonymousID);
            AnonymousIdentificationModule.ClearAnonymousIdentifier();
        }

    }
}

For whatever reason, in the OnMigrateAnonymous function, I get the error that "Profile does not exist in the current context".  I have declared the namespaces I need (I think), so I don't understand the issue here.  Ironically, in a web forms page, I don't get this same error.
I could use some help understanding this issue.  Thanks.


text:
Q: get the request response in Koa with koa-request in node I'm getting started with Koa ecosystem. I know it's based in generator functions (a topic that is pretty new for me, for now), and I'm having issues with a very simple task: Call an external web service, fetch the response and send it to the client app (Angular in my case).
The code:
var koa = require('koa');
var app = koa();
var koarouter = require('koa-router');
var router = koarouter();

router.post('/devices', function *(next) {
    var reqdata = {};
    reqdata.info="request to send"
    var options = {
        url: url_getDevices,
        headers: reqdata
    };

    var response = yield request(options);
    var info = JSON.parse(response.body);

    console.log(info);

});

I suppose that I have to manage with yield and next but I'm doing different tests and having issues, and I'd to know best practices with Koa in this case.
Thanks!

A: Are you just trying to send info as a response from the POST request handler? You can just send it as the body of your response. In Koa, this.body is an alias for this.response.body:
this.body = info;

I would also recommend checking out the docs for Koa on their website.


text:
Q: Empty Tomcat thread dumps using jstack Trying to collect thread dump of Apache Tomcat8.5 in windows server I ended using jstack with psexec as follows(as using jstack directly wasn't possible, so I'm using pexec to execute jstack using syetm process):

PsExec.exe -s "C:\Program Files\Java\jdk1.7.0_40\bin\jstack.exe" -l 5340 > dumps.txt

with 5340 is the PID of the running Tomcat8 process.
The execution started without any errors and it shows this output:

PsExec.exe -s "C:\Program Files\Java\jdk1.7.0_40\bin\jstack.exe" -l 5340 > dumps.txt

 PsExec v2.2 - Execute processes remotely Copyright (C) 2001-2016 Mark Russinovich Sysinternals - www.sysinternals.com

Starting C:\Program Files\Java\jdk1.7.0_40\bin\jstack.exe on VMNAME...

When I check th dumps.txt I find it empty, even I'm running The command line as Admin.

Thnks for your help!

A: As a conclusion to the discussion. You need to use the same VM version for executing a jstack command as the VM version you are going to inspect. In case of any errors, you could try a -F param to jstack.
Also, you don't need PsExec tools on newer VMs anymore.


text:
Q: Alignment Problem with Datatable Header when use ScrollY I have a problem with data table header alignment. All things will go fine until I did not use ScrollY.
On the page, I have a side navbar, that can be expanded. Now When I expand the side navbar and move the content area toward the right side, the table header goes out of the page.
1. Table:

              Header-1
              Header-2
              Header-3
              Header-4

             1
             2
             3
             4

2. Script.

$(document).ready( function () {
   $('#data_table').DataTable( {
    paging: true,
    ordering:false,
    scrollY:315,
    scrollCollapse:true,
    scrollX:true
   });
});

html view

A: Are you using css bootstrap?
Please try to use the following script
Html

        Header-1
        Header-2
        Header-3
        Header-4

        1
        2
        3
        4

Javascript
Add the script below after datatable initiation
table.columns.adjust().draw();

And the script will be like this
$(document).ready(function () {
  var table = $("#data_table").DataTable({
    paging: true,
    ordering: false,
    scrollY: 315,
    scrollCollapse: true,
    scrollX: true
  });

  table.columns.adjust().draw();
});

example : codepen


text:
Q: Updating multiple rows of sql from php I've written a php page to load data from mysql table based on dropdown selection, which is also populated from table.
I then want some of the data to be able to be changed and then, when submitted, written back to the database.
Here's what I have so far; I can get the turnout and percentage to update using the $sql update command at the bottom, however the other data is a list of names which I cannot get to update, see $sql1 command.
I've tried lots of methods including for($i=0;$i<$count;$i++){ etc.... however I can only ever get it to update one of the rows.
Really hope someone can help, as I'm so close now
<?php

require 'config.php';
?>

<!doctype html public "-//w3c//dtd html 3.2//en">

<title>Election Results</title>

<?Php

@$cat=$_GET['cat'];
if(strlen($cat) > 0 and !is_numeric($cat)){
echo "Data Error";
exit;
}

$quer2="SELECT DISTINCT * FROM ward order by ward";

echo "<form method='post' action='$_PHP_SELF'>";

echo "<select name='cat' style='width:220px' onchange=\"reload(this.form)\"><option value=''>Select Ward</option>";
foreach ($dbo->query($quer2) as $noticia2) {
if($noticia2['ward_id']==@$cat){echo "<option selected value='$noticia2[ward_id]'>$noticia2[ward]</option>"."
";

}
else{echo "<option value='$noticia2[ward_id]'>$noticia2[ward]</option>";

}
}
echo "</select>

";

if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT * FROM candidate where ward_id=$cat order by candidate_id";
}else{ }

foreach ($dbo->query($quer2) as $noticia2) {
if($noticia2['ward_id']==@$cat){
echo "Turnout: <input type='text' id='result' name='turnout' style='width:35px' value='$noticia2[turnout]'> Percentage: <input type='text' id='result' name='percentage' style='width:35px' value='$noticia2[percentage]'>%

";
echo "Candidates:
";

$conn = mysql_connect($dbhost_name, $username, $password);
mysql_select_db('raynerco_election');
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("
{$query}
*** {$err} ***
");
}
}

$query="SELECT DISTINCT * FROM candidate where ward_id=$cat order by candidate_id";
$result = mysql_query_or_die($query);

echo("
");
echo '
';
echo "	";
echo "Candidate:	";
echo "Results:	";
echo '
';
while ($rows = mysql_fetch_assoc($result)) {
echo '
';

echo "<input type='text' name='candidate_id' value='$rows[candidate_id]'>	";
echo "<input type='text' name='candidate' value='$rows[candidate]'>	";
echo "<input type='text' name='result' value='$rows[result]'>	";
// }

echo '
';
}
echo("
");

echo "
<input name='update' type='submit' value='Update'>";
echo "</form>";

}
else{

}
}

?>

<?php

$ward_id = $_POST['ward_id'];
$turnout = $_POST['turnout'];
$percentage = $_POST['percentage'];
$candidate_id = $_POST['candidate_id'];
$candidate = $_POST['candidate'];
$result = $_POST['result'];

if(isset($_POST['update']))
{

$conn = mysql_connect($dbhost_name, $username, $password);

$sql = "UPDATE ward SET turnout = '$turnout', percentage = '$percentage' WHERE ward_id = '$cat'";
$sql1 = "UPDATE candidate SET candidate = '$candidate', result = '$result' WHERE candidate_id = 'candidate_id' ";
mysql_select_db('raynerco_election');
$retval = mysql_query( $sql, $conn );

if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
header( "Location: index.php?cat=$cat&updated" ); die;
}
if (isset($_GET['updated'])) {
echo "Data updated successfuly";

}

?>

Start again


text:
Q: S.M.A.R.T data advice I've just bought a re-certified WD Red 6tb drive, and I'm attempting to understand the S.M.A.R.T info after running a long scan on WD Data Lifeguard on it.
Would you say this is worth returning? I'm concerned how low some of the Values are.

Any advice would be appreciated.

A: Those are all stock thresholds for a modern WD disk. no bad sectors or mechanical issues have been detected so far. If you are worried about the 21 for WARN on Spin up Time, that is the standard default (empty) value
Everything looks fine, but be sure to do a chkdsk -r to scan the surface for bad sectors. if you do the scan and then see an increase in either current pending sectors or reallocated sector count (or Raw Read Error Rate for that matter), return the disk.
Here are the SMART stats for a healthy WD 1TB Black of mine:


text:
Q: Formatting the output stream, ios::left and ios::right I have this code:
cout << std::setiosflags(std::ios::right);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

cout << std::setiosflags(std::ios::left);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

but the output doesnt come like i expected. instead of:
  1  2
1  2

this comes out:
  1  2
  1  2

What is the problem? I set 'std::ios::left' but it makes no difference?

A: You have to clear the previous value in adjustfield before you can set a new one.
Try this:
#include <iostream>
#include <iomanip>
int main () {
  std::cout << std::resetiosflags(std::ios::adjustfield);
  std::cout << std::setiosflags(std::ios::right);
  std::cout << std::setw(3) << 1 << std::setw(3) << 2 << '\n';

  std::cout << std::resetiosflags(std::ios::adjustfield);
  std::cout << std::setiosflags(std::ios::left);
  std::cout << std::setw(3) << 1 << std::setw(3) << 2 << '\n';
}

A: Use setf with a mask (no need for resetiosflags)
using namespace std;
cout.setf(ios::right, ios::adjustfield);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

cout.setf(ios::left, ios::adjustfield);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

A: Unless you're feeling masochistic, just use:
// right justify by default.
cout << setw(3) << 1 << setw(3) << 2 << '\n';

// left justify
cout << std::left << setw(3) << 1 << setw(3) << 2 << '\n';

// right justify again.
cout << std::right << setw(3) << 1 << setw(3) << 2 << '\n';

A: Your code wants a std::resetiosflags(std::ios::right) sent to the output stream to undo the preceding std::setiosflags(std::ios::right).

A: Looks like if both left and right flags are set, the one that was set first takes precedence. If I explicitly reset right flag before setting left, I get the output you expected:
cout << std::setiosflags(std::ios::right);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

cout << resetiosflags(std::ios::right);

cout << std::setiosflags(std::ios::left);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values


text:
Q: Android - How to check, device has Internet connection? This code works:
public static boolean isConnected()
{
    ConnectivityManager cm = (ConnectivityManager)App.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni != null) {
        if (ni.getType() == ConnectivityManager.TYPE_WIFI)
            if (ni.isConnected())
                return true;
        if (ni.getType() == ConnectivityManager.TYPE_MOBILE)
            if (ni.isConnected())
                return true;
        if (ni.getType() == ConnectivityManager.TYPE_ETHERNET)
            if (ni.isConnected())
                return true;
    }
    return false; //none of connections available
}

The question is: do we also have to check TYPE_MOBILE_DUN, TYPE_WIMAX and TYPE_VPN?
Can a device be connected to the Internet over Bluetooth?

A: Just one comment. Think what do you need and remember to be connected to a wifi router doesn't mean you have internet connection or that you are able to reach any point of interest like a backend server.
If your app needs to access a service to work, may be the best way it is to check if you can reach it in an early stage through an async call and only proceed if you could validate that connection.

A: Try to make a simple GET request to http://www.google.com. If your response code is 200 or 400 Then the internet connection exists.
protected static boolean hasInternetAccess()
{
    try
    {
        URL url = new URL("http://www.google.com");

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application:1");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000 * 30);
        urlc.connect();

        // http://www.w3.org/Protocols/HTTP/HTRESP.html
        if (urlc.getResponseCode() == 200 || urlc.getResponseCode() > 400)
        {
            // Requested site is available
            return true;
        }
    }
    catch (Exception ex)
    {
        // Error while trying to connect
        return false;
    }
    return false;
}

For more info, refer to: The perfect function to check Android internet connectivity including bluetooth pan

A: This is all I use:
public static boolean isOffline() {
    ConnectivityManager cm = (ConnectivityManager) BigOvenApplication.getInstance()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    return netInfo == null || !netInfo.isConnected();
}

I don't think you need anything more than that.

A: Just call the method isConnectedToNetwork to check whether it has connection or not. Write this method in a common class file. Thereby you can use simple methodcall where ever you need.
public static boolean isConnectedToNetwork(Context thisActivity) {
        ConnectivityManager connMgr = (ConnectivityManager) thisActivity.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
        if (activeInfo != null && activeInfo.isConnected()) {
            return true;
        }
        return false;
    }

Check before you start the operation.
//thisActivity means getActivity() for fragments
   if (isConnectedToNetwork(thisActivity)) {
           // your operation code follows
     } else {
          //show alert box that there is no internet connection
     }


text:
Q: How to run script via cron and get same results as terminal? (Centos 7.2) I have a complicated question (I understood that's related to environment variables).
I'm running a script via termial as follows: "bash install_version.sh"
script contains:
#!/bin/bash
/root/RADview_linux_6_4_0_* << 'EOF'
o
1
LAB - 16GB Minimum Server
sleep 120
EOF

And it works fine (4 folder were created as it should be).
After that, I tried to run the script via cron and only 1 folder was created (instead of 4).
Crob contains:
47 14 * * 1-5 bash /root/nightlyBuild/install_version.sh

Anyone can advise?


text:
Q: php array reorder values in key sometimes I have in array list as 4,5,1,2 and sometimes 1,2,4,5. How could I reorder values in [list] ASC so I will have 1,2,4,5 and 1,2,3 etc in all [list] fields? Thank you.
Array
(
    [0] => DibiRow Object
        (
            [storage:ArrayObject:private] => Array
                (
                    [d] => 2012-04-03 08:30:00
                    [list] => 4,5,1,2
                )

        )

    [1] => DibiRow Object
        (
            [storage:ArrayObject:private] => Array
                (
                    [d] => 2012-04-03 09:00:00
                    [list] => 1,2,4,5
                )

        )

    [2] => DibiRow Object
        (
            [storage:ArrayObject:private] => Array
                (
                    [d] => 2012-04-03 09:00:00
                    [list] => 3,1,2                    )

        )
    [3] => DibiRow Object
        (
            [storage:ArrayObject:private] => Array
                (
                    [d] => 2012-04-03 09:00:00
                    [list] => 1,2,3                    )

        )

A: Try reading something about bubble sorting first. Then google it, find some examples and try to do it yourself. If you still have problems, come back and ask again, specifying what have you tried and what you think it's wrong with your method.

A: thank you. I found this solution (don't know if it is effective with large data):
for ($i = 0; $i < count($all) ; $i++) {
  $num = $all[$i][list];
  $resort = explode(",", $num);
  sort($resort);
  $resort = implode(",", $resort);
  $all[$i][list] = $resort;
}

A: If this is based on the GROUP_CONCAT in results of previous query I wrote you can simply add ORDER BY to the GROUP_CONCAT() -
GROUP_CONCAT(DISTINCT user_bookings.user_id ORDER BY user_bookings.user_id)


text:
Q: Encrypt and decrypt by parts do not seem to work Consider the code:
const CryptoJS = require("crypto-js");

var key = CryptoJS.enc.Hex.parse("000102030405060708090a0b0c0d0e0f");
var iv = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");

// encrypt
var aesEncryptor = CryptoJS.algo.AES.createEncryptor(key, { iv: iv });

var ciphertextPart1 = aesEncryptor.process("Message Part 1");
var ciphertextPart2 = aesEncryptor.process("Message Part 2");
var ciphertextPart3 = aesEncryptor.process("Message Part 3");
var ciphertextPart4 = aesEncryptor.finalize();

// decrypt
var aesDecryptor = CryptoJS.algo.AES.createDecryptor(key, { iv: iv });

var plaintextPart1 = aesDecryptor.process(ciphertextPart1);
var plaintextPart2 = aesDecryptor.process(ciphertextPart2);
var plaintextPart3 = aesDecryptor.process(ciphertextPart3);
var plaintextPart4 = aesDecryptor.process(ciphertextPart4);
var plaintextPart5 = aesDecryptor.finalize();

console.log(plaintextPart5.toString());

Source: https://cryptojs.gitbook.io/docs/#ciphers
Maybe I am wrong, but I expected the messages to be decrypted.
The output is actually:
61676520506172742033

I have no idea what that output means and where that comes from.
If I print out another part, the same issue:
console.log(plaintextPart4.toString());

Output:
7373616765205061727420324d657373

Discussion
One comment says that I am wrong on my assumption regarding how the method works, a nice answer could nicely correct me as well! I know the difference, from my studies, between one-way encryption and by parts: it makes no sense to me the way it is actually working, it seems a bug. My ideia is that you could keep adding message to be encrypted, as we can do with hashing, in the case of hashing (from the same abovementioned source), it seems to work, why not for encryption as well?

A: The .process method returns any new chunks of ciphertext that were generated by processing the plaintext given as the argument to .process along with any plaintext that was left over from earlier encryptor activity.
In this case the cipher algorithm is AES.  Specifically it's AES-128, because the key used to create the encryptor is 128 bits long.  AES-128 consumes plaintext in 128-bit (16-byte) blocks and emits 128 bits (16 bytes) of ciphertext for each plaintext block.  This block-based processing is what produces the results that you didn't understand.
What happens with your program is:
var ciphertextPart1 = aesEncryptor.process("Message Part 1");

The encryptor is given 14 bytes of input.  That's not enough to allow it to generate a ciphertext block, so .process returns an empty ciphertext result which you store in ciphertextPart1.  The encryptor stores the unprocessed 14 bytes internally.
var ciphertextPart2 = aesEncryptor.process("Message Part 2");

This gives the encryptor a further 14 bytes.  It appends those to the 14 bytes left over from the previous call, so it now has a total of 28 unprocessed bytes.  It processes as many of those bytes as it can.  That is, it processes the first 16 of those bytes ("Message Part1Me") and returns the ciphertext block for those 16 bytes, which you store in cipherText2.  The encryptor now contains 12 unprocessed bytes.
var ciphertextPart3 = aesEncryptor.process("Message Part 3");

This gives the encryptor another 14 bytes.  It now has 26 unprocessed bytes.  It processes the first 16 of those bytes ("ssage Part2Mess") and returns the ciphertext block for those 16 bytes, which you store in cipherText3.  The encryptor now contains 10 unprocessed bytes.
var ciphertextPart4 = aesEncryptor.finalize();

This forces the encryptor to process any unprocessed bytes.  It can only work on 16-byte blocks, so it adds 6 bytes of padding to the remaining 10 unprocessed plaintext bytes ("age Part 3"), encrypts that block and returns the ciphertext for that block.  You store that ciphertext block as ciphertextPart4.
And now you decrypt the ciphertext blocks.
var plaintextPart1 = aesDecryptor.process(ciphertextPart1);

cipherTextPart1 was an empty block, so plaintextPart1 will be empty and obviously the decryptor will retain no unprocessed ciphertext.
var plaintextPart2 = aesDecryptor.process(ciphertextPart2);

cipherTextPart2 contained the encrypted version of the first 16 bytes of the plaintext, so plaintextPart2 will contain "Message Part 1Me".  The ciphertext input was exactly 16 bytes long, therefore the decryptor contains no unprocessed ciphertext.
var plaintextPart3 = aesDecryptor.process(ciphertextPart3);

cipherTextPart3 contained the encrypted version of the next 16 bytes of the plaintext, so plaintextPart3 will contain "ssage Part 2Mess".  Again the decryptor is holding no unprocessed ciphertext.
var plaintextPart4 = aesDecryptor.process(ciphertextPart4);

cipherTextPart4 contained the encrypted version of the final 10 bytes of the plaintext, so plaintextPart3 will contain "age Part 3".  No unprocessed ciphertext remains in the decryptor.
var plaintextPart5 = aesDecryptor.finalize();

The is no unprocessed ciphertext remaining in the decryptor, so finalize has no work to do and plaintextPart5 will be empty.

A:
I honestly expected this example to work since it is from the official documentation, and they do not mention anything.

Comprehensive documentation is a rare beast.

it makes no sense to me the way it is actually working, it seems a bug

It works like this:
const CryptoJS = require("crypto-js");

const original_message = " ...0, ...1, ...2, ...3, ...4, ...5, ...6, ...7, ...8, ...9, ...The End!"

var key = CryptoJS.enc.Hex.parse("000102030405060708090a0b0c0d0e0f");
var iv  = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");

const aesEncryptor = CryptoJS.algo.AES.createEncryptor(key, { iv: iv });
const aesDecryptor = CryptoJS.algo.AES.createDecryptor(key, { iv: iv });

const fragment_size = 25
const e_acc = []
for(let i = 0 ; i*fragment_size < original_message.length ; ++i ) {
  const slice = original_message.slice(i*fragment_size, i*fragment_size + fragment_size)
  console.log("slice to encrypt", slice)
  e_acc.push(aesEncryptor.process(slice));
}
e_acc.push(aesEncryptor.finalize());

let message = ""
for(let i = 0 ; i !== e_acc.length ; ++i ) {
  message += aesDecryptor.process(e_acc[i]).toString(CryptoJS.enc.Utf8)
  console.log("intermidiate message", message)
}
message += aesDecryptor.finalize().toString(CryptoJS.enc.Utf8)
console.log("full message", message)

[...] it supposes to be a trick that you can add information by parts
  [...]
  My idea is that you could keep adding message to be encrypted

And you can, the only thing is - you can't decipher parts of messages that do not fill a block. You can only get as much as fits into a chain of complete blocks.
Consider the code
const sum1 = solver.process("1+22+3")
const sum2 = solver.process("03")
const sum3 = solver.finalize()

Here you can get the intermediate sum1 - sum of 1 and 22. But you can't add 3 right away, because, as you can see later on, it is not actually 3 but 303. Same thing with sum2 - solver do not know yet if the 303 should be added or maybe it would become 3031234.... So the only thing the solver can do is to remember the 3 and then the 303, but not use it. Until you call finalize.
aesEncryptor is like the solver but much more complicated.
Let's get back to the aesDecryptor and why all of plaintextPart* contain only the parts of the message... Why do you need "Progressive Ciphering" in the first place? Probably because you are sending fragments over the net? The key word is fragments - they purposely do not contain all the previous parts of the message as they could weight gigabytes!

in the case of hashing [...], it seems to work, why not for encryption as well?

Hashing is a quite different thing. You can not expect that AES has all the same properties as hashing, as you can not expect that hashing has all the same properties as, for example, summation.


text:
Q: Do I need an extern "C" block to include standard POSIX C headers? Do I need an extern "C" {} block to include standard C headers in a C++ program. Only consider standard C headers which do not have counterparts in C++.
For example:
extern "C" {
 #include <fcntl.h>
 #include <unistd.h>
}

A: Yes, you do. However, many systems (notably Linux) are already adding an extern "C" bracketing like you do. See (on Linux) files /usr/include/unistd.h /usr/include/features.h and the macro  __BEGIN_DECLS defined in /usr/include/sys/cdefs.h and used in many Linux system include files.
So on Linux, you usually can avoid your extern "C" but it does not harm (and, IMHO, improve readability in that case).

A: The system C headers usually already include a extern "C" block, guarded by #ifdef __cplusplus. This way the functions automatically get declared as extern "C" when compiled as C++ and you don't need to do that manually.
For example on my system unistd.h and fcntl.h start with __BEGIN_DECLS and end with __END_DECLS, which are macros defined in sys/cdefs.h:
/* C++ needs to know that types and declarations are C, not C++.  */
#ifdef   __cplusplus
# define __BEGIN_DECLS  extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS
# define __END_DECLS
#endif

A: The behavior of <fcntl.h> and <unistd.h> in C++ is not specified by the standard (because they are also not part of the C89 standard).  That said, I have never seen a platform where they (a) exist and (b) actually need to be wrapped in an extern "C" block.
The behavior of <stdio.h>, <math.h>, and the other standard C headers is specified by section D.5 of the C++03 standard.  They do not require an extern "C" wrapper block, and they dump their symbols into the global namespace.  However, everything in Annex D is "deprecated".
The canonical C++ form of those headers is <cstdio>, <cmath>, etc., and they are specified by section 17.4.1.2 (3) of the C++ standard, which says:
<cassert> <ciso646> <csetjmp> <cstdio> <ctime> <cctype> <climits>
<csignal> <cstdlib> <cwchar> <cerrno> <clocale> <cstdarg> <cstring>
<cwctype>

Except as noted in clauses 18 through 27, the contents of each header
  cname shall be the same as that of the corresponding header name.h, as
  specified in ISO/IEC 9899:1990 Programming Languages C (Clause 7), or
  ISO/IEC:1990 Programming Languages—C AMENDMENT 1: C Integrity, (Clause
  7), as appropriate, as if by inclusion. In the C++ Standard Library,
  however, the declarations and definitions (except for names which are
  defined as macros in C) are within namespace scope (3.3.5) of the
  namespace std.

So the standard, non-deprecated, canonical way to use (e.g.) printf in C++ is to #include <cstdio> and then invoke std::printf.

A: No, you should use the C++ wrapper headers (for instance like <cstdio>). Those take care of all that for you.
If it's a header that doesn't have those, then yes, you'll want to wrap them in extern "C" {}.
ETA: It's worth noting that many implementations will include the wrapper inside the .h file like below, so that you can get away with not doing it yourself.
#ifdef  __cplusplus
extern "C" {
#endif

#ifdef  __cplusplus
}
#endif

A: the macro __BEGIN_DECLS defined in /usr/include/sys/cdefs.h and used in many Linux system include files.

A: It is a good idea to let the compiler know so that it can expect C code when compiling as C++. You might also find that the header files themselves contain extern "C" { as guards.
For example, curses.h on my system contains:
#ifdef __cplusplus
extern "C" {
...

A: I just double checked the stdlib.h for the GNU compiler and the declarations do not use extern "C" as declarations.
edit:
if defined __cplusplus && defined _GLIBCPP_USE_NAMESPACES
define __BEGIN_NAMESPACE_STD    namespace std {

So including the old headers will place declarations on std provided _GLIBCPP_USE_NAMESPACES is defined?


text:
Q: Spring Security OAuth type-safe SpEL builder We are implementing an OAuth2 resource server with spring-security + spring-security-oauth.
The use case is pretty simple :

*

*A. Some resources are only available for authorized clients

*B. Some resources are only available for (HTTP basic) authenticated users

*C. All other resources are only available for (HTTP basic) authenticated users

With Java Configuration, to enforce security constraints, we use a lot of SpEL like this :
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()

             // A. Only authorized clients
             .antMatchers("/type-a").access("#oauth2.hasScope('READ_SOMETHING')")

             // B. Both authorized clients and users
             .antMatchers("/type-b").access("#oauth2.hasScope('READ_SOMETHING_ELSE') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")

             // ... (different flavors of B.) ...

             // C. Everything else is for authenticated users
            .anyRequest().hasRole("USER")
            .and().httpBasic();
}

Although this works fine, I don't like :

*

*The SpEL markup itself can get tricky and cannot be verified until runtime

*Repeating constants (scopes, roles) in multiple SpEL strings...

*Or to prevent duplicated constants, 150-character-long concatenations have poor readability

In general with spring-security, the HttpSecurity builder provided by security configuration base classes (WebSecurityConfigurerAdapter, ResourceServerConfigurerAdapter) is perfect for simple constraints, but composite/sophisticated constraints end up in SpEL.
With spring-security-oauth2 I don't know any other way than SpEL.
Question : Is there any existing utility class that provides some kind of type-safe fluent builder for OAuth2 SpEL ?
Something like :
TypicalPerfectlyNamedSpringFrameworkDreamClass.builder()
    .startExpressionGroup()
        .hasOAuth2Scope("MY-SCOPE")
    .endExpressionGroup()
    .or()
    .startExpressionGroup()
        .isNotOAuth2Request()
        .and()
        .hasRole("ROLE_USER")
    .endExpressionGroup()
    .toString();

A: Short answer: "no, there is no such utility".


text:
Q: Pie chart with multiple tags/info in ggplot2 I want to make a pie-chart in R visualizing four companies by their name and market cap.
Preferably I want to do this using the ggplot2 package since I have used this for graphs and histograms etc previously. Below is an example of my data frame and my desired output.
This is an example of a representable data frame for my data:
  Companies <- data.frame(
  Company = c("Company1", "Company2", "Company3", "Company4"),
  Market_cap = c(500, 200, 150, 90),
  Industry = c("Industry 1", "Industry 2", "Industry 3", "Industry 4"))

Desired output (created in Excel):

A: This is pretty much what you've asked for, with labels for market cap and company name
library(ggplot2)
library(dplyr)
Companies %>%
  mutate(Perc = Market_cap / sum(Market_cap)) %>%
  ggplot(aes(x = "", y = Perc, fill = Industry)) +
  geom_bar(stat = "identity", width = 1, color = "black") +
  coord_polar("y", start = 0) +
  geom_text(aes(label = paste0(Market_cap, "\n", Company)), position = position_stack(vjust = 0.5)) +
  labs(x = NULL, y = NULL, fill = NULL) +
  theme_classic() +
  theme(
    axis.line = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    legend.position = "bottom"
  ) +
  scale_fill_manual(values=c("red", "blue", "green", "purple"))

A: This should get you started - you'll likely want to fiddle with the placement of the labels a bit. I referenced this question for a start on that.
Companies <- data.frame(
  Company = c("Company1", "Company2", "Company3", "Company4"),
  Market_cap = c(500, 200, 150, 90),
  Industry = c("Industry 1", "Industry 2", "Industry 3", "Industry 4"))

Companies$pos <- cumsum(Companies$Market_cap) - Companies$Market_cap/4
Companies$lab <- paste0(Companies$Company, " - ", Companies$Market_cap)

library(ggplot2)

ggplot(Companies, aes(factor(1), Market_cap, , fill = reorder(Industry, Market_cap))) +
  geom_bar(width = 1, stat = "identity") +
  geom_text(aes(x= factor(1), y=pos, label = lab)) +
  coord_polar("y", start = 0) +
  ylab("") +
  xlab("") +
  theme_bw() +
  theme(legend.position = "bottom",
        legend.direction = "horizontal",
        panel.grid = element_blank(),
        axis.text.y=element_blank(),
        axis.ticks = element_blank())

Created on 2020-05-24 by the reprex package (v0.3.0)


text:
Q: Wordpress menu stopped working after installing SSL certificate Please I need help. My wordpress Menu stopped working after installing SSL certificate on my domain only my homepage is working fine. I get this error message every time i click on the menu:
https's server IP address could not be found.
Try running Windows Network Diagnostics.
DNS_PROBE_FINISHED_NXDOMAIN
Stepped taking:

*

*I have updated my permalinks

*I installed really simple ssl

*I have deactivated my plugins one after the other

Yet, the menu still not working. Please anyone who can help me out. Thanks in advance


text:
Q: PHP onclick confirm to Sweet Alert 2 confirmation I need your help here please.I have a button which is echoed by a PHP file to a HTML file. When the button is clicked it uses window confirm() method but I want to use a sweet alert 2 modal to be displayed with yes or no option in the HTML file.
Does anyone have any idea how I can make this work?
PHP echo:
$row['handler'] = "".$GLOBALS['_LANG']['cancel'].
"";

Do I need to add the script to a external file and call it inside PHP or there is better way to do this ?

A: I have just modified your code.
$row['handler'] = ''.$GLOBALS['_LANG']['cancel'].
    '';

And your javascript function will looks like this
function confirmation(text,text2)
  {
    swal({
      title: text,
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'No, cancel!',
      confirmButtonClass: 'btn btn-success',
      cancelButtonClass: 'btn btn-danger',
      buttonsStyling: false
    }).then(function () {
      location.href=text2;
    }, function (dismiss) {
        return false;
    })
  }

Hope it will work :)


text:
Q: PHP output to HTML from database I cant output the values of the row value to the html content any suggestions on how to do that? i tried using different methods so that i will print on the page but it's always blank is there any way  to do it?
<?php

//connect
$dbh=mysql_connect ("localhost", "xxxx_admin", "xxxx")
   or die ('I cannot connect to the database.');
 mysql_select_db ("xxxx_Client");

$term = $_POST['term'];
echo $term;

$sql = mysql_query("select * from ClientTable where FName like '$term'");

if ($row['FName'] == $term){

$ID = $row['ID'];
$FName = $row['FName'];
$LName = $row['LName'];
$PHON = $row['PHON'];

}

else
echo "invalid input";

?>

<title></title>

asdadasdad

<?php echo $FName; ?>
a

<?php echo $_POST["$LName"]; ?>
a

$FName

$LName

$ID

$PHON

sadasdasda
</bod>

A: First, you are probably not getting any results from your query.  Typically when using LIKE  you use some form of wildcard in the query like this:
select * from ClientTable where FName like '%$term%'

Second, you are not actually working with the result set.
You need to use some sort of mysql_fetch_array or similar to get the values into $row.
And of course, you really should not be using the mysql_* functions anyway as they are being deprecated in favor of mysqli_* or PDO.
Finally, your need to learn how to prevent SQL injection.  Your code is vulnerable now.

A: Try adding error_reporting(E_ALL); near the beginning of your code. There is a good chance that a notice message will tell you what you're doing wrong.


text:
Q: How to easily determine version of .fdb-file (Firebird database) When looking at a .fdb-database of a proprietary software (probably using Firebird Embedded), how can I determine which version of Firebird I need to setup?
The only way I can currently imagine is by having a look with a hex viewer at 'ODS-version' which is part of a page header, which is most likely also used as format for the file header, and then somehow by digging through respository history find out which Firebird release supports which ODS-Version. ODS-version, atleast nowadays, is encoded like stated below.
Related docs: https://firebirdsql.org/file/documentation/reference_manuals/reference_material/Firebird-Internals.pdf
Related code:
https://github.com/FirebirdSQL/firebird/blob/3dd6a2f5366e0ae3d0e6793ef3da02f0fd05823a/src/jrd/ods.h
and
inline USHORT DECODE_ODS_MAJOR(USHORT ods_version)
{
    return ((ods_version & 0x7FF0) >> 4);
}

inline USHORT DECODE_ODS_MINOR(USHORT ods_version)
{
    return (ods_version & 0x000F);
}

Is there really no easier way to determine required firebird version, e.g. with some cli-tool?

A: If you have a Firebird installation at hand, you can use gstat to check the ODS for a database. For example:
gstat -h <path-to-your-database>

If the ODS version of the database is supported by the version of gstat, you'll get something like:
Database "D:\DATA\DB\FB4\FB4TESTDATABASE.FDB"
Gstat execution time Sat Mar 17 18:08:09 2018

Database header page information:
        Flags                   0
        Generation              308
        System Change Number    0
        Page size               16384
        ODS version             13.0
        Oldest transaction      393
        Oldest active           394
        Oldest snapshot         394
        Next transaction        395
        Sequence number         0
        Next attachment ID      150
        Implementation          HW=AMD/Intel/x64 little-endian OS=Windows CC=MSVC
        Shadow count            0
        Page buffers            0
        Next header page        0
        Database dialect        3
        Creation date           Jan 6, 2017 14:05:48
        Attributes              force write

    Variable header data:
        *END*

Here ODS version 13.0 means it is a Firebird 4 database.
If the gstat version does not support the ODS version of the database, you will get an error like (eg in this case using a Firebird 4 gstat on a Firebird 2.5/ODS 11.2 database):
Wrong ODS version, expected 13, encountered 11

This has its downsides though: it doesn't provide the ODS minor versions, and for example when using a Firebird 2.0 (ODS 11.0) or 2.1 (ODS 11.1) gstat to access a Firebird 2.5 (ODS 11.2) database, this will lead to the unhelpful error message:
Wrong ODS version, expected 11, encountered 11

The quickest route is to use a Firebird 2.5 gstat as this will allow you to pinpoint the exact ODS versions between 10 (Firebird 1) and 11.2 (Firebird 2.5), and at the same time the error message will allow you to pinpoint if you need a newer version (eg ODS 12 is Firebird 3, ODS 13 is Firebird 4).
However, you will also need to look at the Implementation output of gstat. Firebird database files have platform specific storage (although this has been reduced since Firebird 2.0). For example in Firebird 1.5 and earlier (ODS 10), a database from a 32 bit Firebird cannot be accessed by a 64 bit Firebird. A Firebird database from a little endian platform (most common) cannot be read on a big endian platform (and vice versa).
Within these limitations, a Firebird 2.5 installation can read databases with ODS 10 through 11.2. Firebird 3 can only read ODS 12, and Firebird 4 only ODS 13.
If there are platform mismatches (eg old 32/64 bit or little/big endian) or unsupported ODS versions, you will need to have a transportable backup (gbak) to convert and/or upgrade.
For an overview of ODS versions and accompanying Firebird (or InterBase) version, see All Firebird and InterBase On-Disk-Structure (ODS) versions.


text:
Q: Socket timeout exception in Mongo I see a few MongoExceptions caused by SocketTimeoutException (see the stack trace below). That is, client failed to get a response within the timeout (30 sec.). Now I wonder how to fix it.
The trivial solution is to increase the timeout but I'd like to understand the root cause first. What would you suggest?

caused by java.net.SocketTimeoutException: Read timed out
                 java.net.SocketInputStream.socketRead0 (Native Method)
                        java.net.SocketInputStream.read (SocketInputStream.java:152)
                        java.net.SocketInputStream.read (SocketInputStream.java:122)
                      java.io.BufferedInputStream.read1 (BufferedInputStream.java:273)
                       java.io.BufferedInputStream.read (BufferedInputStream.java:334)
                com.mongodb.Response$MyInputStream.read (Response.java:168)
               org.bson.BasicBSONDecoder$BSONInput.fill (BasicBSONDecoder.java:386)
     org.bson.BasicBSONDecoder$BSONInput.readUTF8String (BasicBSONDecoder.java:460)
                org.bson.BasicBSONDecoder.decodeElement (BasicBSONDecoder.java:155)
                      org.bson.BasicBSONDecoder._decode (BasicBSONDecoder.java:79)
                       org.bson.BasicBSONDecoder.decode (BasicBSONDecoder.java:57)
                    com.mongodb.DefaultDBDecoder.decode (DefaultDBDecoder.java:61)
                      com.mongodb.Response. (Response.java:83)
                                  com.mongodb.DBPort.go (DBPort.java:142)
                                com.mongodb.DBPort.call (DBPort.java:92)
                   com.mongodb.DBTCPConnector.innerCall (DBTCPConnector.java:244)
                        com.mongodb.DBTCPConnector.call (DBTCPConnector.java:216)
             com.mongodb.DBApiLayer$MyCollection.__find (DBApiLayer.java:288)
             com.mongodb.DBApiLayer$MyCollection.__find (DBApiLayer.java:273)
                       com.mongodb.DBCollection.findOne (DBCollection.java:728)
                       com.mongodb.DBCollection.findOne (DBCollection.java:708)

A: Did these time-outs happen after periods of inactivity? It's likely that your connection pool became stale after remaining idle for too long.
If so, there are two ways of going about this:

*

*Catch the socket time-out exceptions, and your immediate request should be able to access a fresh connection pool. (this is if the auto-reconnect option in your connection object is left to true, which is default.)

*Use a custom keep-alive, to ping the mongod server periodically using the same connection pool, so the pool remains fresh.
Option 1 is easy to implement, but the default socket time-out is around 30s which is rather excessive. You can change this setting as required.
Option 2 is a bit of a hack, involving threading.


text:
Q: How can I convert YMD LDAP timestamps to date time in Java? For instance I have the date as: 20171208181856.0Z and I want to convert it into date time format using java. I don't seem to find any working solutions for it.

A: You can create DateTimeFormatter using input format and parse it into ZonedDateTime or OffsetDateTime
String dateTime = "20171208181856.0Z";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss.SX");

OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateTime,formatter);

System.out.println(offsetDateTime);


text:
Q: Django - limit key size on unique_together columns Using MySQL, I am trying to have a table with a composite key of multiple fields.
The issue is that some of the fields are large (255 - 1024 length), if I try to run the migration, I will get:
django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes')

Instead of increasing the DB's key length (or changing some other DB / table settings), I found out that I can just limit the value of the field used as a key in the migration file so that it remains within the max key length, like this:
ALTER TABLE <table> ADD UNIQUE KEY `<table>_composite_key` (`col1`, `col2`(75), `col3`, `col4`, `col5`(150));

However, this is an issue if I were to change the db engine, as that syntax might not be compatible with other.
So I'm wondering is there a way to impose limit for each field in unique_together?
Thanks in advance!

A: Now Django do not support constraints, but in near future will do it.
Now you can add TODO for updating it when Django 2.2 will be released.
Now there are not many API for constraints.
See: https://docs.djangoproject.com/en/2.2/ref/models/constraints/
It is not answer for your question but it can help you for figuring out with this.


text:
Q: When to use Map and when to use Array/List? I am quite new to flutter and in my tutorial I've learnt to use Maps and Arrays. I know that a Map is pretty much an array but things are identified by a key. When should I be using Maps and when should I be using Arrays? Can you please provide some real examples? Thank you very much!

A: When you want to store data in key and values then used Map.
eg. contact list. In that, you can store a person's name as a key and phone no as a value.
The array used for only similar data types. we can not store data of multiple data types in the array.


text:
Q: Pagination and group by for Custom views created using list definition not working I created a list using the list definition + list instance from VS 2010. I also created the list views for the list. When I add Group by and paging properties for custom views other than All Items view then it is not updating the paging and group by properties for custom views.
Here is my view section in schema.xml:
<Views>
  <View Name="{0D99F290-8885-460B-B5D9-89DE354C53E7}" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" Type="HTML" DisplayName="All Items" Url="Lists/ArbitrationDecisions/AllItems.aspx" Level="1" BaseViewID="1" ContentTypeID="0x" ImageUrl="/_layouts/images/generic.png">
    <ViewFields>
      <FieldRef Name="Attachments"/>
      <FieldRef Name="LinkTitleNoMenu"/>
      <FieldRef Name="Property_x0020_Type"/>
      <FieldRef Name="Hotel_x0020_Status"/>
      <FieldRef Name="Union"/>
      <FieldRef Name="Local_x0020_Number"/>
      <FieldRef Name="Comments"/>
    </ViewFields>
    <Query>
      <OrderBy>
        <FieldRef Name="Title"/>
      </OrderBy>
    </Query>
    <Aggregations Value="Off"/>
    <RowLimit Paged="TRUE">30</RowLimit>
    <Mobile MobileItemLimit="3" MobileSimpleViewField="Property_x0020_Type"/>
    <XslLink>main.xsl</XslLink>
    <Toolbar Type="Standard"/>
  </View>
  <View Name="{13F09AAA-C7B3-4807-92F7-F277134D6ECD}" MobileView="TRUE" Type="HTML" DisplayName="All By Hotel name" Url="Lists/ArbitrationDecisions/All By Hotel name.aspx" Level="1" BaseViewID="1" ContentTypeID="0x" ImageUrl="/_layouts/images/generic.png">
    <ViewFields>
      <FieldRef Name="Attachments"/>
      <FieldRef Name="LinkTitle"/>
      <FieldRef Name="Property_x0020_Type"/>
      <FieldRef Name="Hotel_x0020_Status"/>
      <FieldRef Name="Union"/>
      <FieldRef Name="Local_x0020_Number"/>
      <FieldRef Name="Comments"/>
    </ViewFields>
    <Query>
      <GroupBy Collapse="TRUE" GroupLimit="30">
        <FieldRef Name="Title"/>
      </GroupBy>
      <OrderBy>
        <FieldRef Name="ID"/>
      </OrderBy>
    </Query>
    <Aggregations Value="Off"/>
    <RowLimit Paged="TRUE">30</RowLimit>
    <Mobile MobileItemLimit="3" MobileSimpleViewField="LinkTitle"/>
    <XslLink>main.xsl</XslLink>
    <Toolbar Type="Standard"/>
  </View>
  <View Name="{50A610E7-03C9-43DD-997C-499C069FDC12}" MobileView="TRUE" Type="HTML" DisplayName="By Hotel Status" Url="Lists/ArbitrationDecisions/By Hotel Status.aspx" Level="1" BaseViewID="1" ContentTypeID="0x" ImageUrl="/_layouts/images/generic.png">
    <ViewFields>
      <FieldRef Name="Attachments"/>
      <FieldRef Name="LinkTitle"/>
      <FieldRef Name="Property_x0020_Type"/>
      <FieldRef Name="Hotel_x0020_Status"/>
      <FieldRef Name="Union"/>
      <FieldRef Name="Local_x0020_Number"/>
      <FieldRef Name="Comments"/>
    </ViewFields>
    <Query>
      <GroupBy Collapse="TRUE" GroupLimit="30">
        <FieldRef Name="Hotel_x0020_Status"/>
      </GroupBy>
      <OrderBy>
        <FieldRef Name="ID"/>
      </OrderBy>
    </Query>
    <Aggregations Value="Off"/>
    <RowLimit Paged="TRUE">30</RowLimit>
    <Mobile MobileItemLimit="3" MobileSimpleViewField="LinkTitle"/>
    <XslLink>main.xsl</XslLink>
    <Toolbar Type="Standard"/>
  </View>
  <View Name="{DE967002-08CD-4BEE-9140-3D39829F7C64}" MobileView="TRUE" Type="HTML" DisplayName="By Hotel Union" Url="Lists/ArbitrationDecisions/By Hotel Union.aspx" Level="1" BaseViewID="1" ContentTypeID="0x" ImageUrl="/_layouts/images/generic.png">
    <ViewFields>
      <FieldRef Name="Attachments"/>
      <FieldRef Name="LinkTitle"/>
      <FieldRef Name="Property_x0020_Type"/>
      <FieldRef Name="Hotel_x0020_Status"/>
      <FieldRef Name="Union"/>
      <FieldRef Name="Local_x0020_Number"/>
      <FieldRef Name="Comments"/>
    </ViewFields>
    <Query>
      <GroupBy Collapse="TRUE" GroupLimit="30">
        <FieldRef Name="Union"/>
      </GroupBy>
      <OrderBy>
        <FieldRef Name="ID"/>
      </OrderBy>
    </Query>
    <Aggregations Value="Off"/>
    <RowLimit Paged="TRUE">30</RowLimit>
    <Mobile MobileItemLimit="3" MobileSimpleViewField="LinkTitle"/>
    <XslLink>main.xsl</XslLink>
    <Toolbar Type="Standard"/>
  </View>
  <View Name="{0BE3F0A4-BCEC-4185-A3D1-8E9EAEACB767}" MobileView="TRUE" Type="HTML" DisplayName="By Local number" Url="Lists/ArbitrationDecisions/By Local number.aspx" Level="1" BaseViewID="1" ContentTypeID="0x" ImageUrl="/_layouts/images/generic.png">
    <ViewFields>
      <FieldRef Name="Attachments"/>
      <FieldRef Name="LinkTitle"/>
      <FieldRef Name="Property_x0020_Type"/>
      <FieldRef Name="Hotel_x0020_Status"/>
      <FieldRef Name="Union"/>
      <FieldRef Name="Local_x0020_Number"/>
      <FieldRef Name="Comments"/>
    </ViewFields>
    <Query>
      <GroupBy Collapse="TRUE" GroupLimit="30">
        <FieldRef Name="Local_x0020_Number"/>
      </GroupBy>
      <OrderBy>
        <FieldRef Name="ID"/>
      </OrderBy>
    </Query>
    <Aggregations Value="Off"/>
    <RowLimit Paged="TRUE">30</RowLimit>
    <Mobile MobileItemLimit="3" MobileSimpleViewField="LinkTitle"/>
    <XslLink>main.xsl</XslLink>
    <Toolbar Type="Standard"/>
  </View>
  <View Name="{48C45BFF-EBD1-473E-B03E-8609B691A9F3}" MobileView="TRUE" Type="HTML" DisplayName="Summary" Url="Lists/ArbitrationDecisions/Summary.aspx" Level="1" BaseViewID="1" ContentTypeID="0x" ImageUrl="/_layouts/images/generic.png">
    <ViewFields>
      <FieldRef Name="Attachments"/>
      <FieldRef Name="LinkTitle"/>
      <FieldRef Name="Property_x0020_Type"/>
      <FieldRef Name="Hotel_x0020_Status"/>
      <FieldRef Name="Union"/>
      <FieldRef Name="Local_x0020_Number"/>
      <FieldRef Name="Comments"/>
    </ViewFields>
    <Query>
      <OrderBy>
        <FieldRef Name="ID"/>
      </OrderBy>
    </Query>
    <Aggregations Value="Off"/>
    <RowLimit Paged="TRUE">3</RowLimit>
    <Mobile MobileItemLimit="3" MobileSimpleViewField="LinkTitle"/>
    <XslLink>main.xsl</XslLink>
    <Toolbar Type="Standard"/>
  </View>
  <View Name="{9607DFEE-43B8-431C-A5CE-EEEDF333BA90}" MobileView="TRUE" Type="HTML" Hidden="TRUE" DisplayName="" Url="Pages/Application.aspx" Level="255" BaseViewID="1" ContentTypeID="0x" ImageUrl="/_layouts/images/generic.png">
    <ViewFields>
      <FieldRef Name="Attachments"/>
      <FieldRef Name="LinkTitle"/>
      <FieldRef Name="Property_x0020_Type"/>
      <FieldRef Name="Hotel_x0020_Status"/>
      <FieldRef Name="Union"/>
      <FieldRef Name="Local_x0020_Number"/>
      <FieldRef Name="Comments"/>
    </ViewFields>
    <Query>
      <OrderBy>
        <FieldRef Name="ID"/>
      </OrderBy>
    </Query>
    <Aggregations Value="Off"/>
    <RowLimit Paged="TRUE">3</RowLimit>
    <Mobile MobileItemLimit="3" MobileSimpleViewField="LinkTitle"/>
    <XslLink>main.xsl</XslLink>
    <Toolbar Type="Standard"/>
  </View>
</Views>

I'm using SharePoint Online.


text:
Q: Django returning 404 for static files When running a Django project on my local Mac server I get 404 errors when trying to access static files.
My directory structure looks like:
myapp/static

In my settings.py I have tried a variety of combinations of the following:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

STATICFILES_DIRS = [
    os.path.join(PROJECT_ROOT, 'static'),
    '/var/www/myapp/static',
    '/pycharmprojects/myapp/static'
]

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.FileSystemFinder',
)

For every use of a static file I get an error like this in PyCharm:
GET /static/img/pastedsvg%2017.svg HTTP/1.1" 404 101

And an error like this in Firefox:
GET
http://127.0.0.1:8888/static/img/pastedsvg%2017.svg [HTTP/1.0 404 NOT FOUND 15ms]

I have looked at other answers to this problem in Stackoverflow and tried the suggestions but so far nothing works.

A: It is difficult to tell what exactly the issue might be, but here are some observations that may help:

*

*STATIC_ROOT is only used for collectstatic.  It is where collectstatic will copy your static files when you run it from the command line (python -m django collectstatic).

*STATIC_ROOT should not be included in STATICFILES_DIRS as this would confuse collectstatic since its job is to copy static files from your static directories to STATIC_ROOT.

*AppDirectoriesFinder is going to look for static files in a directory called static under each of your apps.  So, for example, if your project is located in /pycharmprojects/myapp/, AppDirectoriesFinder will look for static files in directories such as /pycharmprojects/myapp/anapp/static and /pycharmprojects/myapp/anotherapp/static (for each application listed in INSTALLED_APPS) and copy them to STATIC_ROOT.

*FileSystemFinder is going to use the values in STATICFILES_DIRS to look for static files and copy them to STATIC_ROOT (which is why your value for STATIC_ROOT should not be listed in STATICFILES_DIRS).

*When in debug mode, you do not need to collectstatic as Django will look for files in their original location, but when not debug mode (DEBUG = False in your Django config file), you will need to run collectstatic in order for Django to find your static files.

So, from this, I suggest:

*

*Definitely remove os.path.join(PROJECT_ROOT, 'static') from your STATICFILES_DIR

*Probably remove /pycharmprojects/myapp/static from your STATICFILES_DIR if that points to the same location as os.path.join(PROJECT_ROOT, 'static')

*If you are not running in debug mode (DEBUG = True in your Django config file), run collectstatic from the command line so that Django can see your static files.

One other question.  To which directory is your BASE_DIR pointing?  It seems like PROJECT_DIR might be redundant since it's pointing to where BASE_DIR usually points.
Hopefully something in this wall of text will be helpful.
Cheers!

A: I don't know that the following is the correct answer, but I hope it will go well.
STATIC_URL = '/static/'
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATICFILES_DIRS = [
    # os.path.join(PROJECT_ROOT, "static"),
    os.path.join(BASE_DIR, "static"),
]
print("PROJECT_ROOT", PROJECT_ROOT)
print("BASE_DIR", BASE_DIR)

In this case, the value of the variable named PROJECT_ROOT is the same directory that exists setting file.
That is why it's not PROJECT_ROOT exactly.
You can execute when running server even if writing python-code in setting file. So you can verify that the code was written in properly once again.


text:
Q: Convert multiple .rtf (or .pages/.doc) files to .html on Mac I have about 100 .rtf files with images, formatted text etc. How can I convert all these files to .html, so all the images and formatting will remain?

A: Specially for Brandon.
I solved it easily - just copy/paste. I haven't found another way...