问:
Amazon MWS: Accessing Array of Matching Products
I am Working with MWS for the first time and hoping to create a program that uses the ListMatchingProducts request to average out the prices of every product that matches a query.

It should be a very simple program, but I am having trouble retrieving data.

First I make the call and get amazon's xml sheet, Then I convert the xml to an array.

Print_R shows that the array looks something like this:

```<code>Array ( [ListMatchingProductsResult] => Array ( [Products] => Array ( [Product] => Array ( [0] => Array ( [Identifiers] => Array ( [MarketplaceASIN] => Array ( [MarketplaceId] => ATVPDKIKX0DER [ASIN] => 0786866020 ) ) [AttributeSets] => Array ( [ItemAttributes] => Array ( [Author] => Array ( [0] => Stephen C. Lundin [1] => Harry Paul [2] => John Christensen ) [Binding] => Hardcover [Brand] => Hyperion [Color] => White [Creator] => Ken Blanchard [Edition] => 1 [Feature] => Great product! [ItemDimensions] => Array ( [Height] => 8.25 [Length] => 5.50 [Width] => 0.00 [Weight] => 0.54 ) [IsAdultProduct] => false [Label] => Hyperion [Languages] => Array ( [Language] => Array ( [0] => Array ( [Name] => english [Type] => Published ) [1] => Array ( [Name] => english [Type] => Original Language ) [2] => Array ( [Name] => english [Type] => Unknown ) ) ) [ListPrice] => Array ( **[Amount] => 21.00** [CurrencyCode] => USD ) [Manufacturer] => Hyperion [ManufacturerMaximumAge] => 1188.0 [ManufacturerMinimumAge] => 156.0 [NumberOfItems] => 1 [NumberOfPages] => 110 [PackageDimensions] => Array ( [Height] => 0.65 [Length] => 8.60 [Width] => 5.65 [Weight] => 0.58 ) [PackageQuantity] => 1 [PartNumber] => 9780786866021 [ProductGroup] => Book [ProductTypeName] => ABIS_BOOK [PublicationDate] => 2000-03-08 [Publisher] => Hyperion [ReleaseDate] => 2000-03-08 [SmallImage] => Array ( [URL] => http://ecx.images-amazon.com/images/I/51cHo55tbOL._SL75_.jpg [Height] => 75 [Width] => 47 ) [Studio] => Hyperion [Title] => Fish: A Proven Way to Boost Morale and Improve Results ) ) [Relationships] => Array ( ) [SalesRankings] => Array ( [SalesRank] => Array ( [0] => Array ( [ProductCategoryId] => book_display_on_website [Rank] => 4629 ) [1] => Array ( [ProductCategoryId] => 1043856 [Rank] => 2 ) [2] => Array ( [ProductCategoryId] => 2635 [Rank] => 7 ) [3] => Array ( [ProductCategoryId] => 2637 [Rank] => 18 ) ) ) ) [1] ...
</code>```

I am trying to access the amount part of the array, as this is the price of the object. Eventually, I will need to access the amount of each product and so a loop will likely come into play, but right now i cannot even access one products sales amount.

Here is the code I have been trying

```<code>$value = $array->ListMatchingProductsResult->Products->Product[0]->ListPrice->Amount;
print_r($value);
</code>```

And it is not working. Even calling print_r on $array->ListMatchingProductsResult is not printing an array.

Any help is greatly appreciated!

Thanks,

Matt

答:
Here is an sdk library that uses the ListMatchingProducts of Amazon MWS. You will be able to get the info in accessing info required.

https://github.com/choomz/amazon-mws-sdk/blob/master/search/src/MarketplaceWebServiceProducts/Samples/ListMatchingProductsSample.php

To show php errors have this set in your php.in

```<code>display_errors = On
</code>```

You can also give this on top of the php script

```<code>ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');
</code>```

Body:
I am Working with MWS for the first time and hoping to create a program that uses the ListMatchingProducts request to average out the prices of every product that matches a query.

It should be a very simple program, but I am having trouble retrieving data.

First I make the call and get amazon's xml sheet, Then I convert the xml to an array.

Print_R shows that the array looks something like this:

Array ( [ListMatchingProductsResult] => Array ( [Products] => Array ( [Product] => Array ( [0] => Array ( [Identifiers] => Array ( [MarketplaceASIN] => Array ( [MarketplaceId] => ATVPDKIKX0DER [ASIN] => 0786866020 ) ) [AttributeSets] => Array ( [ItemAttributes] => Array ( [Author] => Array ( [0] => Stephen C. Lundin [1] => Harry Paul [2] => John Christensen ) [Binding] => Hardcover [Brand] => Hyperion [Color] => White [Creator] => Ken Blanchard [Edition] => 1 [Feature] => Great product! [ItemDimensions] => Array ( [Height] => 8.25 [Length] => 5.50 [Width] => 0.00 [Weight] => 0.54 ) [IsAdultProduct] => false [Label] => Hyperion [Languages] => Array ( [Language] => Array ( [0] => Array ( [Name] => english [Type] => Published ) [1] => Array ( [Name] => english [Type] => Original Language ) [2] => Array ( [Name] => english [Type] => Unknown ) ) ) [ListPrice] => Array ( **[Amount] => 21.00** [CurrencyCode] => USD ) [Manufacturer] => Hyperion [ManufacturerMaximumAge] => 1188.0 [ManufacturerMinimumAge] => 156.0 [NumberOfItems] => 1 [NumberOfPages] => 110 [PackageDimensions] => Array ( [Height] => 0.65 [Length] => 8.60 [Width] => 5.65 [Weight] => 0.58 ) [PackageQuantity] => 1 [PartNumber] => 9780786866021 [ProductGroup] => Book [ProductTypeName] => ABIS_BOOK [PublicationDate] => 2000-03-08 [Publisher] => Hyperion [ReleaseDate] => 2000-03-08 [SmallImage] => Array ( [URL] => http://ecx.images-amazon.com/images/I/51cHo55tbOL._SL75_.jpg [Height] => 75 [Width] => 47 ) [Studio] => Hyperion [Title] => Fish: A Proven Way to Boost Morale and Improve Results ) ) [Relationships] => Array ( ) [SalesRankings] => Array ( [SalesRank] => Array ( [0] => Array ( [ProductCategoryId] => book_display_on_website [Rank] => 4629 ) [1] => Array ( [ProductCategoryId] => 1043856 [Rank] => 2 ) [2] => Array ( [ProductCategoryId] => 2635 [Rank] => 7 ) [3] => Array ( [ProductCategoryId] => 2637 [Rank] => 18 ) ) ) ) [1] ...

I am trying to access the amount part of the array, as this is the price of the object. Eventually, I will need to access the amount of each product and so a loop will likely come into play, but right now i cannot even access one products sales amount.

Here is the code I have been trying

$value = $array->ListMatchingProductsResult->Products->Product[0]->ListPrice->Amount;
print_r($value);

And it is not working. Even calling print_r on $array->ListMatchingProductsResult is not printing an array.

Any help is greatly appreciated!

Thanks,

Matt

Body:
Here is an sdk library that uses the ListMatchingProducts of Amazon MWS. You will be able to get the info in accessing info required.

https://github.com/choomz/amazon-mws-sdk/blob/master/search/src/MarketplaceWebServiceProducts/Samples/ListMatchingProductsSample.php

To show php errors have this set in your php.in

display_errors = On

You can also give this on top of the php script

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');


来源: stackexchange

问:
How to use Boost.Unit with ratios in the same unit
I have a very simple use case for using Boost.Unit, but not sure if there is a better/easier way to get the same done.

I want to convert between the same units, but different ratios. For example, hertz to kilohertz to megahertz.

From my understanding, I first must define units with my specific ratios:

```<code>typedef boost::units::make_scaled_unit<si::frequency, scale<10, static_rational<0> > >::type  Hertz_unit;
typedef boost::units::make_scaled_unit<si::frequency, scale<10, static_rational<3> > >::type  KilloHertz_unit;
typedef boost::units::make_scaled_unit<si::frequency, scale<10, static_rational<6> > >::type  MegaHertz_unit;
</code>```

Then create quantities that represent the units:

```<code>typedef boost::units::quantity<Hertz_unit     , double> Hertz;
typedef boost::units::quantity<KilloHertz_unit, double> KilloHertz;
typedef boost::units::quantity<MegaHertz_unit , double> MegaHertz;
</code>```

Finally some constants and literals:

```<code>BOOST_UNITS_STATIC_CONSTANT( Hz, Hertz_unit     );
BOOST_UNITS_STATIC_CONSTANT(KHz, KilloHertz_unit);
BOOST_UNITS_STATIC_CONSTANT(MHz, MegaHertz_unit );

Hertz      operator"" _Hz  (long double val) { return Hertz     (val *  Hz); }
KilloHertz operator"" _KHz (long double val) { return KilloHertz(val * KHz); }
MegaHertz  operator"" _MHz (long double val) { return MegaHertz (val * MHz); }
</code>```

Now I can use the quantities:

```<code>Hertz      freq_1 = (10 *  Hz);
KilloHertz freq_2 = (10 * KHz);
MegaHertz  freq_3 = (10 * MHz);
// OR
Hertz      freq_4 = 10.0_Hz;
KilloHertz freq_5 = 10.0_KHz;
MegaHertz  freq_6 = 10.0_MHz;
// Convert between units
Hertz freq_7 = static_cast<Hertz>(10 * KHz);
</code>```

Is this how Boost.Unit should be used or am I missing something that might make it easier to use?

Are there not already defined units/quantities that I can use somewhere hidden in a header? Or should this be done for all my units that I use?

Do I need to know/remember that Kilo is scale<10, static_rational<3> or is this already defined and available?

答:
There are a few different predefined "systems" that make things easier to use and avoid needing to define your own units and scales.

While this code doesn't involve frequencies, you should be able to adapt it to your needs (there is a boost/units/systems/si/frequency.hpp header, for example):

```<code>#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/prefixes.hpp>

using boost::units::si::meters;
using boost::units::si::milli;

typedef boost::units::quantity<boost::units::si::length> length;
static const auto millimeters = milli * meters;

// ...

auto x = length(5 * millimeters);
auto mm = double(x / meters * 1000.0);
</code>```

You used to be able to do this without the explicit cast to length (although you then needed to explicitly type the variable as length instead of using auto), but at some point this was made to require an explicit cast.

In theory you shouldn't need to do the conversion from meters to mm manually in that second line, but the obvious construction x / millimeters produces compile errors that I never did manage to figure out a good workaround (the scale doesn't cancel out like it should).

(You can also use x.value() rather than x / meters, but I don't like that approach as it will still compile and give you surprising results if the base unit of x wasn't what you were expecting.  And it still doesn't solve the mm conversion issue.)

Alternatively you might want to consider something like this answer, although that's mostly geared to using a single alternative scale as your base unit.

Here's another method using frequencies and multiple quantity types:

```<code>#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/frequency.hpp>
#include <boost/units/systems/si/prefixes.hpp>

using boost::units::si::hertz;
using boost::units::si::kilo;
using boost::units::si::mega;

static const auto kilohertz = kilo * hertz;
static const auto megahertz = mega * hertz;

typedef boost::units::quantity<boost::units::si::frequency> Hertz;
typedef boost::units::quantity<decltype(kilohertz)> KiloHertz;
typedef boost::units::quantity<decltype(megahertz)> MegaHertz;

// ...

auto freq_1 = Hertz(10 * hertz);
auto freq_2 = KiloHertz(10 * kilohertz);
auto freq_3 = MegaHertz(10 * megahertz);
auto freq_4 = KiloHertz(freq_3);
// freq1.value() == 10.0
// freq2.value() == 10.0
// freq3.value() == 10.0
// freq4.value() == 10000.0
</code>```

You can do conversions and maths on these fairly easily; in this context the value() is probably the most useful as it will naturally express the same unit as the variable.

One slightly unfortunate behaviour is that the default string output for these units is presented as inverse seconds (eg. freq2 is "10 k(s^-1)").  So you probably just want to avoid using those.

And yes, the operator"" works as well, so you could substitute these in the above:

```<code>Hertz     operator"" _Hz(long double val) { return Hertz(val * hertz); }
KiloHertz operator"" _kHz(long double val) { return KiloHertz(val * kilohertz); }
MegaHertz operator"" _MHz(long double val) { return MegaHertz(val * megahertz); }

auto freq_1 = 10.0_Hz;
auto freq_2 = 10.0_kHz;
auto freq_3 = 10.0_MHz;
auto freq_4 = KiloHertz(freq_3);
</code>```

For consistency you can also define Hertz in terms of hertz, but due to quirks it's a little more tricky than the others; this works though:

```<code>typedef boost::units::quantity<std::decay_t<decltype(hertz)>> Hertz;
typedef boost::units::quantity<std::decay_t<decltype(kilohertz)>> KiloHertz;
typedef boost::units::quantity<std::decay_t<decltype(megahertz)>> MegaHertz;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a very simple use case for using Boost.Unit, but not sure if there is a better/easier way to get the same done.

I want to convert between the same units, but different ratios. For example, hertz to kilohertz to megahertz.

From my understanding, I first must define units with my specific ratios:

typedef boost::units::make_scaled_unit<si::frequency, scale<10, static_rational<0> > >::type  Hertz_unit;
typedef boost::units::make_scaled_unit<si::frequency, scale<10, static_rational<3> > >::type  KilloHertz_unit;
typedef boost::units::make_scaled_unit<si::frequency, scale<10, static_rational<6> > >::type  MegaHertz_unit;

Then create quantities that represent the units:

typedef boost::units::quantity<Hertz_unit     , double> Hertz;
typedef boost::units::quantity<KilloHertz_unit, double> KilloHertz;
typedef boost::units::quantity<MegaHertz_unit , double> MegaHertz;

Finally some constants and literals:

BOOST_UNITS_STATIC_CONSTANT( Hz, Hertz_unit     );
BOOST_UNITS_STATIC_CONSTANT(KHz, KilloHertz_unit);
BOOST_UNITS_STATIC_CONSTANT(MHz, MegaHertz_unit );

Hertz      operator"" _Hz  (long double val) { return Hertz     (val *  Hz); }
KilloHertz operator"" _KHz (long double val) { return KilloHertz(val * KHz); }
MegaHertz  operator"" _MHz (long double val) { return MegaHertz (val * MHz); }

Now I can use the quantities:

Hertz      freq_1 = (10 *  Hz);
KilloHertz freq_2 = (10 * KHz);
MegaHertz  freq_3 = (10 * MHz);
// OR
Hertz      freq_4 = 10.0_Hz;
KilloHertz freq_5 = 10.0_KHz;
MegaHertz  freq_6 = 10.0_MHz;
// Convert between units
Hertz freq_7 = static_cast<Hertz>(10 * KHz);

Is this how Boost.Unit should be used or am I missing something that might make it easier to use?

Are there not already defined units/quantities that I can use somewhere hidden in a header? Or should this be done for all my units that I use?

Do I need to know/remember that Kilo is scale<10, static_rational<3> or is this already defined and available?

Body:
There are a few different predefined "systems" that make things easier to use and avoid needing to define your own units and scales.

While this code doesn't involve frequencies, you should be able to adapt it to your needs (there is a boost/units/systems/si/frequency.hpp header, for example):

#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/prefixes.hpp>

using boost::units::si::meters;
using boost::units::si::milli;

typedef boost::units::quantity<boost::units::si::length> length;
static const auto millimeters = milli * meters;

// ...

auto x = length(5 * millimeters);
auto mm = double(x / meters * 1000.0);

You used to be able to do this without the explicit cast to length (although you then needed to explicitly type the variable as length instead of using auto), but at some point this was made to require an explicit cast.

In theory you shouldn't need to do the conversion from meters to mm manually in that second line, but the obvious construction x / millimeters produces compile errors that I never did manage to figure out a good workaround (the scale doesn't cancel out like it should).

(You can also use x.value() rather than x / meters, but I don't like that approach as it will still compile and give you surprising results if the base unit of x wasn't what you were expecting.  And it still doesn't solve the mm conversion issue.)

Alternatively you might want to consider something like this answer, although that's mostly geared to using a single alternative scale as your base unit.

Here's another method using frequencies and multiple quantity types:

#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/frequency.hpp>
#include <boost/units/systems/si/prefixes.hpp>

using boost::units::si::hertz;
using boost::units::si::kilo;
using boost::units::si::mega;

static const auto kilohertz = kilo * hertz;
static const auto megahertz = mega * hertz;

typedef boost::units::quantity<boost::units::si::frequency> Hertz;
typedef boost::units::quantity<decltype(kilohertz)> KiloHertz;
typedef boost::units::quantity<decltype(megahertz)> MegaHertz;

// ...

auto freq_1 = Hertz(10 * hertz);
auto freq_2 = KiloHertz(10 * kilohertz);
auto freq_3 = MegaHertz(10 * megahertz);
auto freq_4 = KiloHertz(freq_3);
// freq1.value() == 10.0
// freq2.value() == 10.0
// freq3.value() == 10.0
// freq4.value() == 10000.0

You can do conversions and maths on these fairly easily; in this context the value() is probably the most useful as it will naturally express the same unit as the variable.

One slightly unfortunate behaviour is that the default string output for these units is presented as inverse seconds (eg. freq2 is "10 k(s^-1)").  So you probably just want to avoid using those.

And yes, the operator"" works as well, so you could substitute these in the above:

Hertz     operator"" _Hz(long double val) { return Hertz(val * hertz); }
KiloHertz operator"" _kHz(long double val) { return KiloHertz(val * kilohertz); }
MegaHertz operator"" _MHz(long double val) { return MegaHertz(val * megahertz); }

auto freq_1 = 10.0_Hz;
auto freq_2 = 10.0_kHz;
auto freq_3 = 10.0_MHz;
auto freq_4 = KiloHertz(freq_3);

For consistency you can also define Hertz in terms of hertz, but due to quirks it's a little more tricky than the others; this works though:

typedef boost::units::quantity<std::decay_t<decltype(hertz)>> Hertz;
typedef boost::units::quantity<std::decay_t<decltype(kilohertz)>> KiloHertz;
typedef boost::units::quantity<std::decay_t<decltype(megahertz)>> MegaHertz;


问:
How identifiers are stored in memory?
any value assigned to a variable (e.g. int i=5) is stored in memory in hexadecimal form at some address.
So will the variable name(i) associated with the value is converted to ASCII code in memory while storing?</p>

答:
The identifiers names are not retained in the assembly file after the compilation. They are maintained during compilation in a data structure called Symbol Table which associates each identifier with the information about its declaration and memory address allocation.

During compilation, the identifiers are assigned a memory address which are then accessed using offset from base pointer of the memory stack assigned to the process.

Title: How identifiers are stored in memory?


问:
Insert PHP variabel in SQL queries Codeigniter
I'm using Codeigniter to use some queries and this is my code so far. is my code correct?

```<code>$this->db->select("(SELECT SUM(grand_total) FROM Sales_order WHERE member = '2') - (SELECT SUM(amount) FROM payment WHERE member_id = '2')  AS total_sales");
</code>```

and how to change number 2 with this variable

  $this->session->userdata('ID')

答:
Try this</p>

```<code>$this->db->select("(SELECT SUM(grand_total) FROM Sales_order WHERE member = '".$this->session->userdata('ID')."') - (SELECT SUM(amount) FROM payment WHERE member_id = '".$this->session->userdata('ID')."')  AS total_sales"');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Codeigniter to use some queries and this is my code so far. is my code correct?

$this->db->select("(SELECT SUM(grand_total) FROM Sales_order WHERE member = '2') - (SELECT SUM(amount) FROM payment WHERE member_id = '2')  AS total_sales");

and how to change number 2 with this variable

  $this->session->userdata('ID')

Body:
Try this

$this->db->select("(SELECT SUM(grand_total) FROM Sales_order WHERE member = '".$this->session->userdata('ID')."') - (SELECT SUM(amount) FROM payment WHERE member_id = '".$this->session->userdata('ID')."')  AS total_sales"');


问:
Saving a Twitter Sample Stream to RavenDB results in the exception The maximum number of requests (30) allowed for this session has been reached
I am attempting to save a Twitter sample stream to RavenDB but I am encountering the exception: "The maximum number of requests (30) allowed for this session has been reached."

This question has the same problem however I think by calling session.Store I am already doing what the accepted answer suggests.

I know I am doing something wrong but not sure what.

Here is my code:

```<code>using Tweetinvi;

namespace TwitterNoSql
{
    class Program
    {
        static void Main(string[] args)
        {
            Auth.SetUserCredentials() // redacted for SO

            var stream = Stream.CreateSampleStream();

            using (var session = DocumentStoreHolder.Store.OpenSession())
            {
                stream.TweetReceived += (sender, theTweet) =>
                {
                    var tm = new TwitterModels
                    {
                        Id = theTweet.Tweet.Id,
                        TheTextFromTwitter = theTweet.Tweet.FullText
                    };

                    session.Store(tm);
                    session.SaveChanges();

                };
                stream.StartStream();

            }
        }
    }
}
</code>```

DocumentStoreHolder.cs

```<code>using System;
using Raven.Client;
using Raven.Client.Document;

namespace TwitterNoSql
{
    class DocumentStoreHolder
    {
        private static readonly Lazy<IDocumentStore> LazyStore =
            new Lazy<IDocumentStore>(() =>
            {
                var store = new DocumentStore
                {
                    Url = "http://localhost:8080",
                    DefaultDatabase = "TwitterNoSql"
                };
                return store.Initialize();
            });

        public static IDocumentStore Store =>
             LazyStore.Value;
    }
}
</code>```

TwitterModels.cs

```<code>namespace TwitterNoSql
{
    public class TwitterModels
    {
        public long Id { get; set; }
        public string TheTextFromTwitter { get; set; }
    }
}
</code>```

答:
Try calling SaveChanges() at the end of your operation:</p>

```<code>using (var session = DocumentStoreHolder.Store.OpenSession())
{
    stream.TweetReceived += (sender, theTweet) =>
    {
        var tm = new TwitterModels
        {
            Id = theTweet.Tweet.Id,
            TheTextFromTwitter = theTweet.Tweet.FullText
        };

        session.Store(tm);

    };

    stream.StartStream();
    session.SaveChanges();

}
</code>```

Body:
I am attempting to save a Twitter sample stream to RavenDB but I am encountering the exception: "The maximum number of requests (30) allowed for this session has been reached."

This question has the same problem however I think by calling session.Store I am already doing what the accepted answer suggests.

I know I am doing something wrong but not sure what.

Here is my code:

using Tweetinvi;

namespace TwitterNoSql
{
    class Program
    {
        static void Main(string[] args)
        {
            Auth.SetUserCredentials() // redacted for SO

            var stream = Stream.CreateSampleStream();

            using (var session = DocumentStoreHolder.Store.OpenSession())
            {
                stream.TweetReceived += (sender, theTweet) =>
                {
                    var tm = new TwitterModels
                    {
                        Id = theTweet.Tweet.Id,
                        TheTextFromTwitter = theTweet.Tweet.FullText
                    };

                    session.Store(tm);
                    session.SaveChanges();

                };
                stream.StartStream();

            }
        }
    }
}

DocumentStoreHolder.cs

using System;
using Raven.Client;
using Raven.Client.Document;

namespace TwitterNoSql
{
    class DocumentStoreHolder
    {
        private static readonly Lazy<IDocumentStore> LazyStore =
            new Lazy<IDocumentStore>(() =>
            {
                var store = new DocumentStore
                {
                    Url = "http://localhost:8080",
                    DefaultDatabase = "TwitterNoSql"
                };
                return store.Initialize();
            });

        public static IDocumentStore Store =>
             LazyStore.Value;
    }
}

TwitterModels.cs

namespace TwitterNoSql
{
    public class TwitterModels
    {
        public long Id { get; set; }
        public string TheTextFromTwitter { get; set; }
    }
}

Body:
Try calling SaveChanges() at the end of your operation:

using (var session = DocumentStoreHolder.Store.OpenSession())
{
    stream.TweetReceived += (sender, theTweet) =>
    {
        var tm = new TwitterModels
        {
            Id = theTweet.Tweet.Id,
            TheTextFromTwitter = theTweet.Tweet.FullText
        };

        session.Store(tm);

    };

    stream.StartStream();
    session.SaveChanges();

}


问:
Javascript If Button is pressed - do stuff
I am looking for something like:

```<code>if (..button1 is pressed..){
some function
}

if (...button2 is pressed...){
some other function
}
</code>```

But all of those need to be a part of some completely different function.

Something like:

```<code>$(document).ready(function () {
$(".Test").hover(function () {
  if (...Button is pressed...) {
 $('.dropdown').slideToggle('medium');
  }
});
});
</code>```

答:
I'm assuming you want a to attach event listener to a few buttons? In that case you can do it like the following code:

$(document).ready(function () {
  $('#btn1').click(function() {
    // do stuff with button 1
    console.log('button 1 clicked');
  });
  $('#btn2').click(function() {
    // do stuff with button 2
    console.log('button 2 clicked');
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn1'>button 1</button>
<button id='btn2'>button 2</button></code>```

Body:
I am looking for something like:

if (..button1 is pressed..){
some function
}

if (...button2 is pressed...){
some other function
}

But all of those need to be a part of some completely different function.

Something like:

$(document).ready(function () {
$(".Test").hover(function () {
  if (...Button is pressed...) {
 $('.dropdown').slideToggle('medium');
  }
});
});

Body:
I'm assuming you want a to attach event listener to a few buttons? In that case you can do it like the following code:

$(document).ready(function () {
  $('#btn1').click(function() {
    // do stuff with button 1
    console.log('button 1 clicked');
  });
  $('#btn2').click(function() {
    // do stuff with button 2
    console.log('button 2 clicked');
  })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn1'>button 1</button>
<button id='btn2'>button 2</button>


问:
sort a table's columns using jquery without plugins
I am trying to sort a table's column values when specific buttons are clicked. I first want to figure out how to sort the table with pre-defined values (I have included 2 rows with actual values in my table). Second, after I am done with sorting pre-defined values in the table. I want to be able to add a "Create Row" button which can randomly generate any values or even letters. And still, after clicking buttons, values will be sorted.
My code is broken and I don't know why!

I am stuck and I cannot find much help!! Thanks in advance guys!

//add row function
$(document).ready(function() {
  $("#add_row").click(function() {
    event.preventDefault();
    var new1 = $("
6	1	<input id ='dr' class='btn btn-danger' type ='button' value= 'delete'>
").on('click', function() {
      $(this).find('td').toggleClass('highlighted')
    });
    $('#myTable').append(new1);
  });

  //delete function
  $('#myTable').on('click', '#dr', function() {
    $(this).parent().parent().remove();
  });

  //sort function
  $('#sort1,#sort2').on('click', function() {
    var n1 = $(this).index();
    console.log(n1);
    var n2 = $('#myTable').find('tbody >tr:has(td)').get();
    console.log(n2);
    n1 += 1;
    n2.sort(function(a, b) {
      var vA = $(a).children(':nth-child(' + n1 + ')').text();
      var vB = $(b).children(':nth-child(' + n1 + ')').text();
      if (vA < vB) {
        return -1;
      } else if (vA > vB) {
        return 1;
      } else {
        return 0
      };
    });

    $.each(n2, function(index, row) {
      $('tbody').append(row);
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>create table</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <style type="text/css">
    table,
    td {
      border: 1px solid black;
    }

    .highlighted {
      background-color: yellow;
    }
  </style>

</head>

<body>
  <div class="container">
    <p>Click the buttons to create and delete row(s) for the table.</p>

    <table id="myTable" class="table" style="width: 80%">
      <tbody>
        <tr>
          <td>Name<button type="button" id="sort1" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></td>
          <td>Value<button type="button" id="sort2" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></td>
          <td>Deletable</td>
        </tr>
        <tr>
          <td>3</td>
          <td>4</td>
          <td>5</td>
        </tr>
        <tr>
          <td>1</td>
          <td>2</td>
          <td>3</td>
        </tr>
    </table>
    <br>
    <button type="button" id="add_row" class="btn btn-primary">Create row</button>
  </div>
</body></code>```

答:
In your first row if you change the  tags to s then the sorting will leave them where they are.

```<code><th>Name<button type="button" id="sort1" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></th>
<th>Value<button type="button" id="sort2" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></th>
<th>Deletable</th>
</code>```

And in your code when getting the index of the clicked button you always get the index of $(this) which is the button's index and not the column's. So try changing that line to

var n1 = $(this).closest("th").index();

and it should work.

//add row function
$(document).ready(function() {
  $("#add_row").click(function() {
    event.preventDefault();
    var new1 = $("
6	1	<input id ='dr' class='btn btn-danger' type ='button' value= 'delete'>
").on('click', function() {
      $(this).find('td').toggleClass('highlighted');
    });
    $('#myTable').append(new1);
  });

  //delete function
  $('#myTable').on('click', '#dr', function() {
    $(this).parent().parent().remove();
  });

  //sort function
  $('#sort1,#sort2').on('click', function() {
    var n1 = $(this).closest("th").index() + 1;
    console.log(n1 - 1);
    var n2 = $('#myTable').find('tbody >tr:has(td)').get();
    console.log(n2);
    n2.sort(function(a, b) {
      var vA = $(a).children(':nth-child(' + n1 + ')').text();
      var vB = $(b).children(':nth-child(' + n1 + ')').text();
      if (vA < vB) return -1;
      if (vA > vB) return 1;
      return 0;
    });

    $.each(n2, function(index, row) {
      $('tbody').append(row);
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>create table</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <style type="text/css">
    table,
    td {
      border: 1px solid black;
    }

    .highlighted {
      background-color: yellow;
    }
  </style>

</head>

<body>
  <div class="container">
    <p>Click the buttons to create and delete row(s) for the table.</p>

    <table id="myTable" class="table" style="width: 80%">
      <tbody>
        <tr>
          <th>Name<button type="button" id="sort1" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></th>
          <th>Value<button type="button" id="sort2" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></th>
          <th>Deletable</th>
        </tr>
        <tr>
          <td>3</td>
          <td>4</td>
          <td>5</td>
        </tr>
        <tr>
          <td>1</td>
          <td>2</td>
          <td>3</td>
        </tr>
    </table>
    <br>
    <button type="button" id="add_row" class="btn btn-primary">Create row</button>
  </div>
</body></code>```

Body:
I am trying to sort a table's column values when specific buttons are clicked. I first want to figure out how to sort the table with pre-defined values (I have included 2 rows with actual values in my table). Second, after I am done with sorting pre-defined values in the table. I want to be able to add a "Create Row" button which can randomly generate any values or even letters. And still, after clicking buttons, values will be sorted.
My code is broken and I don't know why!

I am stuck and I cannot find much help!! Thanks in advance guys!

//add row function
$(document).ready(function() {
  $("#add_row").click(function() {
    event.preventDefault();
    var new1 = $("
6	1	<input id ='dr' class='btn btn-danger' type ='button' value= 'delete'>
").on('click', function() {
      $(this).find('td').toggleClass('highlighted')
    });
    $('#myTable').append(new1);
  });

  //delete function
  $('#myTable').on('click', '#dr', function() {
    $(this).parent().parent().remove();
  });

  //sort function
  $('#sort1,#sort2').on('click', function() {
    var n1 = $(this).index();
    console.log(n1);
    var n2 = $('#myTable').find('tbody >tr:has(td)').get();
    console.log(n2);
    n1 += 1;
    n2.sort(function(a, b) {
      var vA = $(a).children(':nth-child(' + n1 + ')').text();
      var vB = $(b).children(':nth-child(' + n1 + ')').text();
      if (vA < vB) {
        return -1;
      } else if (vA > vB) {
        return 1;
      } else {
        return 0
      };
    });

    $.each(n2, function(index, row) {
      $('tbody').append(row);
    });
  });
});

<!DOCTYPE html>

  <title>create table</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Click the buttons to create and delete row(s) for the table.

          Name<button type="button" id="sort1" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button>
          Value<button type="button" id="sort2" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button>
          Deletable

          3
          4
          5

          1
          2
          3

    <button type="button" id="add_row" class="btn btn-primary">Create row</button>

Body:
In your first row if you change the <td> tags to <th>s then the sorting will leave them where they are.

<th>Name<button type="button" id="sort1" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></th>
<th>Value<button type="button" id="sort2" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></th>
<th>Deletable</th>

And in your code when getting the index of the clicked button you always get the index of $(this) which is the button's index and not the column's. So try changing that line to

var n1 = $(this).closest("th").index();

and it should work.

//add row function
$(document).ready(function() {
  $("#add_row").click(function() {
    event.preventDefault();
    var new1 = $("<tr><td>6</td><td>1</td><td><input id ='dr' class='btn btn-danger' type ='button' value= 'delete'></td></tr>").on('click', function() {
      $(this).find('td').toggleClass('highlighted');
    });
    $('#myTable').append(new1);
  });

  //delete function
  $('#myTable').on('click', '#dr', function() {
    $(this).parent().parent().remove();
  });

  //sort function
  $('#sort1,#sort2').on('click', function() {
    var n1 = $(this).closest("th").index() + 1;
    console.log(n1 - 1);
    var n2 = $('#myTable').find('tbody >tr:has(td)').get();
    console.log(n2);
    n2.sort(function(a, b) {
      var vA = $(a).children(':nth-child(' + n1 + ')').text();
      var vB = $(b).children(':nth-child(' + n1 + ')').text();
      if (vA < vB) return -1;
      if (vA > vB) return 1;
      return 0;
    });

    $.each(n2, function(index, row) {
      $('tbody').append(row);
    });
  });
});

<!DOCTYPE html>
<html lang="en">

<head>
  <title>create table</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <style type="text/css">
    table,
    td {
      border: 1px solid black;
    }

    .highlighted {
      background-color: yellow;
    }
  </style>

</head>

<body>
  <div class="container">
    <p>Click the buttons to create and delete row(s) for the table.</p>

    <table id="myTable" class="table" style="width: 80%">
      <tbody>
        <tr>
          <th>Name<button type="button" id="sort1" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></th>
          <th>Value<button type="button" id="sort2" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></th>
          <th>Deletable</th>
        </tr>
        <tr>
          <td>3</td>
          <td>4</td>
          <td>5</td>
        </tr>
        <tr>
          <td>1</td>
          <td>2</td>
          <td>3</td>
        </tr>
    </table>
    <br>
    <button type="button" id="add_row" class="btn btn-primary">Create row</button>
  </div>
</body>


问:
Unexpected type from a slice of 2-dimensional array
In the following code, I'm trying to get the 1st and 2nd rows of array A by using either var or ref. Here, my understanding is that var always creates a new array, while ref creates an alias (or reference) to the right-hand side.

```<code>var A: [1..2, 1..3] int;
A = 0;

var row1 = A[ 1, .. ];
ref row2 = A[ 2, .. ];

row1 = 10;
row2 = 20;

writeln( "row1 = ", row1 );
writeln( "row2 = ", row2 );

writeln( "A = ", A );
</code>```

The result is as expected (i.e., the 1st row of A is not modified):

```<code>row1 = 10 10 10
row2 = 20 20 20
A = 0 0 0
20 20 20
</code>```

But if I print the type of row1 and row2

```<code>writeln( "row1.type = ", row1.type: string );
writeln( "row2.type = ", row2.type: string );
</code>```

I get this result:

```<code>row1.type = [ArrayViewRankChangeDom(1,int(64),false,2*bool,2*int(64),ArrayViewRankChangeDist(DefaultDist,2*bool,2*int(64)))] int(64)
row2.type = [ArrayViewRankChangeDom(1,int(64),false,2*bool,2*int(64),ArrayViewRankChangeDist(DefaultDist,2*bool,2*int(64)))] int(64)
</code>```

This is somewhat surprising because I assumed row1 to be a "usual" array (i.e., not an alias). For example, the following vec (which I call a "usual" array)

```<code>var vec: [1..3] int;
writeln( "vec.type = ", vec.type: string );
</code>```

gives

```<code>vec.type = [domain(1,int(64),false)] int(64)
</code>```

So I'm wondering whether there is some difference between row1 and vec (as array types)...?

答:
I'm wondering whether there is some difference between row1 and vec (as array types)...?

There is a difference, though whether or not you consider it a difference in type will depend somewhat on what your notion of type is.  Every Chapel array is defined in terms of a domain map which specifies how it is defined (and how its domain is defined).  If no domain map is specified, a default domain map is used.  An array's domain map is technically part of its type, though in practice, it tends to be an aspect that should impact how the array is implemented more than the operations that can be applied to the array.

So vec in your example is a 1D array of int(64) elements indexed by int(64)s (and its indices are non-stridable which is what the false in its domain's signature represents), and its domain map is the default domain map.  Meanwhile your slice expressions A[i, ..] are also 1D arrays of int(64) elements indexed by int(64)s (and are also non-stridable), yet their domain maps are ArrayViewRankChange.  This is an internal domain map which represents a rank-change alias ("view") of another array.

[The short version of the rationale for using this distinct domain map to represent the rank-change slice of the array is this: if the original 2D array is distributed (say), a 1D slice of it should presumably be similarly distributed as well -- this suggests that it shouldn't be a default domain map (which is not distributed) nor the original array's distribution (which describes how to implement 2D things).  So the choice is either to have rank-change slices require domain maps to create new lower-dimensional domain maps of themselves (which tends to be somewhere between challenging and impossible) or to use a new domain map that knows how to translate from 1D indices to the original distribution's 2D indices.  This is what the ArrayViewRankChange domain map does.  A longer version of the rationale can be found in the 1.15 release notes starting on slide 27 ("Array Views").]

Given the above, it probably makes sense that row2 would also indicate ArrayViewRankChange as its domain map since it is a reference to a rank-change slice expression.  But it may be more surprising that row1 would, since it is a brand-new array resulting in a deep copy of the ArrayViewRankChange array and could therefore use traditional default array storage.  But the rationale can again be seen in the distributed case where that new array variable should (presumably) have the same distribution as the original---and our means of doing so is via the ArrayViewRankChange.

If you wanted to force an array slice to be "a normal array", you could do so using a more precise declaration:

```<code>var row1b: [A.domain.dim(2)] A.eltType = A[1, ..];
</code>```

At which point its type will match vecs:

```<code>row1b.type = [domain(1,int(64),false)] int(64)
</code>```

All that said, hopefully you will find that you can use row1 and row2 in most places that you could use vec.  If not, please ask a follow-up question or file an issue on GitHub.

As a closing note, arguably the compiler could/should do a better job of printing array types more cleanly, or at least to offer different options for the level of verbosity in printing out its type (e.g., in many cases, perhaps identifying the domain map is unnecessary, or perhaps the domain type could be printed out more simply?)

Body:
In the following code, I'm trying to get the 1st and 2nd rows of array A by using either var or ref. Here, my understanding is that var always creates a new array, while ref creates an alias (or reference) to the right-hand side.

var A: [1..2, 1..3] int;
A = 0;

var row1 = A[ 1, .. ];
ref row2 = A[ 2, .. ];

row1 = 10;
row2 = 20;

writeln( "row1 = ", row1 );
writeln( "row2 = ", row2 );

writeln( "A = ", A );

The result is as expected (i.e., the 1st row of A is not modified):

row1 = 10 10 10
row2 = 20 20 20
A = 0 0 0
20 20 20

But if I print the type of row1 and row2

writeln( "row1.type = ", row1.type: string );
writeln( "row2.type = ", row2.type: string );

I get this result:

row1.type = [ArrayViewRankChangeDom(1,int(64),false,2*bool,2*int(64),ArrayViewRankChangeDist(DefaultDist,2*bool,2*int(64)))] int(64)
row2.type = [ArrayViewRankChangeDom(1,int(64),false,2*bool,2*int(64),ArrayViewRankChangeDist(DefaultDist,2*bool,2*int(64)))] int(64)

This is somewhat surprising because I assumed row1 to be a "usual" array (i.e., not an alias). For example, the following vec (which I call a "usual" array)

var vec: [1..3] int;
writeln( "vec.type = ", vec.type: string );

gives

vec.type = [domain(1,int(64),false)] int(64)

So I'm wondering whether there is some difference between row1 and vec (as array types)...?

Body:
I'm wondering whether there is some difference between row1 and vec (as array types)...?

There is a difference, though whether or not you consider it a difference in type will depend somewhat on what your notion of type is.  Every Chapel array is defined in terms of a domain map which specifies how it is defined (and how its domain is defined).  If no domain map is specified, a default domain map is used.  An array's domain map is technically part of its type, though in practice, it tends to be an aspect that should impact how the array is implemented more than the operations that can be applied to the array.

So vec in your example is a 1D array of int(64) elements indexed by int(64)s (and its indices are non-stridable which is what the false in its domain's signature represents), and its domain map is the default domain map.  Meanwhile your slice expressions A[i, ..] are also 1D arrays of int(64) elements indexed by int(64)s (and are also non-stridable), yet their domain maps are ArrayViewRankChange.  This is an internal domain map which represents a rank-change alias ("view") of another array.

[The short version of the rationale for using this distinct domain map to represent the rank-change slice of the array is this: if the original 2D array is distributed (say), a 1D slice of it should presumably be similarly distributed as well -- this suggests that it shouldn't be a default domain map (which is not distributed) nor the original array's distribution (which describes how to implement 2D things).  So the choice is either to have rank-change slices require domain maps to create new lower-dimensional domain maps of themselves (which tends to be somewhere between challenging and impossible) or to use a new domain map that knows how to translate from 1D indices to the original distribution's 2D indices.  This is what the ArrayViewRankChange domain map does.  A longer version of the rationale can be found in the 1.15 release notes starting on slide 27 ("Array Views").]

Given the above, it probably makes sense that row2 would also indicate ArrayViewRankChange as its domain map since it is a reference to a rank-change slice expression.  But it may be more surprising that row1 would, since it is a brand-new array resulting in a deep copy of the ArrayViewRankChange array and could therefore use traditional default array storage.  But the rationale can again be seen in the distributed case where that new array variable should (presumably) have the same distribution as the original---and our means of doing so is via the ArrayViewRankChange.

If you wanted to force an array slice to be "a normal array", you could do so using a more precise declaration:

var row1b: [A.domain.dim(2)] A.eltType = A[1, ..];

At which point its type will match vecs:

row1b.type = [domain(1,int(64),false)] int(64)

All that said, hopefully you will find that you can use row1 and row2 in most places that you could use vec.  If not, please ask a follow-up question or file an issue on GitHub.

As a closing note, arguably the compiler could/should do a better job of printing array types more cleanly, or at least to offer different options for the level of verbosity in printing out its type (e.g., in many cases, perhaps identifying the domain map is unnecessary, or perhaps the domain type could be printed out more simply?)


问:
ASP.NET controls cannot be referenced in code-behind in Visual Studio 2008
Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops.

I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a  screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls.

After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind.

In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts.

I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio.

Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy.

I doubt anyone has run into this, but have you?

Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water.

Jon Limjap: I edited the title to both make it clear and descriptive and make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one.

答: we cannot change the code when the application is running .To do so first click  on the stop button on the top which will halt your application .now click on the button in design mode ,it will insert the code in .aspx.cs file ,then write the code in it</p>

OwnerDisplayName: Kevin Lee

LastEditorDisplayName: Jon Limjap


问:
'and' keyword in C++
I have seen and  keyword being used inside if statement just like && operator.
Is there any difference between these (and , &&) ?

```<code>#include <iostream>

using namespace std;

int main()
{
bool a = true;
bool b = true;

if(a==true and b==true) // if(a==true && b == true)
{
    cout << "YES ";
}

return 0;
}
</code>```

答: There is no difference in and and &&. you can also use not instead of ! and or instead of ||.

Title: 'and' keyword in C++

Body:
I have seen and  keyword being used inside if statement just like && operator.
Is there any difference between these (and , &&) ?

#include <iostream>

using namespace std;

int main()
{
bool a = true;
bool b = true;

if(a==true and b==true) // if(a==true && b == true)
{
    cout << "YES ";
}

return 0;
}


问:
Oracle Subquery - How to?
I have 2 tables that look like:

```<code>GL_ROLLUP
Responsibility    Responsibility_L3
15500             15B
15445             15C
15515             15B
15494             15C
15600             15D

GL_Detail
Responsibility    Expense      Amount
15500             6501         30.51
15445             6508         75.60
15515             6535         45.68
15494             6508         65.50
15600             6505         84.39
</code>```

My query right now is pulling the data from the GL_Detail table; however what I want to be able to due is use the search parameter Responsibility_L3 found in GL_ROLLUP so I can query all Responsibilities within this rolled up value (instead of doing a range or a " = '15500' or....."). I tried doing this a few times, but my query seems to get stuck and never brings data back.

Any help would be greatly appreciated!

答:
The required query is a simple one:

```<code>select d.responsibility
       , d.expense
       , d.amount
from GL_ROLLUP r
     inner join GL_Detail d
           on d.responsibility = r.responsibility
where r.responsibility_l3 = :l3_search_param -- use appropriate notation
</code>```

"my query seems to get stuck and never brings data back"

If the above query suffers the same fate, that's a performance issue.  You will need to post an explain plan, details of data volumes,indexes, etc

Title: Oracle Subquery - How to?

Body:
I have 2 tables that look like:

GL_ROLLUP
Responsibility    Responsibility_L3
15500             15B
15445             15C
15515             15B
15494             15C
15600             15D

GL_Detail
Responsibility    Expense      Amount
15500             6501         30.51
15445             6508         75.60
15515             6535         45.68
15494             6508         65.50
15600             6505         84.39

My query right now is pulling the data from the GL_Detail table; however what I want to be able to due is use the search parameter Responsibility_L3 found in GL_ROLLUP so I can query all Responsibilities within this rolled up value (instead of doing a range or a " = '15500' or....."). I tried doing this a few times, but my query seems to get stuck and never brings data back.

Any help would be greatly appreciated!

Body:
The required query is a simple one:

select d.responsibility
       , d.expense
       , d.amount
from GL_ROLLUP r
     inner join GL_Detail d
           on d.responsibility = r.responsibility
where r.responsibility_l3 = :l3_search_param -- use appropriate notation

"my query seems to get stuck and never brings data back"

If the above query suffers the same fate, that's a performance issue.  You will need to post an explain plan, details of data volumes,indexes, etc


问:
Run a batch file with Windows task scheduler
I have a batch file daily.bat, this is the code:

```<code>cd C:\inetpub\wwwroot\infoweb\factuur\cron
c:\PHP\php.exe -f ./cron_pdf.php
ftp -s:ftp_upload.txt ftp.site.be
</code>```

And I created a task with task scheduler in Windows 7. When I run the batch manually, everything goes fine, but when I try to run it with the task scheduler nothing happens.

My action is

```<code>'run script' "C:\inetpub\wwwroot\site\x\cron\daily.bat"
</code>```

UAC is off and I am Admin.

Any idea why this is not working?

答:
It is working now. This is what I did. You probably won't need all these steps to make it work but just to be sure try them all:

Check the account parameters of your scheduled task and make sure they are set to run whether or not someone is logged into the machine

check run with most privileges/rights

Make sure you go to the full path first: cd C:\inetpub\wwwroot\infoweb\factuur\cron

Don't use double quotes in your batch files (don't know why but seems to help)

Be super admin, enter 'Net user administrator /active:yes' in command prompt, log out and log in as the super admin, so UAC is off

Body:
I have a batch file daily.bat, this is the code:

cd C:\inetpub\wwwroot\infoweb\factuur\cron
c:\PHP\php.exe -f ./cron_pdf.php
ftp -s:ftp_upload.txt ftp.site.be

And I created a task with task scheduler in Windows 7. When I run the batch manually, everything goes fine, but when I try to run it with the task scheduler nothing happens.

My action is

'run script' "C:\inetpub\wwwroot\site\x\cron\daily.bat"

UAC is off and I am Admin.

Any idea why this is not working?


答: Yes, the new and keyword has been around since at least C++98. It operates identically to the && operator.

Title: 'and' keyword in C++


答:
Example

$(function(){
  $('#button1').click(function(event){
    alert('button 1 clicked');
  });

  $('#button2').click(function(event){
    alert('button 2 clicked');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE>
<html>
  <head></head>
  <body>
    <button id='button1'>button 1</button>
    <button id='button2'>button 2</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  </body>
</html></code>```

Title: Javascript If Button is pressed - do stuff

Body:
Example

$(function(){
  $('#button1').click(function(event){
    alert('button 1 clicked');
  });

  $('#button2').click(function(event){
    alert('button 2 clicked');
  });
});

<!DOCTYPE>
<html>
  <head></head>
  <body>
    <button id='button1'>button 1</button>
    <button id='button2'>button 2</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  </body>
</html>


问:
How can i get location on center of screen with Google Map Api
I need to make it like in PlacePicker API But i want it to mapsActivity  when move screen location is change on center of screen  plz guide me</p>

答:
As I can see you are trying to know the centre of the screen and drop a pin on it.(My assumption of your query.)
There are numerous posts on which you can try to get the centre point in XY coordinates with respect to the screen.
Check this link out https://stackoverflow.com/a/40714006/8117352.

After fetching these coordinates in X and Y points in screen you can use a concept of Projection in the google maps, which allows you to convert these points to latitude and longitude.

```<code>Point x_y_points = new Point(x_co, y_co);
    LatLng latLng =
mGoogleMap.getProjection().fromScreenLocation(x_y_points);
</code>```

More on projection : https://developers.google.com/android/reference/com/google/android/gms/maps/Projection

Body:
As I can see you are trying to know the centre of the screen and drop a pin on it.(My assumption of your query.)
There are numerous posts on which you can try to get the centre point in XY coordinates with respect to the screen.
Check this link out https://stackoverflow.com/a/40714006/8117352.

After fetching these coordinates in X and Y points in screen you can use a concept of Projection in the google maps, which allows you to convert these points to latitude and longitude.

Point x_y_points = new Point(x_co, y_co);
    LatLng latLng =
mGoogleMap.getProjection().fromScreenLocation(x_y_points);

More on projection : https://developers.google.com/android/reference/com/google/android/gms/maps/Projection


问:
Strange behavior in a flexbox when resizing window on mobile chrome
There is a very strange behavior with flexbox happening on a mobile browser.

Please see this gif for a visual of what's happening

This only happens on a mobile browser, I'm currently using Chrome mobile on a Google Pixel phone. I have a resize script running that resizes multiple elements on the page as a workaround for not being able to properly utilize 100vh like so:

```<code>window.onresize = function() {
        document.getElementById("backgroundImage").style.height = window.innerHeight;
        document.getElementById("mainScreen").style.height = window.innerHeight;
        if (window.innerWidth > 750) {
          document.getElementById("scrollContent").style.height = window.innerHeight - "96";
        } else {
          document.getElementById("scrollContent").style.height = window.innerHeight - "72";
        }
    };
</code>```

The items that are being effected as seen in the gif are items in a flex container. This behavior happens when I scroll up to hide the navigation bar, then click one of the flex links.

I'm using Vuejs, and the content below is being populated by checking for a prop change. The flex links pass a string into a function that changes the project view to the selected project.

I also have a script to add a class that changes the background color on the selected link, and remove that class on all other links, which is how I am changing the active link background.

```<code>var webComp = Vue.component('design-comp', {
  template: "#webComp",
  props:['trans-state'],
  components: {
      'project-comp': projectComp,
  },
  data: function() {
    return {
      activeProj: 'default',
    }
  },
  methods: {
    changeProj: function(proj) {
      this.activeProj = proj;
      var a = document.getElementsByClassName('projClick');
      for (i=0; i<a.length; i++) {
        a[i].classList.remove('projActive');
      }
      event.currentTarget.classList.add('projActive');
      document.getElementById('webContainer').scrollTop = 0;
    }
  },
  created: function() {
    this.activeProj = "default";
  }
});
</code>```

Here is the relevant portion of my SASS file:

```<code>#webContainer {
  margin-top: 50px;
  height: calc(100% - 50px);
  .projHeader {
    display: flex;
    justify-content: center;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    background-color: $headerColor;
    box-sizing: border-box;

    .projClick {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      height: 50px;
      box-sizing: border-box;
      background-color: $contentColor;
      border-right: 2px solid $headerColor;
      border-left: 2px solid $headerColor;
      border-bottom: 4px solid $headerColor;
      border-top: 4px solid $headerColor;
      flex-basis: 50px;
      transition: background-color 0.3s;

      &.projActive {
        background-color: $linkActiveColor;
      }

      p {
        color: $fontColor;
        font-family: $titleFont;
        font-size: 2em;
      }
    }
  }
}
</code>```

Here is the relevant HTML:

```<code><div class="viewContainer" id="webContainer">
        <div class="transitionBox"></div>
        <div class="stickyImageBottomLeft"><img src="./img/AfricaMountainPixelR.gif" /></div>
        <div class="stickyImageBottomRight"><img src="./img/AfricaMountainPixel.gif" /></div>
        <div class="projHeader">
            <div class="projClick projActive" v-on:click="changeProj('default')">
                <p>0</p>
            </div>
            <div class="projClick" v-on:click="changeProj('kyount')">
                <p>1</p>
            </div>
            <div class="projClick" v-on:click="changeProj('prodigal')">
                <p>2</p>
            </div>
            <div class="projClick" v-on:click="changeProj('joy')">
                <p>3</p>
            </div>
            <div class="projClick" v-on:click="changeProj('cgl')">
                <p>4</p>
            </div>
            <div class="projClick" v-on:click="changeProj('mikeg')">
                <p>5</p>
            </div>
            <div class="projClick" v-on:click="changeProj('reddit')">
                <p>6</p>
            </div>
            <div class="projClick" v-on:click="changeProj('westbeach')">
                <p>7</p>
            </div>
        </div>
        <div class="contentContainer">
        Project Page is loaded here
        </div>
</div>
</code>```

I'm hoping someone might know what is going on because I really don't see a reason for this to be happening.

答:
With the help of Kosh Very, I was able to find a solution that works perfectly while still keeping the intended style of the element.

```<code>#webContainer {
  margin-top: 50px;
  box-sizing: border-box;
  position: relative;
  height: 100%;

    .projHeader {
        ...
        position: fixed;
        ...
    }
}
</code>```

I still feel like the initial problem is a bug of some sort, but this is at least a workaround.

Body:
There is a very strange behavior with flexbox happening on a mobile browser.

Please see this gif for a visual of what's happening

This only happens on a mobile browser, I'm currently using Chrome mobile on a Google Pixel phone. I have a resize script running that resizes multiple elements on the page as a workaround for not being able to properly utilize 100vh like so:

window.onresize = function() {
        document.getElementById("backgroundImage").style.height = window.innerHeight;
        document.getElementById("mainScreen").style.height = window.innerHeight;
        if (window.innerWidth > 750) {
          document.getElementById("scrollContent").style.height = window.innerHeight - "96";
        } else {
          document.getElementById("scrollContent").style.height = window.innerHeight - "72";
        }
    };

The items that are being effected as seen in the gif are items in a flex container. This behavior happens when I scroll up to hide the navigation bar, then click one of the flex links.

I'm using Vuejs, and the content below is being populated by checking for a prop change. The flex links pass a string into a function that changes the project view to the selected project.

I also have a script to add a class that changes the background color on the selected link, and remove that class on all other links, which is how I am changing the active link background.

var webComp = Vue.component('design-comp', {
  template: "#webComp",
  props:['trans-state'],
  components: {
      'project-comp': projectComp,
  },
  data: function() {
    return {
      activeProj: 'default',
    }
  },
  methods: {
    changeProj: function(proj) {
      this.activeProj = proj;
      var a = document.getElementsByClassName('projClick');
      for (i=0; i<a.length; i++) {
        a[i].classList.remove('projActive');
      }
      event.currentTarget.classList.add('projActive');
      document.getElementById('webContainer').scrollTop = 0;
    }
  },
  created: function() {
    this.activeProj = "default";
  }
});

Here is the relevant portion of my SASS file:

#webContainer {
  margin-top: 50px;
  height: calc(100% - 50px);
  .projHeader {
    display: flex;
    justify-content: center;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    background-color: $headerColor;
    box-sizing: border-box;

    .projClick {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      height: 50px;
      box-sizing: border-box;
      background-color: $contentColor;
      border-right: 2px solid $headerColor;
      border-left: 2px solid $headerColor;
      border-bottom: 4px solid $headerColor;
      border-top: 4px solid $headerColor;
      flex-basis: 50px;
      transition: background-color 0.3s;

      &.projActive {
        background-color: $linkActiveColor;
      }

      p {
        color: $fontColor;
        font-family: $titleFont;
        font-size: 2em;
      }
    }
  }
}

Here is the relevant HTML:

0

1

2

3

4

5

6

7

        Project Page is loaded here

I'm hoping someone might know what is going on because I really don't see a reason for this to be happening.

Body:
With the help of Kosh Very, I was able to find a solution that works perfectly while still keeping the intended style of the element.

#webContainer {
  margin-top: 50px;
  box-sizing: border-box;
  position: relative;
  height: 100%;

    .projHeader {
        ...
        position: fixed;
        ...
    }
}

I still feel like the initial problem is a bug of some sort, but this is at least a workaround.


问:
What does "Scan advances the Scanner to the next token" mean in Go's bufio.Scanner?
According to Scanner.scan documents, Scan() advances the Scanner to the next token, but what does that mean? I find that Scanner.Text and Scanner.Bytes can be different, which is puzzling.

This code doesn't always cause an error, but as the file becomes larger it does:

```<code>func TestScanner(t *testing.T) {
    path := "/tmp/test.txt"
    f, err := os.Open(path)
    if err != nil {
        panic(fmt.Sprint("failed to open ", path))
    }
    defer f.Close()
    scanner := bufio.NewScanner(f)

    bs := make([][]byte, 0)
    for scanner.Scan() {
        bs = append(bs, scanner.Bytes())
    }

    f, err = os.Open(path)
    if err != nil {
        panic(fmt.Sprint("failed to open ", path))
    }
    defer f.Close()
    scanner = bufio.NewScanner(f)
    ss := make([]string, 0)
    for scanner.Scan() {
        ss = append(ss, scanner.Text())
    }

    for i, b := range bs {
        if string(b) != ss[i] {
            t.Errorf("expect %s, got %s", ss[i], string(b))
        }
    }
}
</code>```

答:
The token is defined by the scanner's split function. Scan() returns when the split function finds a token or there's an error.

The String() and Bytes() methods both return the current token. The String() method returns a copy of the token. The Bytes() method does not allocate memory and returns a slice that may use a backing array that's overwritten on a subsequent call to Scan().

Copy the slice returned from Bytes() to avoid this issue:

```<code>for scanner.Scan() {
    bs = append(bs, append([]byte(nil), scanner.Bytes()...))
}
</code>```

Body:
According to Scanner.scan documents, Scan() advances the Scanner to the next token, but what does that mean? I find that Scanner.Text and Scanner.Bytes can be different, which is puzzling.

This code doesn't always cause an error, but as the file becomes larger it does:

func TestScanner(t *testing.T) {
    path := "/tmp/test.txt"
    f, err := os.Open(path)
    if err != nil {
        panic(fmt.Sprint("failed to open ", path))
    }
    defer f.Close()
    scanner := bufio.NewScanner(f)

    bs := make([][]byte, 0)
    for scanner.Scan() {
        bs = append(bs, scanner.Bytes())
    }

    f, err = os.Open(path)
    if err != nil {
        panic(fmt.Sprint("failed to open ", path))
    }
    defer f.Close()
    scanner = bufio.NewScanner(f)
    ss := make([]string, 0)
    for scanner.Scan() {
        ss = append(ss, scanner.Text())
    }

    for i, b := range bs {
        if string(b) != ss[i] {
            t.Errorf("expect %s, got %s", ss[i], string(b))
        }
    }
}

Body:
The token is defined by the scanner's split function. Scan() returns when the split function finds a token or there's an error.

The String() and Bytes() methods both return the current token. The String() method returns a copy of the token. The Bytes() method does not allocate memory and returns a slice that may use a backing array that's overwritten on a subsequent call to Scan().

Copy the slice returned from Bytes() to avoid this issue:

for scanner.Scan() {
    bs = append(bs, append([]byte(nil), scanner.Bytes()...))
}


问:
Android apk with Firebase Test LAB
So I implement Admob ads to my apk and I want to upload my apk to Firebase Test Lab to make some test. But I'm not sure if it's okay to upload apk with ads to there. So my question is: Can I upload my apk with live ads to firebase to make some tests?</p>

答: I used firebase test lab pre-launch report with live ads for a year with no issue, but my last app got suspended for clicks on test lab.  I was having issues with screen loading on an version of Android and I think the lab may have clicked the ads in those tests, but doesn't normally click ads.  You could probably verify after each pre-launch report on the adsense console that you're not getting clicks and be fine, if you see clicks disable immediately.  Test lab does provide an IP address range, but it is not clear on how to programmaticly exclude these IP addresses, e.g. https://firebase.google.com/docs/test-lab/overview#testlab_and_mobile_advertising</p>

Title: Android apk with Firebase Test LAB


问:
Python Dictionary Syntax Error [learn python the hard way -ex39]
```<code>states = [
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
]
print states.Oregon
</code>```

<p>Why is this code showing syntax error in line 2?
Running on python 2.7.12 (default on ubuntu) </p>

答:
You're mixing up the syntax for a list and a dictionary in python.For representing keys and values we use a dictionary and we'll be using curly braces"{}" instead of "[]".
    Eg. Oregon represent a key,therefore to find the value for the corresponding
    key
    just type -> print states['Oregon'].This will print out the corresponding
    value i.e "OR"</p>

Body:
states = [
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
]
print states.Oregon

Why is this code showing syntax error in line 2?
Running on python 2.7.12 (default on ubuntu)


问:
How to make Ruby's Find.find follow symlinks?
I have a file hierarchy and some of the sub-directories are relative symlinks. I am using Ruby's Find.find to crawl through these dirs and find some specific files. However it's not looking into any directory which is a symlink (it follows files which are symlinks).

Looking at the source code it seems the problem is because it's using File.lstat(file).directory? to test if something is a directory. This returns false for symlinks but File.stat.directory? returns true.

How can I make Find.find follow symlinks, short of monkey patching it to use File.stat instead of File.lstat?

答:
Here is a simpler and more efficient version of the recursive Pathname method:</p>

```<code>def find_files(*paths)
  paths.flatten.map do |path|
    path = Pathname.new(path)
    path.file? ? [path.to_s] : find_files(path.children)
  end.flatten
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is a simpler and more efficient version of the recursive Pathname method:

def find_files(*paths)
  paths.flatten.map do |path|
    path = Pathname.new(path)
    path.file? ? [path.to_s] : find_files(path.children)
  end.flatten
end


问:
org.apache.commons.net.io.CopyStreamException: IOException caught while copying
I'm trying to copy some files created in my server to FTP using code in below method. But weird thing is i'm getting below error randomly and i couldn't figure out what is happening.

```<code>Exception =org.apache.commons.net.io.CopyStreamException: IOException caught while copying.
</code>```

Below is the code by which i'm copying the files to FTP.

```<code>public void copyDumpsToFTP() throws SocketException, IOException
  {

      FTPClient f= new FTPClient();
      f.connect(dumpProperties.getProperty("ftpIPAddress"));
      boolean flag =f.login(dumpProperties.getProperty("ftpUser"),dumpProperties.getProperty("ftpPassword"));
      System.out.println(" is connected to FTP ::"+flag);

      // setting fileType to binary

      boolean isFileTypeChanged =f.setFileType(FTP.BINARY_FILE_TYPE);

      // System.out.println(" Is file type changed to binary :: "+isFileTypeChanged);
      // change working directory of FTP Server

      boolean isDirectoryChanged =f.changeWorkingDirectory(dumpProperties.getProperty("ftpDirectory"));

      System.out.println(" Is the FTP working directory Changed :: "+isDirectoryChanged);

      // to copy engineering dump from source to FTP

      InputStream inputFileEngg = new FileInputStream(new File(dumpNameEngineering));

      boolean isSavedEngg = f.storeFile(dumpProperties.getProperty("dumpNameOfEnggInFTP"), inputFileEngg);
      System.out.println("is Engineering dump File Saved in FTP Server :: "+isSavedEngg);
      System.out.println(" Engg Dump sucessfully Created and Saved in FTP...");

   // to copy correspondance dump from source to FTP

     InputStream inputFileCorr = new FileInputStream(new File(dumpNameCorrespondance));

      boolean isSavedCorr = f.storeFile(dumpProperties.getProperty("dumpNameOfCorrInFTP"), inputFileCorr);
      System.out.println("is Correspondance File Saved in FTP Server :: "+isSavedCorr);
      System.out.println(" Correspondance Dump sucessfully Created and Saved in FTP...");

   // to copy tmg dump from source to FTP

       InputStream inputFileTmg = new FileInputStream(new File(dumpNameTmg));

      boolean isSavedTmg = f.storeFile(dumpProperties.getProperty("dumpNameOfTmgInFTP"), inputFileTmg);
      System.out.println("is TMG File Saved in FTP Server :: "+isSavedTmg);
      System.out.println(" TMG Dump sucessfully Created and Saved in FTP...");

  }
</code>```

The program is executing till SOP statement Is the FTP working directory Changed :: true

and latter it had thrown error as mentioned above.

答: This error occurred when disk space is not available or disk quote exceed.   </p>

Body:
I'm trying to copy some files created in my server to FTP using code in below method. But weird thing is i'm getting below error randomly and i couldn't figure out what is happening.

Exception =org.apache.commons.net.io.CopyStreamException: IOException caught while copying.

Below is the code by which i'm copying the files to FTP.

public void copyDumpsToFTP() throws SocketException, IOException
  {

      FTPClient f= new FTPClient();
      f.connect(dumpProperties.getProperty("ftpIPAddress"));
      boolean flag =f.login(dumpProperties.getProperty("ftpUser"),dumpProperties.getProperty("ftpPassword"));
      System.out.println(" is connected to FTP ::"+flag);

      // setting fileType to binary

      boolean isFileTypeChanged =f.setFileType(FTP.BINARY_FILE_TYPE);

      // System.out.println(" Is file type changed to binary :: "+isFileTypeChanged);
      // change working directory of FTP Server

      boolean isDirectoryChanged =f.changeWorkingDirectory(dumpProperties.getProperty("ftpDirectory"));

      System.out.println(" Is the FTP working directory Changed :: "+isDirectoryChanged);

      // to copy engineering dump from source to FTP

      InputStream inputFileEngg = new FileInputStream(new File(dumpNameEngineering));

      boolean isSavedEngg = f.storeFile(dumpProperties.getProperty("dumpNameOfEnggInFTP"), inputFileEngg);
      System.out.println("is Engineering dump File Saved in FTP Server :: "+isSavedEngg);
      System.out.println(" Engg Dump sucessfully Created and Saved in FTP...");

   // to copy correspondance dump from source to FTP

     InputStream inputFileCorr = new FileInputStream(new File(dumpNameCorrespondance));

      boolean isSavedCorr = f.storeFile(dumpProperties.getProperty("dumpNameOfCorrInFTP"), inputFileCorr);
      System.out.println("is Correspondance File Saved in FTP Server :: "+isSavedCorr);
      System.out.println(" Correspondance Dump sucessfully Created and Saved in FTP...");

   // to copy tmg dump from source to FTP

       InputStream inputFileTmg = new FileInputStream(new File(dumpNameTmg));

      boolean isSavedTmg = f.storeFile(dumpProperties.getProperty("dumpNameOfTmgInFTP"), inputFileTmg);
      System.out.println("is TMG File Saved in FTP Server :: "+isSavedTmg);
      System.out.println(" TMG Dump sucessfully Created and Saved in FTP...");

  }

The program is executing till SOP statement Is the FTP working directory Changed :: true

and latter it had thrown error as mentioned above.


问:
Sequence does not exist exception while using Generation annotation in Hibernate
Please see my Model class:

```<code>import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="STUDENT")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="student_id")
    private String studentId;

    @Column(name="student_name")
    private String studentName;

    public String getStudentId() {
        return studentId;
    }
    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
}
</code>```

and save it to DB like below:

```<code>public static void test4()
{
    Student st = new Student();
    st.setStudentName("Bitt");

    SessionFactory sessionF = new Configuration().configure().buildSessionFactory();
    Session session = sessionF.openSession();
    session.beginTransaction();
    session.save(st);

    st = new Student();
    st.setStudentName("Rock");
    session.save(st);
    session.getTransaction().commit();
    session.close();
}
</code>```

the background DB is Oracle11g, Hibernate version is hibernate-core-5.2.10.Final.jar.

from my opinion, if studentId is String data type, hibernate should generate a random string, if studentId is int data type, hibernate should generate a unique number to make sure it is not duplicate in DB, but I got following error message:

```<code>Jun 06, 2017 9:20:10 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
Jun 06, 2017 9:20:10 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 06, 2017 9:20:10 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@16.165.180.124:1521:orcl]
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=hibernate, password=****}
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jun 06, 2017 9:20:11 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Hibernate: select hibernate_sequence.nextval from dual
Jun 06, 2017 9:20:12 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2289, SQLState: 42000
Jun 06, 2017 9:20:12 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02289: sequence does not exist

Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
    at org.hibernate.id.enhanced.SequenceStructure$1.getNextValue(SequenceStructure.java:95)
    at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
    at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:432)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)
    at org.dxc.java.hibernate.main.HibernateDriver.test4(HibernateDriver.java:73)
    at org.dxc.java.hibernate.main.HibernateDriver.main(HibernateDriver.java:19)
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:886)
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3657)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1495)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:71)
    ... 14 more
</code>```

so, how can I have hibernate to generate the primary key value automatically for me?

答:
Please change your code to this and check once,

```<code>@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="student_id")
private Integer studentId;
</code>```

@GeneratedValue(strategy = GenerationType.AUTO)

This gives you a numeric long value which is auto updated for studentId, each and every record you add.

Body:
Please see my Model class:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="STUDENT")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="student_id")
    private String studentId;

    @Column(name="student_name")
    private String studentName;

    public String getStudentId() {
        return studentId;
    }
    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
}

and save it to DB like below:

public static void test4()
{
    Student st = new Student();
    st.setStudentName("Bitt");

    SessionFactory sessionF = new Configuration().configure().buildSessionFactory();
    Session session = sessionF.openSession();
    session.beginTransaction();
    session.save(st);

    st = new Student();
    st.setStudentName("Rock");
    session.save(st);
    session.getTransaction().commit();
    session.close();
}

the background DB is Oracle11g, Hibernate version is hibernate-core-5.2.10.Final.jar.

from my opinion, if studentId is String data type, hibernate should generate a random string, if studentId is int data type, hibernate should generate a unique number to make sure it is not duplicate in DB, but I got following error message:

Jun 06, 2017 9:20:10 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
Jun 06, 2017 9:20:10 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 06, 2017 9:20:10 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@16.165.180.124:1521:orcl]
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=hibernate, password=****}
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jun 06, 2017 9:20:11 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Hibernate: select hibernate_sequence.nextval from dual
Jun 06, 2017 9:20:12 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2289, SQLState: 42000
Jun 06, 2017 9:20:12 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02289: sequence does not exist

Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
    at org.hibernate.id.enhanced.SequenceStructure$1.getNextValue(SequenceStructure.java:95)
    at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
    at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:432)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)
    at org.dxc.java.hibernate.main.HibernateDriver.test4(HibernateDriver.java:73)
    at org.dxc.java.hibernate.main.HibernateDriver.main(HibernateDriver.java:19)
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:886)
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3657)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1495)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:71)
    ... 14 more

so, how can I have hibernate to generate the primary key value automatically for me?

Body:
Please change your code to this and check once,

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="student_id")
private Integer studentId;

@GeneratedValue(strategy = GenerationType.AUTO)

This gives you a numeric long value which is auto updated for studentId, each and every record you add.


问:
AHBottomNavigation always on front of FloatingActionButton
I'm trying to create a layout with an FAB on top of the bottom navigation menu, but the menu always stays above the button. :(

My layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container"
    tools:context="com.example.mytest.money.MainActivity">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="110dp"
        android:padding="15dp"
        card_view:cardElevation="2dp"
        card_view:cardCornerRadius="4dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Test" />

    </android.support.v7.widget.CardView>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"
        android:layout_alignParentTop="true"
        android:foreground="@color/colorBackground">
    </ScrollView>

    <com.aurelhubert.ahbottomnavigation.AHBottomNavigation
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:selectedBackgroundVisible="false"
        android:layout_gravity="bottom" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/create_gain_expense"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:layout_margin="15dp"
        android:layout_above="@id/bottom_navigation"
        android:src="@drawable/ic_add_white_24dp"
        app:fabSize="normal" />

</android.support.design.widget.CoordinatorLayout>
</code>```

What I expect:

Expectation

What I got:

Reality

What can I do to change this? :D

答:
I guess the problem is, AHBottomNavigation has higher elevation than FloatingActionButton that's why its showing above the FloatingActionButton.

FloatingActionButton has default 6dp elevation and the default elevation of AHBottomNavigation is 8dp(From AHBottomNavigation source)

Try setting more higher elevation to FloatingActionButton:

```<code><android.support.design.widget.FloatingActionButton
    android:id="@+id/create_gain_expense"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"
    android:layout_margin="15dp"
    android:layout_above="@id/bottom_navigation"
    android:src="@drawable/ic_add_white_24dp"
    app:fabSize="normal"
    app:elevation="12dp"
    app:borderWidth="0dp" />
</code>```

#. You can also use android.support.design.widget.BottomNavigationView instead of AHBottomNavigation.

Below is an Orthographic view of app structure:

See documentation.

Hope this will help~

Body:
I'm trying to create a layout with an FAB on top of the bottom navigation menu, but the menu always stays above the button. :(

My layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container"
    tools:context="com.example.mytest.money.MainActivity">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="110dp"
        android:padding="15dp"
        card_view:cardElevation="2dp"
        card_view:cardCornerRadius="4dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Test" />

    </android.support.v7.widget.CardView>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"
        android:layout_alignParentTop="true"
        android:foreground="@color/colorBackground">
    </ScrollView>

    <com.aurelhubert.ahbottomnavigation.AHBottomNavigation
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:selectedBackgroundVisible="false"
        android:layout_gravity="bottom" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/create_gain_expense"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:layout_margin="15dp"
        android:layout_above="@id/bottom_navigation"
        android:src="@drawable/ic_add_white_24dp"
        app:fabSize="normal" />

</android.support.design.widget.CoordinatorLayout>

What I expect:

Expectation

What I got:

Reality

What can I do to change this? :D

Body:
I guess the problem is, AHBottomNavigation has higher elevation than FloatingActionButton that's why its showing above the FloatingActionButton.

FloatingActionButton has default 6dp elevation and the default elevation of AHBottomNavigation is 8dp(From AHBottomNavigation source)

Try setting more higher elevation to FloatingActionButton:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/create_gain_expense"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"
    android:layout_margin="15dp"
    android:layout_above="@id/bottom_navigation"
    android:src="@drawable/ic_add_white_24dp"
    app:fabSize="normal"
    app:elevation="12dp"
    app:borderWidth="0dp" />

#. You can also use android.support.design.widget.BottomNavigationView instead of AHBottomNavigation.

Below is an Orthographic view of app structure:

See documentation.

Hope this will help~