问:
Insert into database table with if else statement in php
May be i didn't ask well
Let's say i have two forms

```<code><form action="reg.php" method="post" enctype="multipart/form-data">
    <input type="text" name="reg_as" id="export" value="exporter">
    <input type="submit" name="reg">
</form>

<form action="reg.php" method="post" enctype="multipart/form-data">
    <input type="text" name="reg_as" id="import" value="importer">
    <input type="submit" name="reg">
</form>
</code>```

How do i insert into multiple tables with if else conditions
reg.php

```<code>$reg_as = strip_tags(@$_POST['reg_as']);
$reg = strip_tags(@$_POST['reg']);
$exporter = "exporter";
$importer = "importer";

if ($reg)
{
    if ($reg_as == $exporter)
                    {
                        $sql =<<<EOF
INSERT INTO exporter (reg_as)
VALUES ('$reg_as');
EOF;

                        $stmt = $db->exec($sql);

                        if (!$stmt)
                        {
                            echo "<script>alert('There was an error some where!.. Please try again')</script>";
                        }
                        else
                        {
                            header("Location: index.php");
                        }
                        if ($reg_as == $importer) {
                            $sql = <<<EOF
INSERT INTO importer (reg_as)
VALUES ('$reg_as');
EOF;
                        }

                        $stmt = $db->exec($sql);

                        if (!$stmt)
                        {
                            echo "<script>alert('There was an error some where!.. Please try again')</script>";
                        }
                        else
                        {
                            header("Location: index.php");
                        }

}
</code>```

The issue here is that, the data dosn't insert to database. Please what could be wrong?

答:
This is an assignment, and the expression returns bool(true):

if ($reg_as = "Exporter")

To compare the two values, you should use two equal signs:

if ($reg_as == "Exporter")

Maybe your could do something like this:

```<code><form action="reg.php" method="post" enctype="multipart/form-data">
    <select name="type" id="type">
        <option value="importer">Importer</option>
        <option value="exporter">Exporter</option>
    </select>

    <input type="text" name="reg_as" placeholder="Insert your data here..." />

    <input type="submit" name="submit" value="Save">
</form>

<?php

if (!empty($_POST['submit'])) {
    $type = in_array($_POST['type'], ['exporter', 'importer']) ? $_POST['type'] : false;
    $value = $_POST['reg_as'];

    switch ($type) {
        case 'exporter':
            $query = "INSERT INTO exporter (reg_as) VALUES (:reg_as)";
            break;
        case 'importer':
            $query = "INSERT INTO importer (reg_as) VALUES (:reg_as)";
            break;
        default:
            throw new Exception('Handle your error here!');
            break;
    }

    $statement = $db->prepare($query);
    $insert = $statement->execute([':reg_as' => $value]);

    if ($insert) {
        header("Location: index.php");
    } else {
        echo "<script>alert('There was an error some where!.. Please try again')</script>";
    }
}
</code>```

Body:
May be i didn't ask well
Let's say i have two forms

<form action="reg.php" method="post" enctype="multipart/form-data">
    <input type="text" name="reg_as" id="export" value="exporter">
    <input type="submit" name="reg">
</form>

<form action="reg.php" method="post" enctype="multipart/form-data">
    <input type="text" name="reg_as" id="import" value="importer">
    <input type="submit" name="reg">
</form>

How do i insert into multiple tables with if else conditions
reg.php

$reg_as = strip_tags(@$_POST['reg_as']);
$reg = strip_tags(@$_POST['reg']);
$exporter = "exporter";
$importer = "importer";

if ($reg)
{
    if ($reg_as == $exporter)
                    {
                        $sql =<<<EOF
INSERT INTO exporter (reg_as)
VALUES ('$reg_as');
EOF;

                        $stmt = $db->exec($sql);

                        if (!$stmt)
                        {
                            echo "";
                        }
                        else
                        {
                            header("Location: index.php");
                        }
                        if ($reg_as == $importer) {
                            $sql = <<<EOF
INSERT INTO importer (reg_as)
VALUES ('$reg_as');
EOF;
                        }

                        $stmt = $db->exec($sql);

                        if (!$stmt)
                        {
                            echo "";
                        }
                        else
                        {
                            header("Location: index.php");
                        }

}

The issue here is that, the data dosn't insert to database. Please what could be wrong?

Body:
This is an assignment, and the expression returns bool(true):

if ($reg_as = "Exporter")

To compare the two values, you should use two equal signs:

if ($reg_as == "Exporter")

Maybe your could do something like this:

<form action="reg.php" method="post" enctype="multipart/form-data">
    <select name="type" id="type">
        <option value="importer">Importer</option>
        <option value="exporter">Exporter</option>
    </select>

    <input type="text" name="reg_as" placeholder="Insert your data here..." />

    <input type="submit" name="submit" value="Save">
</form>

<?php

if (!empty($_POST['submit'])) {
    $type = in_array($_POST['type'], ['exporter', 'importer']) ? $_POST['type'] : false;
    $value = $_POST['reg_as'];

    switch ($type) {
        case 'exporter':
            $query = "INSERT INTO exporter (reg_as) VALUES (:reg_as)";
            break;
        case 'importer':
            $query = "INSERT INTO importer (reg_as) VALUES (:reg_as)";
            break;
        default:
            throw new Exception('Handle your error here!');
            break;
    }

    $statement = $db->prepare($query);
    $insert = $statement->execute([':reg_as' => $value]);

    if ($insert) {
        header("Location: index.php");
    } else {
        echo "<script>alert('There was an error some where!.. Please try again')</script>";
    }
}


来源: stackexchange

问:
Javascript Nested Function - Need help returning result
I am trying to create a function to return a lat/long array from the Google Maps JS API (v3). I am able to write the data out that I retrieve from the API, but I am not able to pass the data along to a variable. I am wanting to do something like this:

```<code>var latLong = getLatLong(Address);
</code>```

The function that I have created is here:

```<code>function getLatLong(loc, callback) {
  var geocoder = new google.maps.Geocoder();
  var array = new Array();

  if (geocoder) {
    geocoder.geocode({ 'address': loc }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latLng = results[0].geometry.location;;
        $.each(latLng, function(k, v) {
          if (k == 'va' || k == 'wa') {
            array.push(v);
          }
        });
        var ret = array;
        callback(ret);
      } else {
        console.log("Geocoding failed: " + status);
      }
    });
  }
}
</code>```

I then am assigning the function to a variable and calling it to give me the lat/long.

```<code>var geo = getLatLong('Dallas, TX', function(result) {
  return result;
});
</code>```

Unfortunately this produces an 'undefined' result. I can access the result in the function, I just can't pass it along. How can I pass the result of the function to a variable to be accessed?

答:
You can't structure the code the way you want to here.  The problem is that geocoder.geocode() is an asynchronous operation.  That's why it takes a callback function.  When you call geocoder.geocode(), it initiates the request to fetch the geocode, and then returns, leaving the request running in the background.  When the request eventually completes, google's api will execute the anonymous function you passed as the second parameter to geocode().

So when you call getLatLong() the actual order that things happen is something like this:

call geocoder.geocode().  (initiates geocode request)

getLatLong() is done and returns undefined. (this is where geo gets set)

(the geocode request completes) google api calls the anonymous function, which pushes the LatLng values into array, and then calls your callback()

to better visualize what's going on, you might write your code as follows (this is exactly equivalent to the way you've written it):

```<code>function getLatLong(loc, callback) {
  var geocoder = new google.maps.Geocoder();
  var array = new Array();

  function handleGeocodeResponse(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var latLng = results[0].geometry.location;;
      $.each(latLng, function(k, v) {
        if (k == 'va' || k == 'wa') {
          array.push(v);
        }
      });
      var ret = array;
      callback(ret);
    }
  }

  if (geocoder) {
    geocoder.geocode({ 'address': loc }, handleGeocodeResponse);
  } else {
    console.log("Geocoding failed: " + status);
  }

  // note- no return specified explicitly is the same as
  //return undefined;
}
</code>```

So, if you can't return a value, then how do you use the results?  Like this:

```<code>getLatLong('Dallas, TX', function(geo) {
  // geo is passed to this function as a parameter
  // move all code that requires `geo` into this function.

});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to create a function to return a lat/long array from the Google Maps JS API (v3). I am able to write the data out that I retrieve from the API, but I am not able to pass the data along to a variable. I am wanting to do something like this:

var latLong = getLatLong(Address);

The function that I have created is here:

function getLatLong(loc, callback) {
  var geocoder = new google.maps.Geocoder();
  var array = new Array();

  if (geocoder) {
    geocoder.geocode({ 'address': loc }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latLng = results[0].geometry.location;;
        $.each(latLng, function(k, v) {
          if (k == 'va' || k == 'wa') {
            array.push(v);
          }
        });
        var ret = array;
        callback(ret);
      } else {
        console.log("Geocoding failed: " + status);
      }
    });
  }
}

I then am assigning the function to a variable and calling it to give me the lat/long.

var geo = getLatLong('Dallas, TX', function(result) {
  return result;
});

Unfortunately this produces an 'undefined' result. I can access the result in the function, I just can't pass it along. How can I pass the result of the function to a variable to be accessed?

Body:
You can't structure the code the way you want to here.  The problem is that geocoder.geocode() is an asynchronous operation.  That's why it takes a callback function.  When you call geocoder.geocode(), it initiates the request to fetch the geocode, and then returns, leaving the request running in the background.  When the request eventually completes, google's api will execute the anonymous function you passed as the second parameter to geocode().

So when you call getLatLong() the actual order that things happen is something like this:

call geocoder.geocode().  (initiates geocode request)

getLatLong() is done and returns undefined. (this is where geo gets set)

(the geocode request completes) google api calls the anonymous function, which pushes the LatLng values into array, and then calls your callback()

to better visualize what's going on, you might write your code as follows (this is exactly equivalent to the way you've written it):

function getLatLong(loc, callback) {
  var geocoder = new google.maps.Geocoder();
  var array = new Array();

  function handleGeocodeResponse(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var latLng = results[0].geometry.location;;
      $.each(latLng, function(k, v) {
        if (k == 'va' || k == 'wa') {
          array.push(v);
        }
      });
      var ret = array;
      callback(ret);
    }
  }

  if (geocoder) {
    geocoder.geocode({ 'address': loc }, handleGeocodeResponse);
  } else {
    console.log("Geocoding failed: " + status);
  }

  // note- no return specified explicitly is the same as
  //return undefined;
}

So, if you can't return a value, then how do you use the results?  Like this:

getLatLong('Dallas, TX', function(geo) {
  // geo is passed to this function as a parameter
  // move all code that requires `geo` into this function.

});


问:
Converting date in excel
I need to convert the below date format in excel.

Currently I have: Fri Jan 06 05:10:31 2017

Current Format : ddd MMM dd hh:mm:ss yyyy

I wanted to be in the following format: dd/mm/yyyy hh:mm:ss

答:
Yet another approach:</p>

```<code>=DATEVALUE(MID(A1,9,2)&MID(A1,5,3)&RIGHT(A1,4))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Converting date in excel

Body:
Yet another approach:

=DATEVALUE(MID(A1,9,2)&MID(A1,5,3)&RIGHT(A1,4))


问:
Azure Virtual Machine not accessible after RDP port changed
I've changed RDP port to 8080 in registry on my Azure Virtual Machine (Windows Server). Now it is not accessible from outside, I cant connect it.

Azure VM is managed by Resource Manager (not Classic VM).

UPDATE:

Turning secuiruty rules so allow all not helped.

答:
Azure has to know to allow traffic through to your VM. By default, on a Windows VM, only RDP is open. But you (for some reason) changed the RDP port in Windows Server. You need to do this with the network interface as well, via the VM settings (which has nothing to do with Windows itself):

Via Settings, go to Network Interfaces

Select your network interface and go to Network Security Group

From network security group, add an inbound rule for port 8080 (or modify the existing RDP rule to be port 8080).


问:
npm script to rename files with the version specified in package.json
In the script section of my package.json file, I'm trying to rename some files in a directory, however I would like to inject a value in the command line that is taken from the package.json itself (version).

So in the case below, the build:rename script, I would like it to replace a token in the script (somevalue) before executing it.

In this case I would like to pass in the npm_package_version so that it's part of the name of the file.  I'm at a loss...

"scripts": {
    "build:copy": "mkdirp dist && cp src/*.js dist/",
    "build:rename": "renamer --regex --find '(.+)(.js)' --replace '$1**somevalue**$2' dist/*"
}
```

答:
The current version specified in package.json can be referenced via the script using package.json vars as follows:

bash

In bash shells using the syntax - (note the dollar $ prefix):

$npm_package_version

Windows

In cmd.exe and Powershell using the syntax  - (note the percentage % prefix and suffix):

%npm_package_version%

cross-patform

To achieve this cross-platform utlize cross-var:

$ npm i -D cross-var

The build:rename script can be revised as follows:

"scripts": {
  ...
  "build:rename": "cross-var \"renamer --regex --find '\\.js$' --replace '$npm_package_version.js' dist/*\""
},
```

<p><em>Note</em>: the additional change to the <code>--find</code> regular expression as <code>cross-var</code> doesn't seem to play nice when the <code>--replace</code> value includes dollar references (<code>$1</code>, <code>$2</code>) to the parenthesised substrings/groups in the <code>--find</code> value. The new regex simply matches the files/strings part ending in <code>.js</code> instead.</p>

<hr>

<p><strong>Example directory</strong></p>

<p>Running the updated <code>build:rename</code> script, (when the <code>version</code> in <code>package.json</code> is <code>0.3.0</code>), will rename the <code>.js</code> files in the <code>dist</code> directory from this:</p>

```.
├── dist
│   ├── a.html
│   ├── b.css
│   ├── foo.js
│   ├── bar.js
│   └── quux.js
```

<p>...to this:</p>

```.
├── dist
│   ├── a.html
│   ├── b.css
│   ├── foo0.3.0.js
│   ├── bar0.3.0.js
│   └── quux0.3.0.js
```

<p><strong>Additional note</strong></p>

<p>The cp command used in the <code>build:copy</code> script will also not work cross-platform. This can be substituted with the copyfiles package:</p>

<p><code>$ npm i -D copyfiles</code></p>

<p>... and the <code>build:copy</code> script then replaced with the following:</p>

<pre class="lang-json prettyprint-override"><code>"scripts": {
  "build:copy": "copyfiles -u 1 \"src/*.js\" \"dist\"",
   ...
},
</code>```

The mkdirp dist && part in your script then becomes redundant as copyfiles with create the necessary directory (i.e. dist).

If cross-platform is not necessary for your use-case then simply leave the build:copy script as-is, and change your build:rename script to:

"build:rename": "renamer --regex --find '\\.js$' --replace $npm_package_version'.js' dist/*"
```

ContentLicense: CC BY-SA 4.0

Body:
The current version specified in package.json can be referenced via the script using package.json vars as follows:

bash

In bash shells using the syntax - (note the dollar $ prefix):

$npm_package_version

Windows

In cmd.exe and Powershell using the syntax  - (note the percentage % prefix and suffix):

%npm_package_version%

cross-patform

To achieve this cross-platform utlize cross-var:

$ npm i -D cross-var

The build:rename script can be revised as follows:

"scripts": {
  ...
  "build:rename": "cross-var \"renamer --regex --find '\\.js$' --replace '$npm_package_version.js' dist/*\""
},

Note: the additional change to the --find regular expression as cross-var doesn't seem to play nice when the --replace value includes dollar references ($1, $2) to the parenthesised substrings/groups in the --find value. The new regex simply matches the files/strings part ending in .js instead.

Example directory

Running the updated build:rename script, (when the version in package.json is 0.3.0), will rename the .js files in the dist directory from this:

.
├── dist
│   ├── a.html
│   ├── b.css
│   ├── foo.js
│   ├── bar.js
│   └── quux.js

...to this:

.
├── dist
│   ├── a.html
│   ├── b.css
│   ├── foo0.3.0.js
│   ├── bar0.3.0.js
│   └── quux0.3.0.js

Additional note

The cp command used in the build:copy script will also not work cross-platform. This can be substituted with the copyfiles package:

$ npm i -D copyfiles

... and the build:copy script then replaced with the following:

"scripts": {
  "build:copy": "copyfiles -u 1 \"src/*.js\" \"dist\"",
   ...
},

The mkdirp dist && part in your script then becomes redundant as copyfiles with create the necessary directory (i.e. dist).

If cross-platform is not necessary for your use-case then simply leave the build:copy script as-is, and change your build:rename script to:

"build:rename": "renamer --regex --find '\\.js$' --replace $npm_package_version'.js' dist/*"


问:
mkimage doesn't add public key to .dtb file
I am trying to make a verified boot on beaglebone black by following the documentation

https://github.com/01org/edison-u-boot/blob/master/doc/uImage.FIT/beaglebone_vboot.txt

when i run the command to put public key into .dtb file

```<code>mkimage -f sign.its -K am335x-boneblack.dtb -k keys -r image.fit
</code>```

I get the output

```<code>FIT description: Beaglebone black
Created:         Fri Mar 24 18:47:51 2017
 Image 0 (kernel@1)
  Description:  unavailable
  Created:      Fri Mar 24 18:47:51 2017
  Type:         Kernel Image
  Compression:  lzo compressed
  Data Size:    8490316 Bytes = 8291.32 KiB = 8.10 MiB
  Architecture: ARM
  OS:           Linux
  Load Address: 0x80008000
  Entry Point:  0x80008000
  Hash algo:    sha1
  Hash value:   9a390ee3c02c5bddc7b191d5cbe107991522a6d7
 Image 1 (fdt@1)
  Description:  beaglebone-black
  Created:      Fri Mar 24 18:47:51 2017
  Type:         Flat Device Tree
  Compression:  uncompressed
  Data Size:    38894 Bytes = 37.98 KiB = 0.04 MiB
  Architecture: ARM
  Hash algo:    sha1
  Hash value:   249ca75de41f5202fae334253bd153666f60b7dc
 Default Configuration: 'conf@1'
 Configuration 0 (conf@1)
  Description:  unavailable
  Kernel:       kernel@1
  FDT:          fdt@1
</code>```

But unfortunately there is no such a field like signature or rsa in my .dtb file when i read it with fdtdump.

Here is my .its file:

```<code>/dts-v1/;

/ {
    description = "Beaglebone black";
    #address-cells = <1>;

    images {
        kernel@1 {
            data = /incbin/("zImage.lzo");
            type = "kernel";
            arch = "arm";
            os = "linux";
            compression = "lzo";
            load = <0x80008000>;
            entry = <0x80008000>;
            hash@1 {
                algo = "sha1";
            };
        };
        fdt@1 {
            description = "beaglebone-black";
            data = /incbin/("am335x-boneblack.dtb");
            type = "flat_dt";
            arch = "arm";
            compression = "none";
            hash@1 {
                algo = "sha1";
            };
        };
    };
    configurations {
        default = "conf@1";
        conf@1 {
            kernel = "kernel@1";
            fdt = "fdt@1";
            signature@1 {
                algo = "sha1,rsa2048";
                key-name-hint = "dev";
                sign-images = "fdt", "kernel";
            };
        };
    };
};
</code>```

also in keys folder i have dev.key and dev.crt files.

thanks for your answer.

答:
as it says in: https://lxr.missinglinkelectronics.com/#uboot/doc/uImage.FIT/signature.txt

Public Key Storage

In order to verify an image that has been signed with a public key we need to
have a trusted public key. This cannot be stored in the signed image, since
it would be easy to alter. For this implementation we choose to store the
public key in U-Boot's control FDT (using CONFIG_OF_CONTROL).

Regards, Steve

Body:
I am trying to make a verified boot on beaglebone black by following the documentation

https://github.com/01org/edison-u-boot/blob/master/doc/uImage.FIT/beaglebone_vboot.txt

when i run the command to put public key into .dtb file

mkimage -f sign.its -K am335x-boneblack.dtb -k keys -r image.fit

I get the output

FIT description: Beaglebone black
Created:         Fri Mar 24 18:47:51 2017
 Image 0 (kernel@1)
  Description:  unavailable
  Created:      Fri Mar 24 18:47:51 2017
  Type:         Kernel Image
  Compression:  lzo compressed
  Data Size:    8490316 Bytes = 8291.32 KiB = 8.10 MiB
  Architecture: ARM
  OS:           Linux
  Load Address: 0x80008000
  Entry Point:  0x80008000
  Hash algo:    sha1
  Hash value:   9a390ee3c02c5bddc7b191d5cbe107991522a6d7
 Image 1 (fdt@1)
  Description:  beaglebone-black
  Created:      Fri Mar 24 18:47:51 2017
  Type:         Flat Device Tree
  Compression:  uncompressed
  Data Size:    38894 Bytes = 37.98 KiB = 0.04 MiB
  Architecture: ARM
  Hash algo:    sha1
  Hash value:   249ca75de41f5202fae334253bd153666f60b7dc
 Default Configuration: 'conf@1'
 Configuration 0 (conf@1)
  Description:  unavailable
  Kernel:       kernel@1
  FDT:          fdt@1

But unfortunately there is no such a field like signature or rsa in my .dtb file when i read it with fdtdump.

Here is my .its file:

/dts-v1/;

/ {
    description = "Beaglebone black";
    #address-cells = <1>;

    images {
        kernel@1 {
            data = /incbin/("zImage.lzo");
            type = "kernel";
            arch = "arm";
            os = "linux";
            compression = "lzo";
            load = <0x80008000>;
            entry = <0x80008000>;
            hash@1 {
                algo = "sha1";
            };
        };
        fdt@1 {
            description = "beaglebone-black";
            data = /incbin/("am335x-boneblack.dtb");
            type = "flat_dt";
            arch = "arm";
            compression = "none";
            hash@1 {
                algo = "sha1";
            };
        };
    };
    configurations {
        default = "conf@1";
        conf@1 {
            kernel = "kernel@1";
            fdt = "fdt@1";
            signature@1 {
                algo = "sha1,rsa2048";
                key-name-hint = "dev";
                sign-images = "fdt", "kernel";
            };
        };
    };
};

also in keys folder i have dev.key and dev.crt files.

thanks for your answer.


问:
c# comparing a value in a text box to a field value in Access Database table
I need to read a value in a text box and compare that value to a field in an Access database Table field, if the value in the text box does not exist then provide a message as shown in the code, if it does exist carry on with the rest of the code. Here is what I have, it returns the message if the value is or isn't present in the database table field?? I do not know what I have done incorrectly.</p>

```<code>{
            connection.Open();
            OleDbCommand comd = new OleDbCommand();
            comd.Connection = connection;
            comd.CommandText = "IF NOT EXISTS(SELECT * FROM Players WHERE DOB= '%" + txt_DOB.Text + "%')";
            MessageBox.Show("You must register before you can add activities!");

            //Function to reset all text boxes in Activity Section
        ClearBox2();

        }
</code>```

答:
```<code>using (OleDbConnection connection = new OleDbConnection("yourConnectionString"))
{
    OleDbDataAdapter adap;
    DataTable dt = new DataTable();

    OleDbCommand comd = new OleDbCommand();
    comd.Connection = connection;
    comd.Parameters.AddWithValue("@param", "%" + txt_DOB.Text + "%");
    comd.CommandText = "SELECT * FROM Players WHERE DOB LIKE @param";

    adap = new OleDbDataAdapter(comd);
    adap.Fill(dt);

    if (dt.Rows == null || dt.Rows.Count == 0)
        MessageBox.Show("You must register before you can add activities!");

}
</code>```

Body:
I need to read a value in a text box and compare that value to a field in an Access database Table field, if the value in the text box does not exist then provide a message as shown in the code, if it does exist carry on with the rest of the code. Here is what I have, it returns the message if the value is or isn't present in the database table field?? I do not know what I have done incorrectly.

{
            connection.Open();
            OleDbCommand comd = new OleDbCommand();
            comd.Connection = connection;
            comd.CommandText = "IF NOT EXISTS(SELECT * FROM Players WHERE DOB= '%" + txt_DOB.Text + "%')";
            MessageBox.Show("You must register before you can add activities!");

            //Function to reset all text boxes in Activity Section
        ClearBox2();

        }


问:
Good way to get *any* value from a Java Set?
Given a simple Set<T>, what is a good way (fast, few lines of code) to get any value from the Set?

With a List, it's easy:

```<code>List<T> things = ...;
return things.get(0);
</code>```

But, with a Set, there is no .get(...) method because Sets are not ordered.

答:
Getting any element from a Set or Collection may seem like an uncommon demand - if not arbitrary or eclectic - but, it is quite common when one, for example, needs to calculate statistics on Keys or Values objects in a Map and must initialise min/max values. The any element from a Set/Collection (returned by Map.keySet() or Map.values()) will be used for this initialisation prior to updating min/max values over each element.

So, what options one has when faced with this problem and at the same time trying to keep memory and execution time small and code clear?

Often you get the usual: "convert Set to ArrayList and get the first element". Great! Another array of millions of items and extra processing cycles to retrieve objects from Set, allocate array and populate it:

```<code>HashMap<K,V> map;
List<K> list = new ArrayList<V>(map.keySet()); // min/max of keys
min = max = list.get(0).some_property(); // initialisation step
for(i=list.size();i-->1;){
 if( min > list.get(i).some_property() ){ ... }
 ...
}
</code>```

Or one may use looping with an Iterator, using a flag to denote that min/max need to be initialised and a conditional statement to check if that flag is set for all the iterations in the loop. This implies a lot of conditional checking.

```<code>boolean flag = true;
Iterator it = map.keySet().iterator();
while( it.hasNext() ){
  if( flag ){
    // initialisation step
    min = max = it.next().some_property();
    flag = false;
  } else {
    if( min > list.get(i).some_property() ){ min = list.get(i).some_property() }
  ...
  }
}
</code>```

Or do the initialisation outside the loop:

```<code>HashMap<K,V> map;
Iterator it = map.keySet().iterator();
K akey;
if( it.hasNext() ){
  // initialisation step:
  akey = it.next();
  min = max = akey.value();
  do {
    if( min > list.get(i).some_property() ){ min = akey.some_property() }
  } while( it.hasNext() && ((akey=it.next())!=null) );
}
</code>```

But is it really worth all this manouvre on the behalf of the programmer (and setting up the Iterator on behalf of the JVM) whenever min/max's needed?

The suggestion from a javally-correct ol' sport could well be: "wrap your Map in a class which keeps track of min and max values when put or deleted!".

There is another situation which in my experience the need for just any item from a Map arises. This is when the map contains objects which have a common property - all the same for all of them in that map - and you need to read that property. For example suppose there is a Map of holding bins of the same histogram which have the same number of dimensions. Given such a Map you may need to know the number of dimensions of just any Histobin in the Map in order to, say, create another Histobin of the same dimensions. Do I need to setup an iterator again and dispose it after calling next() just once? I will skip the javally-correct person's suggestion to this situation.

And if all the trouble in getting the any element causes insignificant memory and cpu cycles increase, then what about all the code one has to write just to get the hard-to-get any element.

We need the any element. Give it to us!

Body:
Given a simple Set<T>, what is a good way (fast, few lines of code) to get any value from the Set?

With a List, it's easy:

List<T> things = ...;
return things.get(0);

But, with a Set, there is no .get(...) method because Sets are not ordered.

Body:
Getting any element from a Set or Collection may seem like an uncommon demand - if not arbitrary or eclectic - but, it is quite common when one, for example, needs to calculate statistics on Keys or Values objects in a Map and must initialise min/max values. The any element from a Set/Collection (returned by Map.keySet() or Map.values()) will be used for this initialisation prior to updating min/max values over each element.

So, what options one has when faced with this problem and at the same time trying to keep memory and execution time small and code clear?

Often you get the usual: "convert Set to ArrayList and get the first element". Great! Another array of millions of items and extra processing cycles to retrieve objects from Set, allocate array and populate it:

HashMap<K,V> map;
List<K> list = new ArrayList<V>(map.keySet()); // min/max of keys
min = max = list.get(0).some_property(); // initialisation step
for(i=list.size();i-->1;){
 if( min > list.get(i).some_property() ){ ... }
 ...
}

Or one may use looping with an Iterator, using a flag to denote that min/max need to be initialised and a conditional statement to check if that flag is set for all the iterations in the loop. This implies a lot of conditional checking.

boolean flag = true;
Iterator it = map.keySet().iterator();
while( it.hasNext() ){
  if( flag ){
    // initialisation step
    min = max = it.next().some_property();
    flag = false;
  } else {
    if( min > list.get(i).some_property() ){ min = list.get(i).some_property() }
  ...
  }
}

Or do the initialisation outside the loop:

HashMap<K,V> map;
Iterator it = map.keySet().iterator();
K akey;
if( it.hasNext() ){
  // initialisation step:
  akey = it.next();
  min = max = akey.value();
  do {
    if( min > list.get(i).some_property() ){ min = akey.some_property() }
  } while( it.hasNext() && ((akey=it.next())!=null) );
}

But is it really worth all this manouvre on the behalf of the programmer (and setting up the Iterator on behalf of the JVM) whenever min/max's needed?

The suggestion from a javally-correct ol' sport could well be: "wrap your Map in a class which keeps track of min and max values when put or deleted!".

There is another situation which in my experience the need for just any item from a Map arises. This is when the map contains objects which have a common property - all the same for all of them in that map - and you need to read that property. For example suppose there is a Map of holding bins of the same histogram which have the same number of dimensions. Given such a Map you may need to know the number of dimensions of just any Histobin in the Map in order to, say, create another Histobin of the same dimensions. Do I need to setup an iterator again and dispose it after calling next() just once? I will skip the javally-correct person's suggestion to this situation.

And if all the trouble in getting the any element causes insignificant memory and cpu cycles increase, then what about all the code one has to write just to get the hard-to-get any element.

We need the any element. Give it to us!


问:
Evenly sized columns between rows using grid/flex
Consider the following snippet:

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-template-columns: repeat(3, auto);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="row">
    <div class="item">A1111</div>
    <div class="item">B1</div>
    <div class="item">C1</div>
  </div>
  <div class="row">
    <div class="item">A2</div>
    <div class="item">B2222</div>
    <div class="item">C2</div>
  </div>
  <div class="row">
    <div class="item">A3</div>
    <div class="item">B3</div>
    <div class="item">C3333</div>
  </div>
</div></code>```

The end result is a table-like display where each item of every row is the width of the widest item in that column.

```<code>A1111 A2    A3
B1    B2222 B3
C1    C2    C3333
</code>```

Which is great - but I need the table laid out as rows...

```<code>A1111 B1    C1
A2    B2222 C2
A3    B3    C3333
</code>```

display: table solves this - but table has some drawbacks around spacing, alignments and so-on. Therefore, grid and flex looks attractive.

Alas I cannot figure out how to get the information laid out as desired.

Adding display: grid to .row helps the order of information, but doesn't retain the equal column widths.

The item content will vary, and so cannot use fixed widths and it is not desired that the grid/flex spans the entire page/containing width.

答:
You can define which column the grid item should be using grid-column. This means the row doesn't require a containing row div.

Working example...

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-auto-flow: row;
  grid-gap: 10px;
  padding: 10px;
}

.col1{
  grid-column: 1;
}

.col2{
  grid-column: 2;
}

.col3{
  grid-column: 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
    <div class="col1">A11111</div>
    <div class="col2">B1</div>
    <div class="col3">C1</div>
    <div class="col1">A2</div>
    <div class="col2">B2222222</div>
    <div class="col3">C2</div>
    <div class="col1">A3</div>
    <div class="col2">B3</div>
    <div class="col3">C33333333</div>
  </div>
</div></code>```

Body:
Consider the following snippet:

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-template-columns: repeat(3, auto);
}

A1111

B1

C1

A2

B2222

C2

A3

B3

C3333

The end result is a table-like display where each item of every row is the width of the widest item in that column.

A1111 A2    A3
B1    B2222 B3
C1    C2    C3333

Which is great - but I need the table laid out as rows...

A1111 B1    C1
A2    B2222 C2
A3    B3    C3333

display: table solves this - but table has some drawbacks around spacing, alignments and so-on. Therefore, grid and flex looks attractive.

Alas I cannot figure out how to get the information laid out as desired.

Adding display: grid to .row helps the order of information, but doesn't retain the equal column widths.

The item content will vary, and so cannot use fixed widths and it is not desired that the grid/flex spans the entire page/containing width.

Body:
You can define which column the grid item should be using grid-column. This means the row doesn't require a containing row div.

Working example...

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-auto-flow: row;
  grid-gap: 10px;
  padding: 10px;
}

.col1{
  grid-column: 1;
}

.col2{
  grid-column: 2;
}

.col3{
  grid-column: 3;
}

<div id="container">
    <div class="col1">A11111</div>
    <div class="col2">B1</div>
    <div class="col3">C1</div>
    <div class="col1">A2</div>
    <div class="col2">B2222222</div>
    <div class="col3">C2</div>
    <div class="col1">A3</div>
    <div class="col2">B3</div>
    <div class="col3">C33333333</div>
  </div>
</div>


问:
how to find the commit message by author?
How can I find the commit message by a specific author?

For example, if we are both working on a project and I want to find the line added by another author for the file hello.java.

答:
Are you looking for the commit message, or for the specific line changed by the commit?

If you're looking for the message, use git log to see all of the commit messages. If you mean the specific code line, KingCrunch has what you want.


问:
SQL Server Integration Services 14 - Only insert if no exists
I've the following workflow in SSIS 14:

Each source have more than million records and I need to execute this workflow everydays at week.

My question is: How can I say to SSIS that I only want to extract only the records that not exists in Table Destination? Like a

```<code>INSERT INTO TABLEA
SELET * FROM TABLEB
EXCEPT SELECT * FROM TABLEA
</code>```

Many thanks!

答: You can use the Lookup transformation to find out if something exists already.</p>

Body:
I've the following workflow in SSIS 14:

Each source have more than million records and I need to execute this workflow everydays at week.

My question is: How can I say to SSIS that I only want to extract only the records that not exists in Table Destination? Like a

INSERT INTO TABLEA
SELET * FROM TABLEB
EXCEPT SELECT * FROM TABLEA

Many thanks!


问:
Django Search bar feature not working?
In my base template I have this search bar. When I search for something it doesn't actually return anything. I'm not sure if the url is correct because I want it to work on every page.

In the base navbar this is the code:

```<code><form class="navbar-form navbar-left" target="_self">
    <div class="form-group">

        <label class="control-label" for="search-field">
        <i class="glyphicon glyphicon-search"></i></label>

        <input type="text/submit" value="{{request.GET.q}}" name="q"
         class="form-control search-field"
         action={% url 'search_posts' %}
         placeholder="Search Airline or Aircraft" id="search-field" />

    </div>
</form>
</code>```

Urls.py

```<code>url(r'^$', search_posts, name='search_posts'),
</code>```

Views.py

```<code>def search_posts(request):
    aircraft = Aircraft.objects.all()
    airline = Airline.objects.all()

    query = request.GET.get("q")
    if query:
        aircraft = aircraft.filter(
        Q(name__icontains=query) |
        Q(description__icontains=query)
        ).distinct()
    return render(request, 'search_post.html', {'aircraft': aircraft})
</code>```

Is it possible to combine two models into a variable? I have Aircraft and Airline. Will this work?

```<code>queryset_list = Aircraft.objects.all() + Airline.objects.all()
</code>```

Views.py Updated

```<code>def search_posts(request):
    aircraft = Aircraft.objects.all()
    airline = Airline.objects.all()
    query = request.GET.get("q")

    aircraft = aircraft.filter(
    Q(name__icontains=query) |
    Q(description__icontains=query)).distinct()

    airline = airline.filter(
    Q(name__icontains=query) |
    Q(description__icontains=query)).distinct()

    return render(request, 'search_post.html', {'aircraft': aircraft,'airline': airline })
</code>```

search_post.html

```<code><div class="team-boxed">
    <div class="container">
        <div class="row aircraft">
          {% for aircraft in aircraft %}
            <div class="col-lg-offset-0 col-md-4 col-sm-3 item">
                <div class="box"><img src="{{ aircraft.image.url }}" />
                    <h3 class="name"><a href="{{ aircraft.get_absolute_url }}">{{ aircraft.name }}</a></h3>
                    <h4><em>Range: {{ aircraft.maximum_range }} NM</em></h4>
                    <h4><em> Passengers: {{ aircraft.passengers }}</em></h4>
                    <h4><em> Speed: {{ aircraft.cruising_speed }} Kt</em></h4>
               </div>
            </div>
        {% endfor %}
        </div>
    </div>
</div>
</code>```

答:
Since HTML input elements do not have an action attribute, remove action={% url 'search_posts' %} from <input> and place it inside the <form> like this:

```<code><form action={% url 'search_posts' %} method="GET" ...>
</code>```

Also remove the type="text/submit" from the input and replace it with just text (in order to present the user a text input box to write the query - thanks Alasdair for that - haven't seen that), like this:

```<code><input type="text" ...>
</code>```

so, the form should look like this:

```<code><form method="GET" action={% url 'search_posts' %} class="navbar-form navbar-left">
    <div class="form-group">
        <label class="control-label" for="search-field">
        <i class="glyphicon glyphicon-search"></i></label>
        <input type="text" value="{{request.GET.q}}" name="q" class="form-control search-field" placeholder="Search Airline or Aircraft" id="search-field" />
    </div>
</form>
</code>```

Concerning the other part of your question, in order to combine two (or more) QuerySets (I can't imagine why you would want to do that), here it is:

```<code>qs = list(Aircraft.objects.all()) + list(Airline.objects.all())
</code>```

Finally in your search_post.html do this:

```<code>{% if aircraft.exists %}
    <div class="team-boxed">
        <div class="container">
            <div class="row aircraft">
                {% for aircraft in aircraft %}
                    <div class="col-lg-offset-0 col-md-4 col-sm-3 item">
                        <div class="box"><img src="{{ aircraft.image.url }}"></div>
                        <h3 class="name"><a href="{{ aircraft.get_absolute_url }}">{{ aircraft.name }}</a></h3>
                        <h4><em>Range: {{ aircraft.maximum_range }} NM</em></h4>
                        <h4><em> Passengers: {{ aircraft.passengers }}</em></h4>
                        <h4><em> Speed: {{ aircraft.cruising_speed }} Kt</em></h4>
                    </div>
                {% endfor %}
            </div>
        </div>
    </div>
{% endif %}

{% if airline.exists %}
    <div class="team-boxed">
        <div class="container">
            <div class="row airline">
                {% for airline in airline %}
                    <div class="col-lg-offset-0 col-md-4 col-sm-3 item">
                        <div class="box"><img src="{{ airline.image.url }}"></div>
                        <h3 class="name"><a href="{{ airline.get_absolute_url }}">{{ airline.name }}</a></h3>
                        <h4><em>Range: {{ airline.maximum_range }} NM</em></h4>
                        <h4><em> Passengers: {{ airline.passengers }}</em></h4>
                        <h4><em> Speed: {{ airline.cruising_speed }} Kt</em></h4>
                    </div>
                {% endfor %}
            </div>
        </div>
    </div>
{% endif %}
</code>```

Title: Django Search bar feature not working?

Body:
In my base template I have this search bar. When I search for something it doesn't actually return anything. I'm not sure if the url is correct because I want it to work on every page.

In the base navbar this is the code:

<form class="navbar-form navbar-left" target="_self">

        <input type="text/submit" value="{{request.GET.q}}" name="q"
         class="form-control search-field"
         action={% url 'search_posts' %}
         placeholder="Search Airline or Aircraft" id="search-field" />

</form>

Urls.py

url(r'^$', search_posts, name='search_posts'),

Views.py

def search_posts(request):
    aircraft = Aircraft.objects.all()
    airline = Airline.objects.all()

    query = request.GET.get("q")
    if query:
        aircraft = aircraft.filter(
        Q(name__icontains=query) |
        Q(description__icontains=query)
        ).distinct()
    return render(request, 'search_post.html', {'aircraft': aircraft})

Is it possible to combine two models into a variable? I have Aircraft and Airline. Will this work?

queryset_list = Aircraft.objects.all() + Airline.objects.all()

Views.py Updated

def search_posts(request):
    aircraft = Aircraft.objects.all()
    airline = Airline.objects.all()
    query = request.GET.get("q")

    aircraft = aircraft.filter(
    Q(name__icontains=query) |
    Q(description__icontains=query)).distinct()

    airline = airline.filter(
    Q(name__icontains=query) |
    Q(description__icontains=query)).distinct()

    return render(request, 'search_post.html', {'aircraft': aircraft,'airline': airline })

search_post.html

          {% for aircraft in aircraft %}

{{ aircraft.name }}

Range: {{ aircraft.maximum_range }} NM

 Passengers: {{ aircraft.passengers }}

 Speed: {{ aircraft.cruising_speed }} Kt

        {% endfor %}

Body:
Since HTML input elements do not have an action attribute, remove action={% url 'search_posts' %} from <input> and place it inside the <form> like this:

<form action={% url 'search_posts' %} method="GET" ...>

Also remove the type="text/submit" from the input and replace it with just text (in order to present the user a text input box to write the query - thanks Alasdair for that - haven't seen that), like this:

<input type="text" ...>

so, the form should look like this:

<form method="GET" action={% url 'search_posts' %} class="navbar-form navbar-left">
    <div class="form-group">
        <label class="control-label" for="search-field">
        <i class="glyphicon glyphicon-search"></i></label>
        <input type="text" value="{{request.GET.q}}" name="q" class="form-control search-field" placeholder="Search Airline or Aircraft" id="search-field" />
    </div>
</form>

Concerning the other part of your question, in order to combine two (or more) QuerySets (I can't imagine why you would want to do that), here it is:

qs = list(Aircraft.objects.all()) + list(Airline.objects.all())

Finally in your search_post.html do this:

{% if aircraft.exists %}
    <div class="team-boxed">
        <div class="container">
            <div class="row aircraft">
                {% for aircraft in aircraft %}
                    <div class="col-lg-offset-0 col-md-4 col-sm-3 item">
                        <div class="box"><img src="{{ aircraft.image.url }}"></div>
                        <h3 class="name"><a href="{{ aircraft.get_absolute_url }}">{{ aircraft.name }}</a></h3>
                        <h4><em>Range: {{ aircraft.maximum_range }} NM</em></h4>
                        <h4><em> Passengers: {{ aircraft.passengers }}</em></h4>
                        <h4><em> Speed: {{ aircraft.cruising_speed }} Kt</em></h4>
                    </div>
                {% endfor %}
            </div>
        </div>
    </div>
{% endif %}

{% if airline.exists %}
    <div class="team-boxed">
        <div class="container">
            <div class="row airline">
                {% for airline in airline %}
                    <div class="col-lg-offset-0 col-md-4 col-sm-3 item">
                        <div class="box"><img src="{{ airline.image.url }}"></div>
                        <h3 class="name"><a href="{{ airline.get_absolute_url }}">{{ airline.name }}</a></h3>
                        <h4><em>Range: {{ airline.maximum_range }} NM</em></h4>
                        <h4><em> Passengers: {{ airline.passengers }}</em></h4>
                        <h4><em> Speed: {{ airline.cruising_speed }} Kt</em></h4>
                    </div>
                {% endfor %}
            </div>
        </div>
    </div>
{% endif %}


问:
Maintain sessions in Node.js
How can I maintain my SESSIONS in Node.js?

For example, I want to store UserID in SESSION using Node.js. How can I do that in Node.js? And can I use that Node.js SESSION in PHP too?

I want the following in Node.js:

```<code><?php $_SESSION['user'] = $userId; ?>
</code>```

答:
You can handle the session in two ways.

Using express-session

Using JWT web token and handle your own session (token-based session handling).

I think token-based session handling is more important rather than using express-session. You will get a problem when you scale your server and also a problem with some single device login situation.

For checking I have a token-based session handling Node.js folder structure. You can check it, and it may be helpful.

Title: Maintain sessions in Node.js

Body:
How can I maintain my SESSIONS in Node.js?

For example, I want to store UserID in SESSION using Node.js. How can I do that in Node.js? And can I use that Node.js SESSION in PHP too?

I want the following in Node.js:

<?php $_SESSION['user'] = $userId; ?>


问:
Make elasticsearch only return certain fields?
I'm using elasticsearch to index my documents.

Is it possible to instruct it to only return particular fields instead of the entire json document it has stored?

答:
In Elasticsearch 5.x the above mentioned approach is deprecated.
You can use the _source approach, but but in certain situations it can make sense to store a field. For instance, if you have a document with a title, a date, and a very large content field, you may want to retrieve just the title and the date without having to extract those fields from a large _source field:

In this case, you'd use:

```<code>{
   "size": $INT_NUM_OF_DOCS_TO_RETURN,
   "stored_fields":[
      "doc.headline",
      "doc.text",
      "doc.timestamp_utc"
   ],
   "query":{
      "bool":{
         "must":{
            "term":{
               "doc.topic":"news_on_things"
            }
         },
         "filter":{
            "range":{
               "doc.timestamp_utc":{
                  "gte":1451606400000,
                  "lt":1483228800000,
                  "format":"epoch_millis"
               }
            }
         }
      }
   },
   "aggs":{

   }
}
</code>```

See the documentation on how to index stored fields.
Always happy for an Upvote!

Body:
In Elasticsearch 5.x the above mentioned approach is deprecated.
You can use the _source approach, but but in certain situations it can make sense to store a field. For instance, if you have a document with a title, a date, and a very large content field, you may want to retrieve just the title and the date without having to extract those fields from a large _source field:

In this case, you'd use:

{
   "size": $INT_NUM_OF_DOCS_TO_RETURN,
   "stored_fields":[
      "doc.headline",
      "doc.text",
      "doc.timestamp_utc"
   ],
   "query":{
      "bool":{
         "must":{
            "term":{
               "doc.topic":"news_on_things"
            }
         },
         "filter":{
            "range":{
               "doc.timestamp_utc":{
                  "gte":1451606400000,
                  "lt":1483228800000,
                  "format":"epoch_millis"
               }
            }
         }
      }
   },
   "aggs":{

   }
}

See the documentation on how to index stored fields.
Always happy for an Upvote!


问:
Printing debug values in a cryptographic exchange
I have created this basic program to implement the Diffie-Hellman algorithm. I want s to be a randomly generated prime number, and q to be a randomly generated integer. sk1 and sk2 are shared keys which are also generated randomly. pk1 and pk2 are modulus calculated values which I have to prove are equal to each other. I think my formula is correct but I am not sure how to print the values of s, q, sk1, sk2, pk1 and pk2 to verify my requirements. My code is pasted below and I would really appreciate if anyone could help me with the print statements.

package javaapplication1;
import java.util.Random;
import java.math.*;

public class DH {
    public static void main(String [] arg) {

        int s, q;
        double sk1, sk2, pk1 = 0, pk2 = 0;
        Random generator = new Random();
        s = generator.nextInt(50000);
        q = generator.nextInt(50000);

        sk1 = generator.nextInt();
        sk2 = generator.nextInt();

        if(s==1 || s==2) {
            for(int i = 2; i< (int)(s/2); i++) {
                if(s/i != (int)(s/i)) {
                    double a= Math.pow(q,sk1);
                    pk1 = a%s;

                    double b= Math.pow(q, sk2);
                    pk2 = b%s;

                    if(pk1==pk2) {
                        System.out.println("true");
                    }

                    System.out.println(s);
                    System.out.println(q);
                    System.out.println(sk1);
                    System.out.println(sk2);
                    System.out.println(pk1);
                    System.out.println(pk2);
                }
            }
        }
    }
}
```

答:
As s an intger generated by:

```<code>s = generator.nextInt(50000);
</code>```

There is a 25,000 to 1 chance that :

```<code>if(s==1 || s==2) {
</code>```

will ever be true.
Perhaps yo umeant if s > 2?

Body:
As s an intger generated by:

s = generator.nextInt(50000);

There is a 25,000 to 1 chance that :

if(s==1 || s==2) {

will ever be true.
Perhaps yo umeant if s > 2?


问:
QML Rendering Engine: frame refresh event
Performance Considerations And Suggestions article says:

As an application developer, you must strive to allow the rendering
  engine to achieve a consistent 60 frames-per-second refresh rate. 60
  FPS means that there is approximately 16 milliseconds between each
  frame in which processing can be done, which includes the processing
  required to upload the draw primitives to the graphics hardware.

Is there an event or signal or any form of callback to make the code be called with that refresh?

The goal is to eliminate the need for handling the signal from the rendering thread in the UI thread slot. If the new data arrived then it will be drawn or marked for the next refresh to be drawn (with update() call).

答: QQuickWindow has a bunch of signals for the purpose of synchronization -  beforeRendering(), afterRendering(), beforeSynchronizing(), afterSynchronizing(), frameSwapped(). Take your pick.


问:
How to execute query over Amazon Athena with Ruby?
how to connect Amazon Athena with Ruby and execute query over Amazon Athena and get result.

we not able to find any gem or example with help us to connect Amazon Athena in ruby.

Please provide any reference using which we can use to build connection with Amazon Athena and build a custom query executor in Ruby.

just to clarify my application on production so changing SDK from Ruby to JRuby is not a suitable option for me.

答: JRuby is required. Athena offers only JDBC driver. It works only in JRE.</p>


问:
How to truncate or pad a string to a fixed length in c#
Is there a one-liner way of setting a string to a fixed length (in C#), either by truncating it or padding it with spaces (' ').

For example:

```<code>string s1 = "abcdef";
string s2 = "abc";
</code>```

after setting both to length 5, we should have:

```<code>"abcde"
"abc  "
</code>```

答:
All you need is PadRight followed by Substring (providing that source is not null):

```<code>string source = ...
int length = 5;

string result = source.PadRight(length).Substring(0, length);
</code>```

In case source can be null:

```<code>string result = source == null
  ? new string(' ', length)
  : source.PadRight(length).Substring(0, length);
</code>```

Body:
Is there a one-liner way of setting a string to a fixed length (in C#), either by truncating it or padding it with spaces (' ').

For example:

string s1 = "abcdef";
string s2 = "abc";

after setting both to length 5, we should have:

"abcde"
"abc  "

Body:
All you need is PadRight followed by Substring (providing that source is not null):

string source = ...
int length = 5;

string result = source.PadRight(length).Substring(0, length);

In case source can be null:

string result = source == null
  ? new string(' ', length)
  : source.PadRight(length).Substring(0, length);


问:
How to set null if relations doesn't exist?
In Model I have:

```<code>public function publisher()
{
    return $this->belongsTo('App\User', 'user_id', 'id');
}
</code>```

In template blade I try to show data User:

```<code>@foreach($announcement->offers as $key => $item)
    <img src="{{url($item->publisher->photo)}}">
@endforeach
</code>```

The Problem is that if there is no data in the User table, the program crashes because I can not get the property $item->publisher->photo.

How to fix it?

答:
Working on memory here, but you could use @forelse/ @empty. These directives can be used if the object your'e iterating over is empty:

```<code>@forelse($announcement->offers as $key => $item)
    <img src="{{url($item->publisher->photo)}}">
@empty
    //default image or message?
@endforelse
</code>```

https://laravel.com/docs/5.4/blade#loops

Body:
In Model I have:

public function publisher()
{
    return $this->belongsTo('App\User', 'user_id', 'id');
}

In template blade I try to show data User:

@foreach($announcement->offers as $key => $item)
    publisher->photo)}}">
@endforeach

The Problem is that if there is no data in the User table, the program crashes because I can not get the property $item->publisher->photo.

How to fix it?

Body:
Working on memory here, but you could use @forelse/ @empty. These directives can be used if the object your'e iterating over is empty:

@forelse($announcement->offers as $key => $item)
    <img src="{{url($item->publisher->photo)}}">
@empty
    //default image or message?
@endforelse

https://laravel.com/docs/5.4/blade#loops


问:
How to i get ruby to return json response to be used in rails controller
I'm working with an Api, so far so good i am able to send requests and receive response, but i want the ruby code to send the json response and message that can be accessible from my rails controller so that i can get simple_form to render the error or success messages and also handle redirection from the rails controller, i also want to save transaction details from the response in a model, here's my lib code

```<code>class SimplePay
  require 'net/https'
  require 'uri'
  require 'json'

  def self.pay(api_key, token, amount, amount_currency, status)
    uri = URI.parse('https://checkout.simplepay.ng/v2/payments/card/charge/')
    header = {'Content-Type': 'text/json'}
    data = {
        'token': token,
        'amount': amount,
        'amount_currency': amount_currency
    }
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Post.new(uri.request_uri, header)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    request = Net::HTTP::Post.new(uri.request_uri, header)
    request.basic_auth(api_key, '')
    request.set_form_data(data)

    response = http.request(request)
    res = JSON.parse(response.read_body)
    response_code =  res['response_code']
    if response.kind_of? Net::HTTPSuccess
      if response_code.eql? 20000
        puts 'success'
      else
        puts 'Failed'
      end
    elsif status.eql? true
      puts 'Success But Not Charged'
    elsif status.eql? false
      raise error 'Failed To Charge Card'
    elsif response.kind_of? Net::HTTPBadRequest
      raise error 'Failed 400'
    elsif response.kind_of? Net::HTTPError
      raise error 'Failed 404'
    else
      raise error 'Unknown Error'
    end
  end
end
</code>```

How do i go about achieving this?

答: I would say send a Hash to the controller and then when you are sending it just doing a .to_json will make it into a json

Body:
I'm working with an Api, so far so good i am able to send requests and receive response, but i want the ruby code to send the json response and message that can be accessible from my rails controller so that i can get simple_form to render the error or success messages and also handle redirection from the rails controller, i also want to save transaction details from the response in a model, here's my lib code

class SimplePay
  require 'net/https'
  require 'uri'
  require 'json'

  def self.pay(api_key, token, amount, amount_currency, status)
    uri = URI.parse('https://checkout.simplepay.ng/v2/payments/card/charge/')
    header = {'Content-Type': 'text/json'}
    data = {
        'token': token,
        'amount': amount,
        'amount_currency': amount_currency
    }
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Post.new(uri.request_uri, header)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    request = Net::HTTP::Post.new(uri.request_uri, header)
    request.basic_auth(api_key, '')
    request.set_form_data(data)

    response = http.request(request)
    res = JSON.parse(response.read_body)
    response_code =  res['response_code']
    if response.kind_of? Net::HTTPSuccess
      if response_code.eql? 20000
        puts 'success'
      else
        puts 'Failed'
      end
    elsif status.eql? true
      puts 'Success But Not Charged'
    elsif status.eql? false
      raise error 'Failed To Charge Card'
    elsif response.kind_of? Net::HTTPBadRequest
      raise error 'Failed 400'
    elsif response.kind_of? Net::HTTPError
      raise error 'Failed 404'
    else
      raise error 'Unknown Error'
    end
  end
end

How do i go about achieving this?


问:
Spark read file from S3 using sc.textFile ("s3n://...)
Trying to read a file located in S3 using spark-shell:

```<code>scala> val myRdd = sc.textFile("s3n://myBucket/myFile1.log")
lyrics: org.apache.spark.rdd.RDD[String] = s3n://myBucket/myFile1.log MappedRDD[55] at textFile at <console>:12

scala> myRdd.count
java.io.IOException: No FileSystem for scheme: s3n
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2607)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2614)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:91)
    ... etc ...
</code>```

The IOException: No FileSystem for scheme: s3n error occurred with:

Spark 1.31 or 1.40 on dev machine (no Hadoop libs)

Running from the Hortonworks Sandbox HDP v2.2.4 (Hadoop 2.60) which integrates Spark 1.2.1 out of the box

Using s3:// or s3n:// scheme

What is the cause of this error? Missing dependency, Missing configuration, or mis-use of sc.textFile()?

Or may be this is due to a bug that affects Spark build specific to Hadoop 2.60 as this post seems to suggest. I am going to try Spark for Hadoop 2.40 to see if this solves the issue.

答:
USe s3a instead of s3n. I had similar issue on a Hadoop job. After switching from s3n to s3a it worked.

e.g.

s3a://myBucket/myFile1.log

Body:
Trying to read a file located in S3 using spark-shell:

scala> val myRdd = sc.textFile("s3n://myBucket/myFile1.log")
lyrics: org.apache.spark.rdd.RDD[String] = s3n://myBucket/myFile1.log MappedRDD[55] at textFile at <console>:12

scala> myRdd.count
java.io.IOException: No FileSystem for scheme: s3n
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2607)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2614)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:91)
    ... etc ...

The IOException: No FileSystem for scheme: s3n error occurred with:

Spark 1.31 or 1.40 on dev machine (no Hadoop libs)

Running from the Hortonworks Sandbox HDP v2.2.4 (Hadoop 2.60) which integrates Spark 1.2.1 out of the box

Using s3:// or s3n:// scheme

What is the cause of this error? Missing dependency, Missing configuration, or mis-use of sc.textFile()?

Or may be this is due to a bug that affects Spark build specific to Hadoop 2.60 as this post seems to suggest. I am going to try Spark for Hadoop 2.40 to see if this solves the issue.


问:
Remove non-text chars (like emoticons) from string
How can I replace chars like  from a string? Sometime the YouTube video title contains characters like this. I don't want to replace characters like !@#$%^&*().

I am currently using preg_replace('/[^A-Za-z0-9\-]/', '', $VideoTitle);

Samples Array:

```<code>$VideoTitles[]='Sia 2017 Cheap Thrills 2017 live ';

$VideoTitles[]='TAYLOR SWIFT - SHAKE IT OFF  #1989';
</code>```

Expected Output:

```<code>Sia 2017 Cheap Thrills 2017 live
TAYLOR SWIFT - SHAKE IT OFF #1989
</code>```

答:
```<code>function removeEmoticon($text) {

    $cleanText = "";

    // Match Emoticons
    $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
    $cleanText     = preg_replace($regexEmoticons, '', $text);

    // Match Miscellaneous Symbols and Pictographs
    $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
    $cleanText   = preg_replace($regexSymbols, '', $cleanText);

    // Match Transport And Map Symbols
    $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
    $cleanText     = preg_replace($regexTransport, '', $cleanText);

    // Match Miscellaneous Symbols
    $regexMisc  = '/[\x{2600}-\x{26FF}]/u';
    $cleanText = preg_replace($regexMisc, '', $cleanText);

    // Match Dingbats
    $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
    $cleanText    = preg_replace($regexDingbats, '', $cleanText);

    return $cleanText;
}
</code>```

Body:
How can I replace chars like  from a string? Sometime the YouTube video title contains characters like this. I don't want to replace characters like !@#$%^&*().

I am currently using preg_replace('/[^A-Za-z0-9\-]/', '', $VideoTitle);

Samples Array:

$VideoTitles[]='Sia 2017 Cheap Thrills 2017 live ';

$VideoTitles[]='TAYLOR SWIFT - SHAKE IT OFF  #1989';

Expected Output:

Sia 2017 Cheap Thrills 2017 live
TAYLOR SWIFT - SHAKE IT OFF #1989


问:
matched brackets showed as unmatched
```<code>convertToClockTime <- function(file, lag = Latency) {
  colnames(adamcorrectfile)[which(colnames(adamcorrectfile) == "X.1")] <- "Calculated.Run.Time"
  adamcorrectfile$Calculated.Run.Time <- round(adamcorrectfile$Calculated.Run.Time, digits = 0)
  adamcorrectfile$LPRS.Time <- as.POSIXct(adamcorrectfile$LPRS.Time, format = "%H:%M")

  adamcorrectfile <- adamcorrectfile[order(adamcorrectfile$LPRS.Time),]
  output <- colnames(adamcorrectfile)
  for (j in unique(adamcorrectfile$Folder)) {
    adamcorrectfile.Folder <- adamcorrectfile[which(adamcorrectfile$Folder == "print 1"),]
    adamcorrectfile.Folder$start.time <- adamcorrectfile.Folder$LPRS.Time + lag
    adamcorrectfile.Folder$end.time <- adamcorrectfile.Folder$start.time + adamcorrectfile.Folder$`Calculated.Run.Time`
    for (i in 2:nrow(adamcorrectfile)) {
      adamcorrectfile.Folder[i,"start.time"] <- max(adamcorrectfile.Folder[i,"LPRS.Time"] + 15*60, adamcorrectfile[i-1, "end.time"]
                                                    adamcorrectfile.Folder[i, "end.time"] <- adamcorrectfile.Folder[i,"start.time"] + adamcorrectfile.Folder[i,"Calculated.Run.Time"]
        }
  output <- rbind(output, adamcorrectfile.Folder)
  return(output)
      }
  }
</code>```

On line 1 it says unmatched opening bracket '{' even though it is matched. Any help. Are there some tricky things with R indentation, it just keeps popping errors due to indentations it seems

答:
It looks like the problem is that you haven't closed the parentheses on the max function in the middle of the for loop.

Here is the working code:

```<code>convertToClockTime <- function(file, lag = Latency) {
        colnames(adamcorrectfile)[which(colnames(adamcorrectfile) == "X.1")] <- "Calculated.Run.Time"
        adamcorrectfile$Calculated.Run.Time <- round(adamcorrectfile$Calculated.Run.Time, digits = 0)
        adamcorrectfile$LPRS.Time <- as.POSIXct(adamcorrectfile$LPRS.Time, format = "%H:%M")

        adamcorrectfile <- adamcorrectfile[order(adamcorrectfile$LPRS.Time),]
        output <- colnames(adamcorrectfile)
        for (j in unique(adamcorrectfile$Folder)) {
                adamcorrectfile.Folder <- adamcorrectfile[which(adamcorrectfile$Folder == "print 1"),]
                adamcorrectfile.Folder$start.time <- adamcorrectfile.Folder$LPRS.Time + lag
                adamcorrectfile.Folder$end.time <- adamcorrectfile.Folder$start.time + adamcorrectfile.Folder$`Calculated.Run.Time`
                for (i in 2:nrow(adamcorrectfile)) {
                   adamcorrectfile.Folder[i,"start.time"] <- max(adamcorrectfile.Folder[i,"LPRS.Time"] + 15*60, adamcorrectfile[i-1, "end.time"])
                   adamcorrectfile.Folder[i, "end.time"] <- adamcorrectfile.Folder[i,"start.time"] + adamcorrectfile.Folder[i,"Calculated.Run.Time"]
                }
                output <- rbind(output, adamcorrectfile.Folder)
                return(output)
        }
        }
</code>```

Title: matched brackets showed as unmatched

Body:
convertToClockTime <- function(file, lag = Latency) {
  colnames(adamcorrectfile)[which(colnames(adamcorrectfile) == "X.1")] <- "Calculated.Run.Time"
  adamcorrectfile$Calculated.Run.Time <- round(adamcorrectfile$Calculated.Run.Time, digits = 0)
  adamcorrectfile$LPRS.Time <- as.POSIXct(adamcorrectfile$LPRS.Time, format = "%H:%M")

  adamcorrectfile <- adamcorrectfile[order(adamcorrectfile$LPRS.Time),]
  output <- colnames(adamcorrectfile)
  for (j in unique(adamcorrectfile$Folder)) {
    adamcorrectfile.Folder <- adamcorrectfile[which(adamcorrectfile$Folder == "print 1"),]
    adamcorrectfile.Folder$start.time <- adamcorrectfile.Folder$LPRS.Time + lag
    adamcorrectfile.Folder$end.time <- adamcorrectfile.Folder$start.time + adamcorrectfile.Folder$`Calculated.Run.Time`
    for (i in 2:nrow(adamcorrectfile)) {
      adamcorrectfile.Folder[i,"start.time"] <- max(adamcorrectfile.Folder[i,"LPRS.Time"] + 15*60, adamcorrectfile[i-1, "end.time"]
                                                    adamcorrectfile.Folder[i, "end.time"] <- adamcorrectfile.Folder[i,"start.time"] + adamcorrectfile.Folder[i,"Calculated.Run.Time"]
        }
  output <- rbind(output, adamcorrectfile.Folder)
  return(output)
      }
  }

On line 1 it says unmatched opening bracket '{' even though it is matched. Any help. Are there some tricky things with R indentation, it just keeps popping errors due to indentations it seems

Body:
It looks like the problem is that you haven't closed the parentheses on the max function in the middle of the for loop.

Here is the working code:

convertToClockTime <- function(file, lag = Latency) {
        colnames(adamcorrectfile)[which(colnames(adamcorrectfile) == "X.1")] <- "Calculated.Run.Time"
        adamcorrectfile$Calculated.Run.Time <- round(adamcorrectfile$Calculated.Run.Time, digits = 0)
        adamcorrectfile$LPRS.Time <- as.POSIXct(adamcorrectfile$LPRS.Time, format = "%H:%M")

        adamcorrectfile <- adamcorrectfile[order(adamcorrectfile$LPRS.Time),]
        output <- colnames(adamcorrectfile)
        for (j in unique(adamcorrectfile$Folder)) {
                adamcorrectfile.Folder <- adamcorrectfile[which(adamcorrectfile$Folder == "print 1"),]
                adamcorrectfile.Folder$start.time <- adamcorrectfile.Folder$LPRS.Time + lag
                adamcorrectfile.Folder$end.time <- adamcorrectfile.Folder$start.time + adamcorrectfile.Folder$`Calculated.Run.Time`
                for (i in 2:nrow(adamcorrectfile)) {
                   adamcorrectfile.Folder[i,"start.time"] <- max(adamcorrectfile.Folder[i,"LPRS.Time"] + 15*60, adamcorrectfile[i-1, "end.time"])
                   adamcorrectfile.Folder[i, "end.time"] <- adamcorrectfile.Folder[i,"start.time"] + adamcorrectfile.Folder[i,"Calculated.Run.Time"]
                }
                output <- rbind(output, adamcorrectfile.Folder)
                return(output)
        }
        }


问:
Is XHTML really Xtensible?
Is there any way (server- or client-side) that I can actually extend HTML to include new tags?  For example, it would be cool if I could write something like a schema fragment that defined a blogpost, which contains a postname, a postauthor, a posttime, and a postcontent, and thereafter refer to blogpost in my HTML rather than resorting to the basic HTML div and p tags.

答:
You can add custom tags by mixing XHTML with your custom language. The language is no longer XHTML but a compound language including XHTML, but that was always the intent of XHTML anyway.

You will, however need to use XHTML properly, and serve it with an XML mime type, such as application/xhtml+xml, which means no IE support before IE9.

You can see an example using blogpost, postname, postauthor etc here:

http://www.alohci.net/application/xhtml+xml/custom1.xhtml.ashx

(Works in Firefox, Chrome, Safari, Opera and IE9)

[Of course, you can just put invalid tags into HTML and style them, but to me, that doesn't seem to me to be the point of question, which was specifically about the extensibility nature of XHTML.]

Title: Is XHTML really Xtensible?


问:
Can I store image in array?
I want to save photos from photo gallery in my app and after show them in collection View. Is there some way to store this image in array in UserDefaults? </p>

答:
I would use Core Data and/or store them locally.

see the responses in:
Saving Picked Image to CoreData

NSUserDefaults should only be used for the applications default values.

Title: Can I store image in array?


问:
"The public type must be defined in its own file" but the file name and the class name is the same
```<code>import java.util.StringTokenizer;

public class josimarleewords {

    private static String[] tokenize(String str) {
        StringTokenizer tokenizer = new StringTokenizer(str);
        String[] arr = new String[tokenizer.countTokens()];
        int i = 0;
        while (tokenizer.hasMoreTokens()) {
            arr[i++] = tokenizer.nextToken();
        }
        return arr;
    }

    public static void main(String[] args) {
        String[] strs = tokenize("He said, That's not a good idea.");
        for (String s : strs)
            System.out.println(s);
    }
}
</code>```

答: If your file is called Josimarleewords.java, then your class must be called Josimarleewords. Make sure you capitalize the first letter. </p>


问:
Powerpoint change picture without changing cropping area
I´ve a cropped picture in a powerpoint layer and I want to change the picture without changing the size of the cropping area.
If I change the image by clicking "change picture" the cropping area resizes too, to show the whole picture.
How can I do that without changing the cropping area?

In Apple Keynote you only have to drag the picture you want to the cropping area and you only have to align it.

答:
In my experience, a picture that you insert to replace an existing one, using Change Picture, will "inherit" the crop&size settings of the old picture IF the old&new images are actually of the same size (in pixels) - if not, the new one will revert to the default crop&size so you will have to redo these manually.

This changes if the image to-be-replaced has any crop setting applied to it in Powerpoint. In this case, the replacing image will not inherit those, and might also be inserted with a different size&position, leading most likely to an unwanted result & further work needed.

A workaround I found is to first remove the crop setting from the old picture, replace with new image, then reapply the crop. This is still less work than having to manually redo the size&position (or to define these based on numbers copied from the PropertiesPane of the old image).


问:
Can I use getElementById() in a Maps infowindow in JavaScript?
I have an several markers placed on a Google Maps map and every marker has an infowindow with the following content:

```<code>            // Set the content of the infowindow of the marker.
            var infoContent =
              '<div id="iw-container" class="gm-style-iw">'+
                '<div class="iw-title">'+
                  '<p>{{place.name}}</p>'+
                '</div>'+
                // For each photo associated with this place, add it.
                '<div class="container-fluid">'+
                  {% for photo in place.photo_set.all %}
                    '<div class="row">'+
                      '<div class="col-md-4">'+
                        '<hr>'+
                        '<div class="">'+
                        // Check whether the attributes have a value and display them.
                          {% if photo.info != "" and photo.info != None  %}
                            '<p class="iw-info">{{ photo.info }}</p>'+
                          {% endif %}
                          {% if photo.year != "" and photo.year != None  %}
                            '<p class="iw-year">{{ photo.year }}</p>'+
                          {% endif %}
                          {% if photo.source != "" and photo.source != None  %}
                            '<p class="iw-source">Bron: {{ photo.source }}</p>'+
                          {% endif %}
                        '</div>'+
                        // Display the image with a link to the modal view.
                        '<div class="iw-image">'+
                          '<img id="{{ photo.id }}" class="iw-image" src="../static/images/{{ photo.image }}">'+
                        '</div>'+
                      '</div>'+
                    '</div>'+
                  {% endfor %}
                '</div>'+
              '</div>';
</code>```

I want to add a modal view for every image in every infowindow, but I can not do this:

```<code>var img = document.getElementById("{{ photo.id }}");
</code>```

This is because every time the img variable is Null.

Is it possible to access infowindow content with getElementById()?

答:
<s>Where are you calling document.getElementById("{{ photo.id }}")?</s>

I was able to do something similar by returning a div with an Id in the InfoWidow and calling document.getElementById() in onMarkerClick.

Body:
I have an several markers placed on a Google Maps map and every marker has an infowindow with the following content:

            // Set the content of the infowindow of the marker.
            var infoContent =
              '
'+
                '
'+
                  '
{{place.name}}
'+
                '
'+
                // For each photo associated with this place, add it.
                '
'+
                  {% for photo in place.photo_set.all %}
                    '
'+
                      '
'+
                        '
'+
                        '
'+
                        // Check whether the attributes have a value and display them.
                          {% if photo.info != "" and photo.info != None  %}
                            '
{{ photo.info }}
'+
                          {% endif %}
                          {% if photo.year != "" and photo.year != None  %}
                            '
{{ photo.year }}
'+
                          {% endif %}
                          {% if photo.source != "" and photo.source != None  %}
                            '
Bron: {{ photo.source }}
'+
                          {% endif %}
                        '
'+
                        // Display the image with a link to the modal view.
                        '
'+
                          ''+
                        '
'+
                      '
'+
                    '
'+
                  {% endfor %}
                '
'+
              '
';

I want to add a modal view for every image in every infowindow, but I can not do this:

var img = document.getElementById("{{ photo.id }}");

This is because every time the img variable is Null.

Is it possible to access infowindow content with getElementById()?


问:
Redirect if Resolve fails Angular 2
How Can I redirect to another page if the resolve fails in Angular 2?
I call this resolve for my Edit Page, but I want to handle the errors in the Resolve Page

My Resolve:

 resolve(route: ActivatedRouteSnapshot): Promise<any>|boolean {

        return new Promise((resolve, reject) => {

            if (route.params['id'] !== undefined) {
                this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id'])
                    .subscribe(
                     result => {
                            console.log("ok");
                            return resolve(result);
                    },
                    error => {
                return resolve(error);
            });
    }});
```

答:
Just like in the docs, calling this.router.navigate(["url"])... (think to inject Router in your constructor)

class MyResolve {

  constructor(private router: Router) {}

  resolve(route: ActivatedRouteSnapshot): Observable <any> {
    return this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id'])
      .pipe(catchError(err => {
        this.router.navigate(["/404"]);
        return EMPTY;
      }));
  }
}
```

Title: Redirect if Resolve fails Angular 2


问:
What Type of Random Number Generator is Used in the Casino Gaming Industry?
Given the extremely high requirements for unpredictability to prevent casinos from going bankrupt, what random number generation algorithm and seeding scheme is typically used in devices like slot machines, video poker machines, etc.?

EDIT: Related questions:

Do stateless random number generators exist?

True random number generator

Alternative Entropy Sources

答:
There are many things that the gaming sites have to consider when choosing/implementing an RNG.  Without due dilligence, it can go spectacularly wrong.

To get a licence to operate a gaming site in a particular jurisdiction usually requires that the RNG has been certified by an independent third-party.  The third-party testers will analyse the source code and run statistical tests (e.g. Diehard) to ensure that the RNG behaves randomly.  Reputable poker sites will usually include details of the certification that their RNG has undergone (for example: PokerStars's RNG page).

I've been involved in a few gaming projects, and for one of them I had to design and implement the RNG part, so I had to investigate all of these issues.  Most poker sites will use some hardware device for entropy, but they won't rely on just hardware.  Usually it will be used in conjunction with a pseudo-RNG (PRNG).  There are two main reasons for this.  Firstly, the hardware is slow, it can only extract a certain number of bits of entropy in a given time period from whatever physical process it is monitoring.  Secondly, hardware fails in unpredictable ways that software PRNGs do not.

Fortuna is the state of the art in terms of cryptographically strong PRNGs.  It can be fed entropy from one or more external sources (e.g. a hardware RNG) and is resilient in the face of attempted exploits or RNG hardware failure.  It's a decent choice for gaming sites, though some might argue it is overkill.

Pokerroom.com used to just use Java's SecureRandom (they probably still do, but I couldn't find details on their site).  This is mostly good enough, but it does suffer from the degrees of freedom problem.

Most stock RNG implementations (e.g. Mersenne Twister) do not have sufficient degrees of freedom to be able to generate every possible shuffle of a 52-card deck from a given initial state (this is something I tried to explain in a previous blog post).

EDIT: I've answered mostly in relation to online poker rooms and casinos, but the same considerations apply to physical video poker and video slots machines in real world casinos.

OwnerDisplayName: dsimcha

LastEditorDisplayName: strager

OwnerDisplayName: Dan Dyer

LastEditorDisplayName: Dan Dyer


问:
Nhibernate fail to delete Value Object that has null property value
i faced this sort of problem with nhibernate:

when i try to delete a component (object that as no ID) that has null as value of a property, operation fails because condition is translated as field = NULL instead of Field IS NULL

i have the RilevanzaFinding object mapped as component of Finding:

```<code>HasMany<RilevanzaFinding>(x => x.Rilevanze)
        .Access.CamelCaseField(Prefix.Underscore)
        .Table("RilevanzaFinding_T045")
        .KeyColumn("int_T045_IdFinding")
        .Cascade.AllDeleteOrphan()
        .AsSet()
        .Component(fee =>
        {
            fee.References<Rating>(x => x.Rating).Column("int_T045_IdRating").Fetch.Join();
            fee.Map(x => x.DataFine)
                .Column("dte_T045_DataFine")
                .CustomSqlType("Date");
            fee.Map(x => x.Note)
                .Column("nvc_T045_Note")
                .Length(100000);
        });

public class Finding : BaseObject<Finding, int>
{
    private ICollection<RilevanzaFinding> _rilevanze = new List<RilevanzaFinding>();
    public virtual IEnumerable<RilevanzaFinding> Rilevanze
    {
        get
        {
            return _rilevanze.ToArray();
        }
    }
}

public class RilevanzaFinding : EquatableObject<RilevanzaFinding>
{
    public virtual Rating Rating { get; set; }
    public virtual DateTime? DataFine{ get; set; }
    public virtual string Note { get; set; }
}
</code>```

where EquatableObject implements this Equals:

```<code>public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        TObject other = obj as TObject;

        return Equals(other);

    }

    public virtual bool Equals(TObject other)
    {
        if (other == null)
            return false;

        Type t = GetType();

        TypeInfo typeInfo = t.GetTypeInfo();
        IEnumerable<FieldInfo> fields = typeInfo.DeclaredFields.Where(x => x.FieldType.Name != typeof(ICollection<>).Name);
        foreach (FieldInfo field in fields)
        {
            object value1 = field.GetValue(other);
            object value2 = field.GetValue(this);

            if (value1 == null)
            {
                if (value2 != null)
                    return false;
            }
            else if (!value1.Equals(value2))
                return false;
        }
        return true;
    }
</code>```

now when i remove a Rilevanza from a collection of a finding Rilevanze tis is the sql generated by nhibernate:

```<code>NHibernate: DELETE FROM RilevanzaFinding_T045 WHERE int_T045_IdFinding =
@p0 AND dte_T045_DataFine = @p1 AND nvc_T045_Note = @p2 AND int_T045_IdRating
 = @p3;@p0 = 201 [Type: Int32 (0:0:0)], @p1 = NULL [Type: DateTime (0:0:0)], @p2 = 'GD675PFN2GTR9EUJ3JHPG7XFX' [Type: String (1073741823:0:0)],
@p3 = 243 [Type: Int32 (0:0:0)]
</code>```

wich fails due to "dte_T045_DataFine = NULL" condition, since it would be "dte_T045_DataFine IS NULL"

how can i make it write the right condition?

答:
You cannot with a set and NHibernate v5.1 or former.

From NHibernate reference documentation (v5.1 and below):

Please note that a composite element mapping doesn't support null-able
  properties if you're using a <set>. NHibernate has to use each columns
  value to identify a record when deleting objects (there is no separate
  primary key column in the composite element table), which is not
  possible with null values. You have to either use only not-null
  properties in a composite-element or choose a <list>, <map>, <bag> or
  <idbag>.

Better map an entity than a component for this case, and add a primary key to your table, in my opinion. Your SQL will perform better by the way.

From NHibernate v4.1, null equality semantic support was added to filtering queries with NH-3634. But the delete case was still not supported.

From NHibernate v5.2 (which should be available in 2018, Q3), the delete case does now support it too (#1170).

So another solution will be to upgrade to NHibernate v5.2.

Body:
i faced this sort of problem with nhibernate:

when i try to delete a component (object that as no ID) that has null as value of a property, operation fails because condition is translated as field = NULL instead of Field IS NULL

i have the RilevanzaFinding object mapped as component of Finding:

HasMany<RilevanzaFinding>(x => x.Rilevanze)
        .Access.CamelCaseField(Prefix.Underscore)
        .Table("RilevanzaFinding_T045")
        .KeyColumn("int_T045_IdFinding")
        .Cascade.AllDeleteOrphan()
        .AsSet()
        .Component(fee =>
        {
            fee.References<Rating>(x => x.Rating).Column("int_T045_IdRating").Fetch.Join();
            fee.Map(x => x.DataFine)
                .Column("dte_T045_DataFine")
                .CustomSqlType("Date");
            fee.Map(x => x.Note)
                .Column("nvc_T045_Note")
                .Length(100000);
        });

public class Finding : BaseObject<Finding, int>
{
    private ICollection<RilevanzaFinding> _rilevanze = new List<RilevanzaFinding>();
    public virtual IEnumerable<RilevanzaFinding> Rilevanze
    {
        get
        {
            return _rilevanze.ToArray();
        }
    }
}

public class RilevanzaFinding : EquatableObject<RilevanzaFinding>
{
    public virtual Rating Rating { get; set; }
    public virtual DateTime? DataFine{ get; set; }
    public virtual string Note { get; set; }
}

where EquatableObject implements this Equals:

public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        TObject other = obj as TObject;

        return Equals(other);

    }

    public virtual bool Equals(TObject other)
    {
        if (other == null)
            return false;

        Type t = GetType();

        TypeInfo typeInfo = t.GetTypeInfo();
        IEnumerable<FieldInfo> fields = typeInfo.DeclaredFields.Where(x => x.FieldType.Name != typeof(ICollection<>).Name);
        foreach (FieldInfo field in fields)
        {
            object value1 = field.GetValue(other);
            object value2 = field.GetValue(this);

            if (value1 == null)
            {
                if (value2 != null)
                    return false;
            }
            else if (!value1.Equals(value2))
                return false;
        }
        return true;
    }

now when i remove a Rilevanza from a collection of a finding Rilevanze tis is the sql generated by nhibernate:

NHibernate: DELETE FROM RilevanzaFinding_T045 WHERE int_T045_IdFinding =
@p0 AND dte_T045_DataFine = @p1 AND nvc_T045_Note = @p2 AND int_T045_IdRating
 = @p3;@p0 = 201 [Type: Int32 (0:0:0)], @p1 = NULL [Type: DateTime (0:0:0)], @p2 = 'GD675PFN2GTR9EUJ3JHPG7XFX' [Type: String (1073741823:0:0)],
@p3 = 243 [Type: Int32 (0:0:0)]

wich fails due to "dte_T045_DataFine = NULL" condition, since it would be "dte_T045_DataFine IS NULL"

how can i make it write the right condition?