问:
Why does code with std::vector not compile but with std::unique_ptr it does, if there is no noexcept move constructor?
Why can the following program not be compiled?

NB: something_t's move constructor is not noexcept.

```<code>#include <memory>
#include <vector>

class something_t {
public:
    constexpr something_t() = default;

    constexpr something_t(const something_t& other)
        : field_(other.field_) {
    }

    constexpr something_t(something_t&& other)
        : field_(other.field_) {
    }

private:
    unsigned int field_{ 0 };
};

struct data_t {
    something_t something;
    std::vector<std::unique_ptr<int>> move_only; // <-- this line
};

int main() {
    std::vector<data_t> result;
    data_t data;
    result.push_back(std::move(data));
    return 0;
}
</code>```

Error is (within g++):

```<code>/usr/include/c++/9/bits/stl_uninitialized.h:127:72: error: static assertion failed: result type must be constructible from value type of input range
127 |       static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
    |                                                                        ^~~~~
</code>```

(nearly the same with clang and MSVC).

If I replace the line with the "this line" comment by std::unique_ptr<int> move_only then the code compiles fine:

```<code>    struct data_t {
        something_t something;
        std::unique_ptr<int> move_only;
    };
</code>```

Why does removing std::vector help? It also compiles with or without std::vector if I make the something_t move constructor noexcept.

NB: adding noexcept to something_t's move constructor helps, but that's not the question.

Question is:

Why with this:

```<code>    struct data_t {
        something_t something;
        std::unique_ptr<int> move_only;
    };
</code>```

does the program compile?

But with

```<code>struct data_t {
    something_t something;
    std::vector<std::unique_ptr<int>> move_only; // <-- this line
};
</code>```

does the program NOT compile?

In fact, both std::unique_ptr<int> and std::vector<std::unique_ptr<int>>:

non-copyable

noexcept-moveable

So they have the same properties.

Update: I've tried to compare the type_traits of both variants:

```<code>                                                data_t(vector)          data_t(unique_ptr):
is_constructible:                               true                    true
is_trivially_constructible:                     false                   false
is_nothrow_constructible:                       true                    true
is_default_constructible:                       true                    true
is_trivially_default_constructible:             false                   false
is_nothrow_default_constructible:               true                    true
is_copy_constructible:                          true                    false
is_trivially_copy_constructible:                false                   false
is_nothrow_copy_constructible:                  false                   false
is_move_constructible:                          true                    true
is_trivially_move_constructible:                false                   false
is_nothrow_move_constructible:                  false                   false
is_assignable:                                  false                   false
is_trivially_assignable:                        false                   false
is_nothrow_assignable:                          false                   false
is_copy_assignable:                             false                   false
is_trivially_copy_assignable:                   false                   false
is_nothrow_copy_assignable:                     false                   false
is_move_assignable:                             false                   false
is_trivially_move_assignable:                   false                   false
is_nothrow_move_assignable:                     false                   false
is_destructible:                                true                    true
is_trivially_destructible:                      false                   false
is_nothrow_destructible:                        true                    true
is_swappable:                                   false                   false
is_nothrow_swappable:                           false                   false
</code>```

The only difference is:

```<code>is_copy_constructible:                          true                    false
</code>```

I.e., data_t with vector is copy-constructible, and with unique_ptr it is not. But how can this difference affect compilation?

答:
The important difference here is:

```<code>std::is_copy_constructible<std::vector<std::unique_ptr<int>>>::value == true
std::is_copy_constructible<std::unique_ptr<int>>::value == false
</code>```

That first one is maybe surprising. But note that is_copy_constructible and most similar type traits only require that the operation they test is declared, not that it would be valid to actually use. std::vector unfortunately lacks some "SFINAE correctness" here, but that might be intentional for backwards compatibility.

The Standard's description of template <class T, class Allocator> class vector in [vector.overview]/2 simply says that it declares a member vector(const vector& x);. The following sections say nothing else about the copy constructor. In particular, std::vector doesn't have a piece similar to this sentence from [optional.ctor]/6 about the copy constructor of std::optional<T>:

```<code>constexpr optional(const optional& rhs);
</code>```

Remarks: This constructor shall be defined as deleted unless is_copy_constructible_v<T> is true.

Because of the various requirements on std::vector<T>, its functions like push_back, insert, and emplace which need to deal with the possibility of reallocating and populating new memory with elements already in the vector are forced to be implemented like this:

If std::is_nothrow_move_constructible<T>::value is true, uses the move constructor of T, and the functions provide the strong exception guarantee.

If std::is_nothrow_move_constructible<T>::value is false and std::is_copy_constructible<T>::value is true, uses the copy constructor of T, and the functions provide the strong exception guarantee.

If std::is_nothrow_move_constructible<T>::value and std::is_copy_constructible<T>::value are both false, uses the move constructor of T, but the functions cannot provide the strong exception guarantee.

(T must be move constructible, which might actually mean using a copy constructor, as a general requirement of these container functions.)

So when data_t has a std::vector<std::unique_ptr<int>> member, it "incorrectly" has an implicitly declared copy constructor which is not deleted. This leads to std::vector<data_t>::push_back choosing the second option from the list above, but the actual use of the copy constructor leads to errors.

When data_t has a std::unique_ptr<int> member, its deleted copy constructor means that the implicitly declared copy constructor of data_t is also deleted. So in this case, std::vector<data_t>::push_back chooses the third option from the list above, using the move constructor, but if it does throw, the vector is left in an unspecified state.

Body:
Why can the following program not be compiled?

NB: something_t's move constructor is not noexcept.

#include <memory>
#include <vector>

class something_t {
public:
    constexpr something_t() = default;

    constexpr something_t(const something_t& other)
        : field_(other.field_) {
    }

    constexpr something_t(something_t&& other)
        : field_(other.field_) {
    }

private:
    unsigned int field_{ 0 };
};

struct data_t {
    something_t something;
    std::vector<std::unique_ptr<int>> move_only; // <-- this line
};

int main() {
    std::vector<data_t> result;
    data_t data;
    result.push_back(std::move(data));
    return 0;
}

Error is (within g++):

/usr/include/c++/9/bits/stl_uninitialized.h:127:72: error: static assertion failed: result type must be constructible from value type of input range
127 |       static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
    |                                                                        ^~~~~

(nearly the same with clang and MSVC).

If I replace the line with the "this line" comment by std::unique_ptr<int> move_only then the code compiles fine:

    struct data_t {
        something_t something;
        std::unique_ptr<int> move_only;
    };

Why does removing std::vector help? It also compiles with or without std::vector if I make the something_t move constructor noexcept.

NB: adding noexcept to something_t's move constructor helps, but that's not the question.

Question is:

Why with this:

    struct data_t {
        something_t something;
        std::unique_ptr<int> move_only;
    };

does the program compile?

But with

struct data_t {
    something_t something;
    std::vector<std::unique_ptr<int>> move_only; // <-- this line
};

does the program NOT compile?

In fact, both std::unique_ptr<int> and std::vector<std::unique_ptr<int>>:

non-copyable

noexcept-moveable

So they have the same properties.

Update: I've tried to compare the type_traits of both variants:

                                                data_t(vector)          data_t(unique_ptr):
is_constructible:                               true                    true
is_trivially_constructible:                     false                   false
is_nothrow_constructible:                       true                    true
is_default_constructible:                       true                    true
is_trivially_default_constructible:             false                   false
is_nothrow_default_constructible:               true                    true
is_copy_constructible:                          true                    false
is_trivially_copy_constructible:                false                   false
is_nothrow_copy_constructible:                  false                   false
is_move_constructible:                          true                    true
is_trivially_move_constructible:                false                   false
is_nothrow_move_constructible:                  false                   false
is_assignable:                                  false                   false
is_trivially_assignable:                        false                   false
is_nothrow_assignable:                          false                   false
is_copy_assignable:                             false                   false
is_trivially_copy_assignable:                   false                   false
is_nothrow_copy_assignable:                     false                   false
is_move_assignable:                             false                   false
is_trivially_move_assignable:                   false                   false
is_nothrow_move_assignable:                     false                   false
is_destructible:                                true                    true
is_trivially_destructible:                      false                   false
is_nothrow_destructible:                        true                    true
is_swappable:                                   false                   false
is_nothrow_swappable:                           false                   false

The only difference is:

is_copy_constructible:                          true                    false

I.e., data_t with vector is copy-constructible, and with unique_ptr it is not. But how can this difference affect compilation?

Body:
The important difference here is:

std::is_copy_constructible<std::vector<std::unique_ptr<int>>>::value == true
std::is_copy_constructible<std::unique_ptr<int>>::value == false

That first one is maybe surprising. But note that is_copy_constructible and most similar type traits only require that the operation they test is declared, not that it would be valid to actually use. std::vector unfortunately lacks some "SFINAE correctness" here, but that might be intentional for backwards compatibility.

The Standard's description of template <class T, class Allocator> class vector in [vector.overview]/2 simply says that it declares a member vector(const vector& x);. The following sections say nothing else about the copy constructor. In particular, std::vector doesn't have a piece similar to this sentence from [optional.ctor]/6 about the copy constructor of std::optional<T>:

constexpr optional(const optional& rhs);

Remarks: This constructor shall be defined as deleted unless is_copy_constructible_v<T> is true.

Because of the various requirements on std::vector<T>, its functions like push_back, insert, and emplace which need to deal with the possibility of reallocating and populating new memory with elements already in the vector are forced to be implemented like this:

If std::is_nothrow_move_constructible<T>::value is true, uses the move constructor of T, and the functions provide the strong exception guarantee.

If std::is_nothrow_move_constructible<T>::value is false and std::is_copy_constructible<T>::value is true, uses the copy constructor of T, and the functions provide the strong exception guarantee.

If std::is_nothrow_move_constructible<T>::value and std::is_copy_constructible<T>::value are both false, uses the move constructor of T, but the functions cannot provide the strong exception guarantee.

(T must be move constructible, which might actually mean using a copy constructor, as a general requirement of these container functions.)

So when data_t has a std::vector<std::unique_ptr<int>> member, it "incorrectly" has an implicitly declared copy constructor which is not deleted. This leads to std::vector<data_t>::push_back choosing the second option from the list above, but the actual use of the copy constructor leads to errors.

When data_t has a std::unique_ptr<int> member, its deleted copy constructor means that the implicitly declared copy constructor of data_t is also deleted. So in this case, std::vector<data_t>::push_back chooses the third option from the list above, using the move constructor, but if it does throw, the vector is left in an unspecified state.


来源: stackexchange

问:
How to add columns from a data frame to another based on a common column with different values?
I have two data frame both of them has a column"Country" common but in df1 it has 223 countries(means 223 rows) and in df2 it has only 188 countries(188 rows), both data frames have different columns values for ex.: df1 columns are(18) it contain the "Country", "Population", ....etc, and df2 column are(7) it contain "Country", "GNP", "Capital city",....etc.

I want to merge both data frames and match the values of columns in df2 according to the main column in df1 the "Country", so it adds the Population value from df2 for the exact "Country" that exists in df1 and a NaN for the one is missing.
I have tried .join(), .merge(), and .concat(), none of these function gave me the required result.

答:
The problem solved by arranging the csv files using Excel, made country column have 223 rows for both data frams, then I used

```<code>    df=pd.concat([df1,df2],axis=1)
    df=df.reset_index(drop=True)
</code>```

I got the required results.

ContentLicense: CC BY-SA 4.0

Body:
The problem solved by arranging the csv files using Excel, made country column have 223 rows for both data frams, then I used

    df=pd.concat([df1,df2],axis=1)
    df=df.reset_index(drop=True)

I got the required results.


问:
Eigen: dividing a vector by a scalar in two steps works but not in one step
So I'm trying to implement Power iteration to find the greatest eigenvalue and corresponding eigenvector in C++. I'm using the Eigen library. The weird thing is that, when I divide a vector by a scalar in a single line (marked in line (1)), it throws an error, and is as helpful as C++ errors can be:

```<code>No viable conversion from 'typename internal::enable_if<true, const CwiseBinaryOp<internal::scalar_quotient_op<typename internal::traits<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0> >::Scalar, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>, const Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, const typename internal::plain_constant_type<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>::type> >::type'
(aka 'const Eigen::CwiseBinaryOp<Eigen::internal::scalar_quotient_op<double, double>, const Eigen::Product<Eigen::Product<Eigen::Transpose<Eigen::Matrix<double, -1, 1, 0, -1, 1> >, Eigen::Matrix<double, -1, -1, 1, -1, -1>, 0>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, 0>, const Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, const Eigen::Matrix<double, 1, 1, 0, 1, 1> > >')
to 'double'
</code>```

but when I do it in two steps (marked in line (2)), everything is fine and no errors are thrown. So I find it very weird that Eigen can't do division by scalars in a single step. What is happening here, why it fails when I do it on a single line?

```<code>pair<double, Vector> power_iteration(const Matrix& X, unsigned num_iter, double eps)
{
    Vector b = Vector::Random(X.cols());
    b.normalize();
    Vector b_old;
    for(unsigned int i = 0; i < num_iter; i++){
        b_old =b;
        b = X*b_old;
        b.normalize();
        double cos_angle = b.dot(b_old);
        if(cos_angle > 1-eps){
            i= num_iter+1;
        }
    }

   (1)  double eigenvalue = (b.transpose() * X * b)/(b.transpose().dot(b));

   (2)  double eigenvalue2 = b.transpose() * X * b;
    eigenvalue2 = eigenvalue2/b.transpose().dot(b);

    return make_pair(eigenvalue, b / b.norm());
}
</code>```

答:
In (2), when you assign the former expression first, it triggers an implicit conversion to double since the variable to which it's assigned to is a double.
In (1), the former expression is first evaluated which seems to be of a type of a higher rank defined by the Eigen library, and the later double expression (the dot product) cannot be promoted to this type, hence the error.
If you tell the compiler explicitly that you want b.transpose() * X * b to be reduced to a double, it will work:

```<code>double eigenvalue = static_cast<double>(b.transpose() * X * b)/(b.transpose().dot(b));
</code>```

Body:
So I'm trying to implement Power iteration to find the greatest eigenvalue and corresponding eigenvector in C++. I'm using the Eigen library. The weird thing is that, when I divide a vector by a scalar in a single line (marked in line (1)), it throws an error, and is as helpful as C++ errors can be:

No viable conversion from 'typename internal::enable_if<true, const CwiseBinaryOp<internal::scalar_quotient_op<typename internal::traits<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0> >::Scalar, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>, const Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, const typename internal::plain_constant_type<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>::type> >::type'
(aka 'const Eigen::CwiseBinaryOp<Eigen::internal::scalar_quotient_op<double, double>, const Eigen::Product<Eigen::Product<Eigen::Transpose<Eigen::Matrix<double, -1, 1, 0, -1, 1> >, Eigen::Matrix<double, -1, -1, 1, -1, -1>, 0>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, 0>, const Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, const Eigen::Matrix<double, 1, 1, 0, 1, 1> > >')
to 'double'

but when I do it in two steps (marked in line (2)), everything is fine and no errors are thrown. So I find it very weird that Eigen can't do division by scalars in a single step. What is happening here, why it fails when I do it on a single line?

pair<double, Vector> power_iteration(const Matrix& X, unsigned num_iter, double eps)
{
    Vector b = Vector::Random(X.cols());
    b.normalize();
    Vector b_old;
    for(unsigned int i = 0; i < num_iter; i++){
        b_old =b;
        b = X*b_old;
        b.normalize();
        double cos_angle = b.dot(b_old);
        if(cos_angle > 1-eps){
            i= num_iter+1;
        }
    }

   (1)  double eigenvalue = (b.transpose() * X * b)/(b.transpose().dot(b));

   (2)  double eigenvalue2 = b.transpose() * X * b;
    eigenvalue2 = eigenvalue2/b.transpose().dot(b);

    return make_pair(eigenvalue, b / b.norm());
}

Body:
In (2), when you assign the former expression first, it triggers an implicit conversion to double since the variable to which it's assigned to is a double.
In (1), the former expression is first evaluated which seems to be of a type of a higher rank defined by the Eigen library, and the later double expression (the dot product) cannot be promoted to this type, hence the error.
If you tell the compiler explicitly that you want b.transpose() * X * b to be reduced to a double, it will work:

double eigenvalue = static_cast<double>(b.transpose() * X * b)/(b.transpose().dot(b));


问:
Is Amazon EC2 free tier server appropriate for my little web application?
I'm building a little software activation web service in Java, so I need a cloud-based server which will run Apache and Tomcat and MySQL.

It will get very little usage as I don't expect to sell very much product at first.  I'll be very lucky if the server handles one quick activation a day ... if it got 20 in a day that would be an amazing success.

I'm looking at Amazon EC2 pricing here ...

https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc

I see that there is a "Free Tier" which provides "750 hours per month of Linux t2.micro or t3.micro instance".  And it's free for year.

STUPID QUESTION #1: 24h/day x 31 days/month is 744 hours ... so, does that mean I'm getting a free linux server running 24/7 for a year or is there a catch that I'm missing?

STUPID QUESTION #2: t2.micro/t2.micro has 1 vCPU, 1GB Memory ... is that enough power to run a simple Apache + Tomcat + MySQL web service reliably?

STUPID QUESTION #3: Any reason why I should skip the free tier and invest in a powerful pay $$$ option?

答: There might be a limitation on network traffic for EC2 instances. You should look into that before deciding to host a web service on it. There is even a possibility it could charge you for using too much network bandwidth, so scalability might be an issue. I suggest you try Heroku instead, and then switch to other app hosting services when if and when you need to scale.</p>


问:
Efficient MySQL table structure for rating system
This post is a follow-up of this answered question: Best method for storing a list of user IDs.

I took cletus and Mehrdad Afshari's epic advice of using a normalized database approach. Are the following tables properly set up for proper optimization? I'm kind of new to MySQL efficiency, so I want to make sure this is effective.

Also, when it comes to finding the average rating for a game and the total number of votes should I use the following two queries, respectively?

```<code>SELECT avg(vote) FROM votes WHERE uid = $uid AND gid = $gid;
SELECT count(uid) FROM votes WHERE uid = $uid AND gid = $gid;

CREATE TABLE IF NOT EXISTS `games` (
  `id` int(8) NOT NULL auto_increment,
  `title` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(8) NOT NULL auto_increment,
  `username` varchar(20) NOT NULL,
  PRIMARY KEY  (`id`)
) AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `votes` (
  `uid` int(8) NOT NULL,
  `gid` int(8) NOT NULL,
  `vote` int(1) NOT NULL,
  KEY `uid` (`uid`,`gid`)
) ;
</code>```

答:
Looks good so far. Don't forget indices and foreign keys. In my experience most issues don't arise from not-so-well-thought-out designs but from the lack of indices and foreign keys.

Also, regarding the storage engine selection I have yet to see a reason (in a reasonably complex/sized app) for not using innodb, not just because of transactional semantics.

ContentLicense: CC BY-SA 2.5

Body:
This post is a follow-up of this answered question: Best method for storing a list of user IDs.

I took cletus and Mehrdad Afshari's epic advice of using a normalized database approach. Are the following tables properly set up for proper optimization? I'm kind of new to MySQL efficiency, so I want to make sure this is effective.

Also, when it comes to finding the average rating for a game and the total number of votes should I use the following two queries, respectively?

SELECT avg(vote) FROM votes WHERE uid = $uid AND gid = $gid;
SELECT count(uid) FROM votes WHERE uid = $uid AND gid = $gid;

CREATE TABLE IF NOT EXISTS `games` (
  `id` int(8) NOT NULL auto_increment,
  `title` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(8) NOT NULL auto_increment,
  `username` varchar(20) NOT NULL,
  PRIMARY KEY  (`id`)
) AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `votes` (
  `uid` int(8) NOT NULL,
  `gid` int(8) NOT NULL,
  `vote` int(1) NOT NULL,
  KEY `uid` (`uid`,`gid`)
) ;

OwnerDisplayName: jjungnickel

LastEditorDisplayName: jjungnickel


问:
blackberry tableview solution for jde 4.5
I am very new to blackberry table view. I am using jde 4.5. Can anyone please which is best way  to show

by this forum :  http://devblog.blackberry.com/2009/10/how-to-use-table-view-layout/

or Customize ListField

I want a structure like below

Text

Text               |  ButtonField

Text               |  ButtonField

Text

---------------------------------

Text

Text               |  ButtonField

Text               |  ButtonField

Text

Thanks in advance

Regards,
Sathish

答: You can use the new TableModel class in OS 6. There is sample code and explanation on how to do it in blackberry docs. check out this link  - http://docs.blackberry.com/en/developers/deliverables/29204/Table_Model_1328111_11.jsp</p>

ContentLicense: CC BY-SA 3.0


问:
Cannot get bot to autoban new accounts on Discord
The bot is very simple and will ultimately not require any input from me.  What I want the bot to do is to check the age of an account that joins and then ban them if they are a new account made within the past 10 minutes.  The part that I'm stuck on is calculating the time I think.  The bot isn't giving any errors, it's just not banning the new account that I made.  For testing purpose, I put the bot onto a new server I"m making that doesn't have anyone else on it and also changed the amount of time to 14400 seconds so that it's within 10 days and should give me enough time to figure out what's wrong.

Here's my code as it stands:

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
  console.log("I am ready!");
});

client.on("message", (message) => {
  if (message.content.startsWith("ping")) {
    message.channel.send("pong!");
  }
});

client.on("guildMemberAdd", (member) => {
    if (Date.now() - member.user.createdAt <= 14400) {
        guildMember.ban({ days: 14, reason: 'New account' })
    }
});

client.login("Token");```

member.client.user.createdAt is the section that I think I'm having a problem with.  When I run a debug on Date.now() that works fine but I can't seem to get it to calculate the age of an account that joins.

I'm pretty sure that this is the property I need but I must be calling it incorrectly.  Please forgive any ignorance, I'm super new to js.

https://discord.js.org/#/docs/main/master/class/User?scrollTo=createdAt

I would love to know what I'm doing wrong.  Thanks!

答:
Finally figured out the problem.  The issue is actually multi-part here.  The first issue is that I thought it was calculating in seconds, but instead it's actually calculating in milliseconds so the if statement was never true.  Once I made that true by increasing the time to 10 days in milliseconds, I got an error on the guildMember since it wasn't defined.  I changed that to member and then got an error on the days that it can't be more than 7.  Here's the final working code.

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
  console.log("I am ready!");
});

client.on("message", (message) => {
  if (message.content.startsWith("ping")) {
    message.channel.send("pong!");
  }
});

client.on("guildMemberAdd", (member) => {
    if (Date.now() - member.user.createdAt <= 864000000) {
        member.ban({ days: 7, reason: 'New account' })
    }
});

client.login("Token");```

Body:
The bot is very simple and will ultimately not require any input from me.  What I want the bot to do is to check the age of an account that joins and then ban them if they are a new account made within the past 10 minutes.  The part that I'm stuck on is calculating the time I think.  The bot isn't giving any errors, it's just not banning the new account that I made.  For testing purpose, I put the bot onto a new server I"m making that doesn't have anyone else on it and also changed the amount of time to 14400 seconds so that it's within 10 days and should give me enough time to figure out what's wrong.

Here's my code as it stands:

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
  console.log("I am ready!");
});

client.on("message", (message) => {
  if (message.content.startsWith("ping")) {
    message.channel.send("pong!");
  }
});

client.on("guildMemberAdd", (member) => {
    if (Date.now() - member.user.createdAt <= 14400) {
        guildMember.ban({ days: 14, reason: 'New account' })
    }
});

client.login("Token");

member.client.user.createdAt is the section that I think I'm having a problem with.  When I run a debug on Date.now() that works fine but I can't seem to get it to calculate the age of an account that joins.

I'm pretty sure that this is the property I need but I must be calling it incorrectly.  Please forgive any ignorance, I'm super new to js.

https://discord.js.org/#/docs/main/master/class/User?scrollTo=createdAt

I would love to know what I'm doing wrong.  Thanks!


问:
Syscall Constant syscall.ENONET Undefined in Go
I tried to run the following bar.go script

```<code>package main

import (
    "fmt"
    "syscall"
)

func main() {
    fmt.Printf("%d\n", uintptr(syscall.ENONET))
}
</code>```

by calling go run bar.go and get this error:

```<code># command-line-arguments
./bar.go:9:29: undefined: syscall.ENONET
</code>```

I am using Mac and go version 1.14.3 darwin/amd64. I tried to run this exact script on Go playground, https://play.golang.org/p/ecMZPsGgGOa and it worked.

I tried to run the script using CGO_ENABLED=1 GOOS=linux GOARCH=amd64 and got this error instead:

```<code>fork/exec /var/folders/2l/dj6ph5t92y17vhtv3n6xzr5r0000gn/T/go-build847134732/b001/exe/bar: exec format error
</code>```

How do I get syscall.ENONET to work on Mac?

Thank you

答:
Yes, there's some weird problem with it. Although, syscall is locked down now.

```<code>Deprecated: this package is locked down.
Callers should use the corresponding package in the golang.org/x/sys repository instead.
</code>```

I tried out with go version go1.14.3 darwin/amd64, but I got the same problem.

But in the documentation, we have:

ENONET          = Errno(0x40)
```

<p>As, Errno is also exported type you can explicitly mock the same behaviour:</p>

<pre class="lang-golang prettyprint-override"><code>package main

import (
    "fmt"
    "syscall"
)

func main() {
    fmt.Printf("%d\n", syscall.Errno(0x40)) // 64
    fmt.Printf("%v\n", syscall.Errno(0x40)) // host is down
}
</code>```

Body:
I tried to run the following bar.go script

package main

import (
    "fmt"
    "syscall"
)

func main() {
    fmt.Printf("%d\n", uintptr(syscall.ENONET))
}

by calling go run bar.go and get this error:

# command-line-arguments
./bar.go:9:29: undefined: syscall.ENONET

I am using Mac and go version 1.14.3 darwin/amd64. I tried to run this exact script on Go playground, https://play.golang.org/p/ecMZPsGgGOa and it worked.

I tried to run the script using CGO_ENABLED=1 GOOS=linux GOARCH=amd64 and got this error instead:

fork/exec /var/folders/2l/dj6ph5t92y17vhtv3n6xzr5r0000gn/T/go-build847134732/b001/exe/bar: exec format error

How do I get syscall.ENONET to work on Mac?

Thank you

Body:
Yes, there's some weird problem with it. Although, syscall is locked down now.

Deprecated: this package is locked down.
Callers should use the corresponding package in the golang.org/x/sys repository instead.

I tried out with go version go1.14.3 darwin/amd64, but I got the same problem.

But in the documentation, we have:

ENONET          = Errno(0x40)

As, Errno is also exported type you can explicitly mock the same behaviour:

package main

import (
    "fmt"
    "syscall"
)

func main() {
    fmt.Printf("%d\n", syscall.Errno(0x40)) // 64
    fmt.Printf("%v\n", syscall.Errno(0x40)) // host is down
}


问:
to copy values to a new table and delete values from old table
```<code>CREATE TRIGGER trigg_msg
ON messagein

FOR insert,delete,update AS
IF EXISTS (SELECT * FROM INSERTED)
BEGIN

INSERT INTO new_message (Phone number,CusID,CusName,CusAddress) values ( SELECT ins.sender FROM inserted ins, SELECT cus.CusID FROM customer cus, SELECT cusname FROM customer cus, SELECT cus.cus_phone number FROM customer cus, SELECT cus.Address FROM customer cus)
DELETE * FROM messagein
END
</code>```

this trigger is not working.please somebody show me the mistake....

when insert a row to messagein table it should copy the value of sender field and copy it to the new_message table.then other values like cusID,CusName,.. should be retrieve from the customer table. please some one help me.

Update:

```<code>CREATE TRIGGER trigg_msg

ON messagein

FOR insert

IF EXISTS (SELECT * FROM INSERTED)

BEGIN

INSERT INTO new_message(Phone_number,CusID,CusName,CusAddress) values ( SELECT ins.sender FROM inserted ins, SELECT cus.CusID, cus.cusname, cus.cus_phone_number,  cus.Address FROM customer cus)

DELETE FROM messagein
</code>```

@Devart and @TudorConstantin Thank you very much for help me. finally i came up with this trigger but still getting errors.

答:
You have at least one syntax error:

```<code>DELETE * FROM messagein
</code>```

Should be:

```<code>DELETE FROM messagein
</code>```

Also, the INSERT should be:

```<code>INSERT INTO new_message (Phone_number,CusID,CusName,CusAddress) values ( SELECT ins.sender FROM inserted ins, SELECT cus.CusID, cus.cusname, cus.cus_phone_number,  cus.Address FROM customer cus)
</code>```

Body:
CREATE TRIGGER trigg_msg
ON messagein

FOR insert,delete,update AS
IF EXISTS (SELECT * FROM INSERTED)
BEGIN

INSERT INTO new_message (Phone number,CusID,CusName,CusAddress) values ( SELECT ins.sender FROM inserted ins, SELECT cus.CusID FROM customer cus, SELECT cusname FROM customer cus, SELECT cus.cus_phone number FROM customer cus, SELECT cus.Address FROM customer cus)
DELETE * FROM messagein
END

this trigger is not working.please somebody show me the mistake....

when insert a row to messagein table it should copy the value of sender field and copy it to the new_message table.then other values like cusID,CusName,.. should be retrieve from the customer table. please some one help me.

Update:

CREATE TRIGGER trigg_msg

ON messagein

FOR insert

IF EXISTS (SELECT * FROM INSERTED)

BEGIN

INSERT INTO new_message(Phone_number,CusID,CusName,CusAddress) values ( SELECT ins.sender FROM inserted ins, SELECT cus.CusID, cus.cusname, cus.cus_phone_number,  cus.Address FROM customer cus)

DELETE FROM messagein

@Devart and @TudorConstantin Thank you very much for help me. finally i came up with this trigger but still getting errors.

Body:
You have at least one syntax error:

DELETE * FROM messagein

Should be:

DELETE FROM messagein

Also, the INSERT should be:

INSERT INTO new_message (Phone_number,CusID,CusName,CusAddress) values ( SELECT ins.sender FROM inserted ins, SELECT cus.CusID, cus.cusname, cus.cus_phone_number,  cus.Address FROM customer cus)


问:
Azure Data Factory Copy Pipeline Did Not Copy Data Into The Sink
I created a test copy pipeline in azure data factory which basically reads 2 sample rows from a text file in azure blob storage and loads it into a table in Azure sql database, the run was successful.

However no records were inserted into the table. The source file is only 34 bytes, i read the minimum block size for azure blob storage is 64KB, could it because my test file is too small that azure failed to read it even though the pipeline ran successfully?

答:
could it because my test file is too small that azure failed to read
  it even though the pipeline ran successfully?

I believe this is not related to the file size because i did test with single row and it works fine for me.

Please try following suggestions:

1.Check the configuration of sink dataset if it is the exactly what you want.

2.Check the preview the data of source dataset if it is correct.

3.Check the monitor log of your pipeline, especially the input size and output size.

4.Try to configure another sink dataset, for example blob storage, to check if the data could be transferred into blob storage sucessfully.

If you have other concern, please feel free to let me know.


问:
Is there a better way to check if a number is range of two numbers
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

```<code>def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000
</code>```

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

答:
Since you have continuous, sorted ranges, a quicker and less verbose way to do this, is to use the bisect module to find the index in a list of breakpoints and then use it to get the corresponding value from a list of values:

```<code>import bisect

break_points = [5499,  9499, 14499, 19499, 24499, 29499, 34499, 39499, 44499]
values       = [5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000]

n = 10000
index = bisect.bisect_left(break_points, n)

values[index]
# 15000
</code>```

You'll need to test for n values that exceed the last breakpoint if that's a possibility. Alternatively you can add a default value to the end of the values list.

Body:
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

Body:
Since you have continuous, sorted ranges, a quicker and less verbose way to do this, is to use the bisect module to find the index in a list of breakpoints and then use it to get the corresponding value from a list of values:

import bisect

break_points = [5499,  9499, 14499, 19499, 24499, 29499, 34499, 39499, 44499]
values       = [5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000]

n = 10000
index = bisect.bisect_left(break_points, n)

values[index]
# 15000

You'll need to test for n values that exceed the last breakpoint if that's a possibility. Alternatively you can add a default value to the end of the values list.


问:
How to enable/disable cloudwatch event attached to lambda?
I've tried using the Cloudwatch Events/EventBridge JS SDK to enable/disable the rule which does work on the global scale. However, the cloudwatch event that is attached to my lambda does not change in state.

I'm looking to have a lambda that I can enable/disable the CRON aspect of. I see in the AWS UI there is a toggle to enable/disable the cloudwatch event but I'm not able to figure out how to access this functionality with the JS SDK.

toggle of AWS cloudwatch event:

答: Based on the comments, the problem was that lambda console sometimes shows incorrect associations. The solution was to actually perform a check and test the rules. The test showed that the rule was correctly disabled, even though the console shows otherwise.


问:
How to pass the UI Dispatcher to the ViewModel
I'm supposed to be able to access the Dispatcher that belongs to the View I need to pass it to the ViewModel. But the View should not know anything about the ViewModel, so how do you pass it? Introduce an interface or instead of passing it to the instances create a global dispatcher singleton that will be written by the View? How do you solve this in your MVVM applications and frameworks?

EDIT: Note that since my ViewModels might be created in background threads I can't just do Dispatcher.Current in the constructor of the ViewModel.

答:
No need to pass dispatcher when you can access application dispatcher using </p>

```<code>Dispatcher dis = Application.Current.Dispatcher
</code>```

Body:
No need to pass dispatcher when you can access application dispatcher using

Dispatcher dis = Application.Current.Dispatcher


问:
Best Buy API call limits
what is BestBuy API call limit for the product details? How many calls per hour/day ?</p>

答: Just for anyone who runs across this question the error code has changed to 403.  Source: https://bestbuyapis.github.io/api-documentation/#errors</p>

Title: Best Buy API call limits


问:
How to plot error bars for grouped bar chart using ggplot2?
I have a data set with two different factors (Place and Value) for one variable (bTemp) and I grouped the data based on the two factors, then generated the standard error (sem) for these data groups (i.e. I generated the st. error for data under field max, lab max, field min, etc.).

I tried to plot the st. errors of the grouped data onto my grouped bar chart, but I am only getting one st. error bar for each cluster of mean bars rather than two (one for each mean bar in the cluster). I checked my grouped data frame and it is generating the st. errors properly. So there must be something wrong with how I am defining the error bars in geom_errorbar.

```<code> str(LabFieldData)
'data.frame':   324 obs. of  3 variables:
 $ Place: Factor w/ 2 levels "Field","Lab": 1 1 1 1 1 1 1 1 1 1 ...
 $ Value: Factor w/ 3 levels "Max","Mean","Min": 3 3 3 3 3 3 3 3 3 3 ...
 $ bTemp: num  26.5 26.7 26.1 28.1 26.6 26.8 23.9 26.1 28.5 26.4 ...

#Group data by place (lab,field) and value(min,mean,max)
LabFieldData %>% group_by(Place,Value) %>%
  mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%

#Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
ggplot(mapping = aes(Value, bTemp, color = Place)) +
  geom_bar(mapping = aes(color = Place, fill = Place), stat = "summary", position="dodge") +
  geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
    position=position_dodge(0.9),width=.1, color = "black", size = 1) +
  scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35),
    limits=c(0,34)) + scale_x_discrete(name=element_blank(),limits=c("Min","Mean","Max")) +
  theme(legend.title = element_blank()) + scale_color_hue()
</code>```

答:
You were very close, you need to specify the fill in the ggplot function and not in the geom_bar function.

```<code>LabFieldData %>% group_by(Place,Value) %>%
   mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%
   #Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
   ggplot(mapping = aes(Value, bTemp, color = Place, fill=Place)) +
   geom_bar(stat = "summary", position="dodge") +
   geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
                 position=position_dodge(0.9), width=.1, color = "black", size = 1) +
   scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35), limits=c(0,34)) +
   scale_x_discrete(name=element_blank(), limits=c("Min","Mean","Max")) +
   theme(legend.title = element_blank()) + scale_color_hue()
</code>```

Body:
I have a data set with two different factors (Place and Value) for one variable (bTemp) and I grouped the data based on the two factors, then generated the standard error (sem) for these data groups (i.e. I generated the st. error for data under field max, lab max, field min, etc.).

I tried to plot the st. errors of the grouped data onto my grouped bar chart, but I am only getting one st. error bar for each cluster of mean bars rather than two (one for each mean bar in the cluster). I checked my grouped data frame and it is generating the st. errors properly. So there must be something wrong with how I am defining the error bars in geom_errorbar.

 str(LabFieldData)
'data.frame':   324 obs. of  3 variables:
 $ Place: Factor w/ 2 levels "Field","Lab": 1 1 1 1 1 1 1 1 1 1 ...
 $ Value: Factor w/ 3 levels "Max","Mean","Min": 3 3 3 3 3 3 3 3 3 3 ...
 $ bTemp: num  26.5 26.7 26.1 28.1 26.6 26.8 23.9 26.1 28.5 26.4 ...

#Group data by place (lab,field) and value(min,mean,max)
LabFieldData %>% group_by(Place,Value) %>%
  mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%

#Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
ggplot(mapping = aes(Value, bTemp, color = Place)) +
  geom_bar(mapping = aes(color = Place, fill = Place), stat = "summary", position="dodge") +
  geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
    position=position_dodge(0.9),width=.1, color = "black", size = 1) +
  scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35),
    limits=c(0,34)) + scale_x_discrete(name=element_blank(),limits=c("Min","Mean","Max")) +
  theme(legend.title = element_blank()) + scale_color_hue()

Body:
You were very close, you need to specify the fill in the ggplot function and not in the geom_bar function.

LabFieldData %>% group_by(Place,Value) %>%
   mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%
   #Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
   ggplot(mapping = aes(Value, bTemp, color = Place, fill=Place)) +
   geom_bar(stat = "summary", position="dodge") +
   geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
                 position=position_dodge(0.9), width=.1, color = "black", size = 1) +
   scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35), limits=c(0,34)) +
   scale_x_discrete(name=element_blank(), limits=c("Min","Mean","Max")) +
   theme(legend.title = element_blank()) + scale_color_hue()


问:
What is the difference between Paypal Business and Paypal Enterprise?
As a new developer, I found there are two very similar types of Paypal from Paypal Developer's page: https://developer.paypal.com/home/

For Business and For Enterprise (I understand For Marketplaces and Platforms is meant to be used entirely different use casaes)

I saw "Manage Risk" under for Enterprise  -- that seems to be the only difference from For Business -- but even a small business needs to manage its risk, doesn't it?

Can someone give me a high level explanation, when should I use For Business and when should I use for Enterprise from the following perspective?

how much extra functionality does for enterprise offer comparing to for business?

how much extra complexity for the developers to implement the integration comparing to the later?

答:
It's a matter of scale. The product offerings in the Enterprise section aren't designed for or marketed toward small and medium sized businesses. What exactly that means, and whether there might be a particular exception to something you need, will vary.

If you have to ask whether the Enterprise section applies to you, it doesn't.


问:
How to save data to firebase using react native?
I'm using https://github.com/expo-community/expo-firebase-starter as a starter template to build a react native app using firebase.

I am working with the following file in Home.js and want to save data to firebase but am getting an error. The error.

```<code>firebase.database is not a function. (In 'firebase.database(reflection)', 'firebase.database' is undefined)
</code>```

Here is the code I'm using. When someone writes a reflection, I'm trying to save that reflection text along with the user ID.

```<code>import React, {useEffect, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import { Container, Content, Header, Form, Input, Item, Label } from 'native-base';
import { Button } from "react-native-elements";
import { withFirebaseHOC } from "../config/Firebase";
import * as firebase from 'firebase';
import "firebase/database";

function Home({ navigation, firebase }) {

  const [reflection, setReflection] = useState('');
  const[member, setMember] = useState('');

  useEffect(() => {
    try {

      firebase.checkUserAuth(user => {
        if (user) {
          // if the user has previously logged in

          setMember(user);
          console.log(member);

        } else {
          // if the user has previously logged out from the app
          navigation.navigate("Auth");
        }
      });
    } catch (error) {
      console.log(error);
    }
  }, []);

  async function postReflection() {

    try {
      await console.log(reflection);
      await console.log(member.email);

    firebase.database(reflection).ref('Posts/').set({
        reflection,
    }).then((data)=>{
        //success callback
        console.log('data ' , data)
    }).catch((error)=>{
        //error callback
        console.log('error ' , error)
    })

    } catch (error) {
      console.log(error);
    }

  }

  async function handleSignout() {
    try {
      await firebase.signOut();
      navigation.navigate("Auth");
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <Container style={styles.container}>

          <Form>
            <Item floatingLabel>
              <Label>Reflection</Label>
              <Input
                autoCapitalize='none'
                autoCorrect={false}
                onChangeText={text => setReflection(text)}
              />
            </Item>

              <Button style = {{ marginTop: 10, marginHorizontal:30 }}
                title="Share"
                rounded
                onPress= {postReflection}
                >
              </Button>
              </Form>

      <Button
        title="Signout"
        onPress={handleSignout}
        titleStyle={{
          color: "#F57C00"
        }}
        type="clear"
      />
    </Container>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    // justifyContent: "center"
  }
});

export default withFirebaseHOC(Home);
</code>```

答:
Your /config/Firebase/firebase.js doesn't have a database property. Have a look at how the Firebase object is being exported.

// inside /config/Firebase/firebase.js

import "firebase/database"; // add this

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

const Firebase = {
  // add this
  database: () => {
    return firebase.database()
  }
};

export default Firebase;
```

Have a read of this step. You can't just import the part of the firebase library, you need to actually assign it to a variable and export it to use it.
https://firebase.google.com/docs/web/setup#namespace

Body:
I'm using https://github.com/expo-community/expo-firebase-starter as a starter template to build a react native app using firebase.

I am working with the following file in Home.js and want to save data to firebase but am getting an error. The error.

firebase.database is not a function. (In 'firebase.database(reflection)', 'firebase.database' is undefined)

Here is the code I'm using. When someone writes a reflection, I'm trying to save that reflection text along with the user ID.

import React, {useEffect, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import { Container, Content, Header, Form, Input, Item, Label } from 'native-base';
import { Button } from "react-native-elements";
import { withFirebaseHOC } from "../config/Firebase";
import * as firebase from 'firebase';
import "firebase/database";

function Home({ navigation, firebase }) {

  const [reflection, setReflection] = useState('');
  const[member, setMember] = useState('');

  useEffect(() => {
    try {

      firebase.checkUserAuth(user => {
        if (user) {
          // if the user has previously logged in

          setMember(user);
          console.log(member);

        } else {
          // if the user has previously logged out from the app
          navigation.navigate("Auth");
        }
      });
    } catch (error) {
      console.log(error);
    }
  }, []);

  async function postReflection() {

    try {
      await console.log(reflection);
      await console.log(member.email);

    firebase.database(reflection).ref('Posts/').set({
        reflection,
    }).then((data)=>{
        //success callback
        console.log('data ' , data)
    }).catch((error)=>{
        //error callback
        console.log('error ' , error)
    })

    } catch (error) {
      console.log(error);
    }

  }

  async function handleSignout() {
    try {
      await firebase.signOut();
      navigation.navigate("Auth");
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <Container style={styles.container}>

          <Form>
            <Item floatingLabel>
              Reflection
              <Input
                autoCapitalize='none'
                autoCorrect={false}
                onChangeText={text => setReflection(text)}
              />
            </Item>

              <Button style = {{ marginTop: 10, marginHorizontal:30 }}
                title="Share"
                rounded
                onPress= {postReflection}
                >
              </Button>
              </Form>

      <Button
        title="Signout"
        onPress={handleSignout}
        titleStyle={{
          color: "#F57C00"
        }}
        type="clear"
      />
    </Container>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    // justifyContent: "center"
  }
});

export default withFirebaseHOC(Home);

Body:
Your /config/Firebase/firebase.js doesn't have a database property. Have a look at how the Firebase object is being exported.

// inside /config/Firebase/firebase.js

import "firebase/database"; // add this

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

const Firebase = {
  // add this
  database: () => {
    return firebase.database()
  }
};

export default Firebase;

Have a read of this step. You can't just import the part of the firebase library, you need to actually assign it to a variable and export it to use it.
https://firebase.google.com/docs/web/setup#namespace


问:
Reverse entire dictionary items
I know this may be a simple question but I'm having trouble reversing my dictionary. All the solutions I've seen haven't been working for me. I have a dictionary where the keys are strings and the values are either None or type int. I want to reverse the order so the last (key, value) pair is first and vice versa.

For example:

```<code>d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD: None}
</code>```

I want to reverse the dictionary to:

```<code>reversed_d = {"pointD": None, "pointC": None, "pointB": 140, "pointA": 100}
</code>```

I've tried sorted(d.items(), reverse=True) and reversed(sorted(d.items()))
but I got an error of:

```<code>TypeError: '<' not supported between instances of 'int' and 'str'
</code>```

答:
You could do it this way.

Loop =>

```<code>for k,v in reversed(list(d.items())):
</code>```

or just

```<code>reversed_d = reversed(list(d.items()))
</code>```

Title: Reverse entire dictionary items

Body:
I know this may be a simple question but I'm having trouble reversing my dictionary. All the solutions I've seen haven't been working for me. I have a dictionary where the keys are strings and the values are either None or type int. I want to reverse the order so the last (key, value) pair is first and vice versa.

For example:

d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD: None}

I want to reverse the dictionary to:

reversed_d = {"pointD": None, "pointC": None, "pointB": 140, "pointA": 100}

I've tried sorted(d.items(), reverse=True) and reversed(sorted(d.items()))
but I got an error of:

TypeError: '<' not supported between instances of 'int' and 'str'

Body:
You could do it this way.

Loop =>

for k,v in reversed(list(d.items())):

or just

reversed_d = reversed(list(d.items()))


问:
RichFaces: Does navigation from one page to the next page using panelMenuItem needs to be enclosed in <h:form>
Since i'm just navigating from one page to the next using richfaces panelMenuItem, do those panels/panelMenuGroup/panelMenuItem needs to be enclosed in the  in order for it to navigate successfully? I noticed that if i do not enclose those panels elements in the , nothing happens. But why do i need to enclose it in a form since i'm not submitting any data to the server. At this point, i'm just navigating from one menu page to the next. Please advice.

==========================================================================================

Portfion of the code:

```<code><ui:composition>

<h:form> <-- if i removed this, nothing happens!!

        <rich:panel>
            <center><span id="clock"> </span></center>
        </rich:panel>

        <rich:panel>
            <f:facet name="header"><center>MView Modules</center></f:facet>
            <rich:panelMenu id="MView"  topGroupExpandedRightIcon="triangleDown"
                                        topGroupCollapsedRightIcon="triangle"
                                        groupExpandedLeftIcon="triangleDown"
                                        groupCollapsedLeftIcon="triangle"
                                        itemLeftIcon="grid"
                                        expandSingle="false">
                <rich:panelMenuGroup label="Enquiry Management">

                    <rich:panelMenuItem>Profile
                    </rich:panelMenuItem>
                    <rich:panelMenuItem action="/sections/securityHoldings">Security Holdings
                    </rich:panelMenuItem>
</code>```

答: Yes!! You need to enclose it into  tag because you are navigating from one page to another. To navigate from one page to another you need to send request to the server and to send request to the server for page where you want to navigate you need a form :).</p>

Body:
Since i'm just navigating from one page to the next using richfaces panelMenuItem, do those panels/panelMenuGroup/panelMenuItem needs to be enclosed in the  in order for it to navigate successfully? I noticed that if i do not enclose those panels elements in the , nothing happens. But why do i need to enclose it in a form since i'm not submitting any data to the server. At this point, i'm just navigating from one menu page to the next. Please advice.

==========================================================================================

Portfion of the code:

<ui:composition>

<h:form> <-- if i removed this, nothing happens!!

        <rich:panel>

        </rich:panel>

        <rich:panel>
            <f:facet name="header">MView Modules</f:facet>
            <rich:panelMenu id="MView"  topGroupExpandedRightIcon="triangleDown"
                                        topGroupCollapsedRightIcon="triangle"
                                        groupExpandedLeftIcon="triangleDown"
                                        groupCollapsedLeftIcon="triangle"
                                        itemLeftIcon="grid"
                                        expandSingle="false">
                <rich:panelMenuGroup label="Enquiry Management">

                    <rich:panelMenuItem>Profile
                    </rich:panelMenuItem>
                    <rich:panelMenuItem action="/sections/securityHoldings">Security Holdings
                    </rich:panelMenuItem>


问:
How to change basePath for Springfox Swagger 2.0
I'm running a service, where Swagger UI is accessible at:

```<code>http://serviceURL/swagger-ui.html
</code>```

However, it is behind a proxy, such as:

```<code>http://proxyURL/serviceName
</code>```

Generated URLs by Swagger UI are looking like:

```<code>http://proxyURL/
</code>```

instead of the actual URL with the serviceName as suffix.
As far as I get it, this means manipulating the basePath property. As per documentation:

A swagger API documentation can no longer describe operations on
  different base paths. In 1.2 and earlier, each resource could have had
  a separate basePath. In 2.0, the basePath equivalents
  (schemes+host+basePath) are defined for the whole specification.

@Api(basePath) is deprecated, and it doesn't say what to use and how to use it. How to make the paths generated by Swagger appear properly?

I'm using Spring Boot, Springfox Swagger and annotations.

答:
Using spring fox 2.9.2, using solution mentioned by other users is not works.

What is not working:

Overriding getApplicationBasePath on Docket pathProvider

Adding server.servlet.context-path=/serviceName

I don't know why they are not work, but in my project that using Springboot 2.1.6.RELEASE and Spring 5.1.8.RELEASE, the two solution above is being ignored.

So, I am trying another approach: https://github.com/springfox/springfox/issues/2817#issuecomment-517753110

According to the github issue comment, I need to override Springfox json serialize class and thank god this works.
Here is the code example:

```<code>import io.swagger.models.Swagger;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.JacksonModuleRegistrar;
import springfox.documentation.spring.web.json.Json;
import springfox.documentation.spring.web.json.JsonSerializer;

import java.util.Arrays;
import java.util.List;

import static io.github.jhipster.config.JHipsterConstants.SPRING_PROFILE_PRODUCTION;

@Component
@Primary
public class CustomBasePathSerialize extends JsonSerializer {

    // this injection is optional, if you don't need to
    // add basePath based on active profile, remove this.
    private final Environment env;

    public CustomBasePathSerialize(List<JacksonModuleRegistrar> modules,
                                   Environment env) {
        super(modules);
        this.env = env;
    }

    @Override
    public Json toJson(Object toSerialize) {
        if (toSerialize instanceof Swagger) {
            Swagger swagger = (Swagger) toSerialize;
            String basePath = "/serviceName";
            List<String> profiles = Arrays.asList(env.getActiveProfiles());

            // OPTIONAL: you can change basePath if you have difference path
            // on any Spring profile, for example prod:
            if (profiles.contains(SPRING_PROFILE_PRODUCTION)) {
                basePath = "/";
            }
            swagger.basePath(basePath);
        }
        return super.toJson(toSerialize);
    }
}
</code>```

Body:
I'm running a service, where Swagger UI is accessible at:

http://serviceURL/swagger-ui.html

However, it is behind a proxy, such as:

http://proxyURL/serviceName

Generated URLs by Swagger UI are looking like:

http://proxyURL/

instead of the actual URL with the serviceName as suffix.
As far as I get it, this means manipulating the basePath property. As per documentation:

A swagger API documentation can no longer describe operations on
  different base paths. In 1.2 and earlier, each resource could have had
  a separate basePath. In 2.0, the basePath equivalents
  (schemes+host+basePath) are defined for the whole specification.

@Api(basePath) is deprecated, and it doesn't say what to use and how to use it. How to make the paths generated by Swagger appear properly?

I'm using Spring Boot, Springfox Swagger and annotations.

Body:
Using spring fox 2.9.2, using solution mentioned by other users is not works.

What is not working:

Overriding getApplicationBasePath on Docket pathProvider

Adding server.servlet.context-path=/serviceName

I don't know why they are not work, but in my project that using Springboot 2.1.6.RELEASE and Spring 5.1.8.RELEASE, the two solution above is being ignored.

So, I am trying another approach: https://github.com/springfox/springfox/issues/2817#issuecomment-517753110

According to the github issue comment, I need to override Springfox json serialize class and thank god this works.
Here is the code example:

import io.swagger.models.Swagger;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.JacksonModuleRegistrar;
import springfox.documentation.spring.web.json.Json;
import springfox.documentation.spring.web.json.JsonSerializer;

import java.util.Arrays;
import java.util.List;

import static io.github.jhipster.config.JHipsterConstants.SPRING_PROFILE_PRODUCTION;

@Component
@Primary
public class CustomBasePathSerialize extends JsonSerializer {

    // this injection is optional, if you don't need to
    // add basePath based on active profile, remove this.
    private final Environment env;

    public CustomBasePathSerialize(List<JacksonModuleRegistrar> modules,
                                   Environment env) {
        super(modules);
        this.env = env;
    }

    @Override
    public Json toJson(Object toSerialize) {
        if (toSerialize instanceof Swagger) {
            Swagger swagger = (Swagger) toSerialize;
            String basePath = "/serviceName";
            List<String> profiles = Arrays.asList(env.getActiveProfiles());

            // OPTIONAL: you can change basePath if you have difference path
            // on any Spring profile, for example prod:
            if (profiles.contains(SPRING_PROFILE_PRODUCTION)) {
                basePath = "/";
            }
            swagger.basePath(basePath);
        }
        return super.toJson(toSerialize);
    }
}


问:
Is there any function in C which can store memory address of an array to a variable? What type of variable will store this address?
I used the following code to do the same. Is this the correct way to do the same?

```<code>#include <iostream>
using namespace std;
int main() {
    int ar[512]={0};
    char hex[100]="0xf";
    sscanf(hex,"%x",&ar);
    printf("\n%s",hex);
}
</code>```

Basicly I need to store this hexadecimal value into a variable as a string.

答:
i believe you can make a pointer pointing to the start of the array and print the address of the pointer </p>

```<code>#include <stdio.h>
int main(void)
{
    // my array
    int a[2];
    //my pointer pointing to the start of my array
    int *mysillypointer = &a;
    //print the addres of my pointer
    //the pointer is the "variable " that has the address of your array
    printf("Address of array a is : %p\n",mysillypointer);

    return 0;
}
</code>```

Body:
I used the following code to do the same. Is this the correct way to do the same?

#include <iostream>
using namespace std;
int main() {
    int ar[512]={0};
    char hex[100]="0xf";
    sscanf(hex,"%x",&ar);
    printf("\n%s",hex);
}

Basicly I need to store this hexadecimal value into a variable as a string.

Body:
i believe you can make a pointer pointing to the start of the array and print the address of the pointer

#include <stdio.h>
int main(void)
{
    // my array
    int a[2];
    //my pointer pointing to the start of my array
    int *mysillypointer = &a;
    //print the addres of my pointer
    //the pointer is the "variable " that has the address of your array
    printf("Address of array a is : %p\n",mysillypointer);

    return 0;
}


答:
since dictionaries are ordered by insertion order of the keys (since python 3.6, guaranteed since python 3.7), you can reverse the keys:

```<code>d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD": None}

for k in reversed(d):
    print(k)
</code>```

From there, you can build a new dictionary by inserting key values in the reversed order, or create a generator to access the (Key, value) pairs in that order.

Title: Reverse entire dictionary items

Body:
since dictionaries are ordered by insertion order of the keys (since python 3.6, guaranteed since python 3.7), you can reverse the keys:

d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD": None}

for k in reversed(d):
    print(k)

From there, you can build a new dictionary by inserting key values in the reversed order, or create a generator to access the (Key, value) pairs in that order.


问:
sine function in python gets wrong value
```<code>def sin_x(b):
    a = b
    if a=="pi" or a=="π":
       return 0
    else:
        x=float(a)
        return sin_function(x)
def factorial(b):
    if b==0:
        out=1
    else:
        out=1
        for i in range(1,b+1):
            out*=(i)
            i+=1
    return out
def sin_function(X):
    k=0
    sin=0
    last_term=(((-1)**k)*(X**(2*k+1)))/factorial(2*k+1)
    while abs(last_term)>1*10**(-8):
        sin+=last_term
        k+=1
        last_term=(((-1)**k)*(X**(2*k+1)))/factorial(2*k+1)
    return sin
print (sin_x(50))
</code>```

hello, I'm trying to build a sine function that gives exactly the same value as a calculator without implementing the math function. The main issue I have right now is that whenever the input is bigger than 35, the function starts to give the false value, and several exceptions if I keep increasing the input value. Can someone modify it to make it works exactly as a calculator? (it takes radians as input)

答:
I see several possible reasons, the first of which is that the commonly known Taylor expansion for sin(x) is only valid around the origin, more specifically the range [-pi, +pi]. This figure explains why:

Of course, you could shift the Taylor expansion to be based around any point, but it's probably more intuitive to just map the input radians into a value that falls within the above range, e.g. 5*pi/2 should map to pi/2. The following Python code does this:

```<code>PI = 3.141592653589793
x = 5*PI/2
pi_factor = int(x / PI)
adj = pi_factors if pi_factor%2 == 0 else pi_factor + 1
rad = x - PI*adj

print(rad)
1.5707963267948966
</code>```

Next up, your factorial function returns an int, which can lead to unexpected behavior when dividing. To be safe, make it return a float:

```<code>return out*1.0
</code>```

Lastly, I'm not sure what you're trying to do, but the Taylor expansion is simple. Take a look at the expansion for sine on the first page of this tutorial. I've implemented my own version below, which uses your factorial function:

```<code>def sin_function(x):

    # Doing this instead of math.abs
    sym_fact = -1 if x < 0 else 1
    y = -x if x < 0 else x

    # convert input radians to [-PI, +PI]
    PI = 3.141592653589793
    pi_factor = int(y / PI)
    adj = pi_factor if pi_factor%2 == 0 else pi_factor + 1
    rad = y - PI*adj

    # Taylor expand, increase num_terms for more precision
    total = 0
    num_terms = 7
    f_sign = 1
    for i in range(1,2*num_terms+1,2):
        total += f_sign * pow(rad, i)/factorial(i)
        f_sign *= -1

    return total*sym_fact
</code>```

The first two lines are exploiting the fact that sin(-x) = -sin(x). I avoided using math.abs() to keep it "pure" Python. If that's not a restriction for you, then the code can be simplified a little with math.abs() and math.pi. Also, you can increase the precision by increasing the number of terms used in the Taylor expansion (currently set to 7). Hope this helps.

Body:
def sin_x(b):
    a = b
    if a=="pi" or a=="π":
       return 0
    else:
        x=float(a)
        return sin_function(x)
def factorial(b):
    if b==0:
        out=1
    else:
        out=1
        for i in range(1,b+1):
            out*=(i)
            i+=1
    return out
def sin_function(X):
    k=0
    sin=0
    last_term=(((-1)**k)*(X**(2*k+1)))/factorial(2*k+1)
    while abs(last_term)>1*10**(-8):
        sin+=last_term
        k+=1
        last_term=(((-1)**k)*(X**(2*k+1)))/factorial(2*k+1)
    return sin
print (sin_x(50))

hello, I'm trying to build a sine function that gives exactly the same value as a calculator without implementing the math function. The main issue I have right now is that whenever the input is bigger than 35, the function starts to give the false value, and several exceptions if I keep increasing the input value. Can someone modify it to make it works exactly as a calculator? (it takes radians as input)

Body:
I see several possible reasons, the first of which is that the commonly known Taylor expansion for sin(x) is only valid around the origin, more specifically the range [-pi, +pi]. This figure explains why:

Of course, you could shift the Taylor expansion to be based around any point, but it's probably more intuitive to just map the input radians into a value that falls within the above range, e.g. 5*pi/2 should map to pi/2. The following Python code does this:

PI = 3.141592653589793
x = 5*PI/2
pi_factor = int(x / PI)
adj = pi_factors if pi_factor%2 == 0 else pi_factor + 1
rad = x - PI*adj

print(rad)
1.5707963267948966

Next up, your factorial function returns an int, which can lead to unexpected behavior when dividing. To be safe, make it return a float:

return out*1.0

Lastly, I'm not sure what you're trying to do, but the Taylor expansion is simple. Take a look at the expansion for sine on the first page of this tutorial. I've implemented my own version below, which uses your factorial function:

def sin_function(x):

    # Doing this instead of math.abs
    sym_fact = -1 if x < 0 else 1
    y = -x if x < 0 else x

    # convert input radians to [-PI, +PI]
    PI = 3.141592653589793
    pi_factor = int(y / PI)
    adj = pi_factor if pi_factor%2 == 0 else pi_factor + 1
    rad = y - PI*adj

    # Taylor expand, increase num_terms for more precision
    total = 0
    num_terms = 7
    f_sign = 1
    for i in range(1,2*num_terms+1,2):
        total += f_sign * pow(rad, i)/factorial(i)
        f_sign *= -1

    return total*sym_fact

The first two lines are exploiting the fact that sin(-x) = -sin(x). I avoided using math.abs() to keep it "pure" Python. If that's not a restriction for you, then the code can be simplified a little with math.abs() and math.pi. Also, you can increase the precision by increasing the number of terms used in the Taylor expansion (currently set to 7). Hope this helps.


问:
XBRL R package reads adds another link to input link. Resulting in a link that cannot be opened
I'm using XBRL package to import XBRL data from the SEC EDGAR website, and whenever I use xbrlDoAll function, it is unable to read the url, even though I provided the valid one. For example, to replicate this error, use the following:

```<code>library(XBRL)

inst <- "https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/aapl-20180929.xml"
xbrl.vars <- xbrlDoAll(inst)
</code>```

This is the error I get:

```<code>Error in fileFromCache(file) : Error in download.file(file, cached.file, quiet = !verbose) : cannot open URL 'https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/https://xbrl.sec.gov/dei/2018/dei-2018-01-31.xsd'
</code>```

As you can see, the URL cannot be opened because for some reason it adds another https:// in the middle of the link to get the file.

https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/https://xbrl.sec.gov/dei/2018/dei-2018-01-31.xsd

Which makes it an invalid url. I tried to manually download the file to the cache folder but the issue still persists. How can I edit it so it can properly read and download the content from the links? Thank you.

答: This is a bug as the package has not been maintained very well.  What you need to do is go straight to this website:  https://xbrl.sec.gov/dei/2018/dei-2018-01-31.xsd  and then save it directly into your xbrl.Cache folder (or whichever folder is serving as your cache).</p>

Body:
I'm using XBRL package to import XBRL data from the SEC EDGAR website, and whenever I use xbrlDoAll function, it is unable to read the url, even though I provided the valid one. For example, to replicate this error, use the following:

library(XBRL)

inst <- "https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/aapl-20180929.xml"
xbrl.vars <- xbrlDoAll(inst)

This is the error I get:

Error in fileFromCache(file) : Error in download.file(file, cached.file, quiet = !verbose) : cannot open URL 'https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/https://xbrl.sec.gov/dei/2018/dei-2018-01-31.xsd'

As you can see, the URL cannot be opened because for some reason it adds another https:// in the middle of the link to get the file.

https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/https://xbrl.sec.gov/dei/2018/dei-2018-01-31.xsd

Which makes it an invalid url. I tried to manually download the file to the cache folder but the issue still persists. How can I edit it so it can properly read and download the content from the links? Thank you.


问:
Why Method Overriding is runtime bound
Overriding is a principle that allows you to change the functionality of a method in a child class.

For Ex.

```<code>//Overriding
public class test
{
        public virtual getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}
</code>```

When we Inherit test class in test2 at that time compiler knows that there is a virtual method in parent class.
Then why Method overring is runtime bound and not compile time bound?

答:
It is run-time binding (if that is even the right phrasing - I'm not convinced) because even with a test2 variable you could actually have:

```<code>test2 obj = new test3(); // imagine test3 inherits from test2
obj.getStuff(id);
</code>```

here the variable is a test2, but the object is a test3. You could argue that maybe if it was sealed etc, but actually even non-virtual instance (non-static) methods go through the callvirt process. It works well, and is very fast. Additionally, the callvirt opcode has the necessary null-check, which means your code doesn't (under the bonnet) have to constantly check for nulls (which would be necessary if it was static-call)

The only exception here is structs which override an object method; the following is a static call:

```<code>int i = 1;
string s = i.ToString();
</code>```

Title: Why Method Overriding is runtime bound

Body:
Overriding is a principle that allows you to change the functionality of a method in a child class.

For Ex.

//Overriding
public class test
{
        public virtual getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}

When we Inherit test class in test2 at that time compiler knows that there is a virtual method in parent class.
Then why Method overring is runtime bound and not compile time bound?

Body:
It is run-time binding (if that is even the right phrasing - I'm not convinced) because even with a test2 variable you could actually have:

test2 obj = new test3(); // imagine test3 inherits from test2
obj.getStuff(id);

here the variable is a test2, but the object is a test3. You could argue that maybe if it was sealed etc, but actually even non-virtual instance (non-static) methods go through the callvirt process. It works well, and is very fast. Additionally, the callvirt opcode has the necessary null-check, which means your code doesn't (under the bonnet) have to constantly check for nulls (which would be necessary if it was static-call)

The only exception here is structs which override an object method; the following is a static call:

int i = 1;
string s = i.ToString();


问:
Sending mail to a linux server
I know we can send an email from Linux server using a lot of commands, but is there a way to send an email to a Linux server? From an exchange account?</p>

答:
You need the following:

mail server accepting mail on the Linux server OR a Linux server to which mail is forwarded from a relay mail server.

a user account configured on the Linux server with a mailbox

If those things are set up, then it's just a matter of sending an email to user@linix_hostname or user@forwarded_domain.

Title: Sending mail to a linux server


问:
Is there a way to pull out two successive records only if they occur one after the other in a series of files?
I'm trying to pull out two successive records, but only if those records occur one after the other. I'm working with files that look like this:

```<code>#File1
>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH
>CHB002 PatternC
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH

#File2
>CHB0022 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB0023 PatternC
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB0024 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

</code>```

I want to pull out everything under PatternA and PatternB from all files, but only if they occur one after the other. My desired output is:

```<code>>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH
</code>```

I've tried:

```<code>awk -v RS='>' -v ORS='>' '/PatternA/,/PatternB/' file*.txt > output.txt
</code>```

But this would include PatternC from file 2 in the output and I want to skip file2 because PatternA and PatternB don't occur successively. Next I tried this command:

```<code>awk -v RS='>' -v ORS='>' '/PatternA/{l=NR}/PatternB/&&NR==l+1' file*.txt > output.txt
</code>```

This prints out this:

```<code>>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH
</code>```

This gets me closer as I only print PatternB from file1.txt (which I do want to include in my output) and I exclude PatternB from file2.txt, which I don't want. However, I also want to include PatternA with PatternB in my desired output. The CHB### pattern is variable and can't rely upon that. I feel like this should be something I can accomplish in a one line command without needing to write a script, but I'm stuck (also new to this).

答:
Never use range expressions (/start/,/end/) as while they make the code for trivial tasks very slightly briefer, they need a complete rewrite and duplicate conditions for the tiniest change in requirements. Also never use a variable named l as it looks far too much like the number 1 and so obfuscates your code. Finally - creating a one-line command should never be a goal of writing software as it suggests you favor brevity over everything that actually matters in good software such as tight cohesion, loose coupling, efficiency, portability, clarity, simplicity, and robustness.

```<code>$ cat tst.awk
/^>/ {
    prt()
    prevBuf = currBuf
    prevKey = currKey
    currBuf = ""
    currKey = $2
}
{ currBuf = currBuf $0 ORS }
END { prt() }

function prt() {
    if ( ( currKey == "PatternB" ) && ( prevKey == "PatternA" ) ) {
        printf "%s%s", prevBuf, currBuf
    }
}
</code>```

.

```<code>$ awk -f tst.awk file1
>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

$ awk -f tst.awk file2
$
</code>```

Body:
I'm trying to pull out two successive records, but only if those records occur one after the other. I'm working with files that look like this:

#File1
>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH
>CHB002 PatternC
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH

#File2
>CHB0022 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB0023 PatternC
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB0024 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

I want to pull out everything under PatternA and PatternB from all files, but only if they occur one after the other. My desired output is:

>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

I've tried:

awk -v RS='>' -v ORS='>' '/PatternA/,/PatternB/' file*.txt > output.txt

But this would include PatternC from file 2 in the output and I want to skip file2 because PatternA and PatternB don't occur successively. Next I tried this command:

awk -v RS='>' -v ORS='>' '/PatternA/{l=NR}/PatternB/&&NR==l+1' file*.txt > output.txt

This prints out this:

>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

This gets me closer as I only print PatternB from file1.txt (which I do want to include in my output) and I exclude PatternB from file2.txt, which I don't want. However, I also want to include PatternA with PatternB in my desired output. The CHB### pattern is variable and can't rely upon that. I feel like this should be something I can accomplish in a one line command without needing to write a script, but I'm stuck (also new to this).

Body:
Never use range expressions (/start/,/end/) as while they make the code for trivial tasks very slightly briefer, they need a complete rewrite and duplicate conditions for the tiniest change in requirements. Also never use a variable named l as it looks far too much like the number 1 and so obfuscates your code. Finally - creating a one-line command should never be a goal of writing software as it suggests you favor brevity over everything that actually matters in good software such as tight cohesion, loose coupling, efficiency, portability, clarity, simplicity, and robustness.

$ cat tst.awk
/^>/ {
    prt()
    prevBuf = currBuf
    prevKey = currKey
    currBuf = ""
    currKey = $2
}
{ currBuf = currBuf $0 ORS }
END { prt() }

function prt() {
    if ( ( currKey == "PatternB" ) && ( prevKey == "PatternA" ) ) {
        printf "%s%s", prevBuf, currBuf
    }
}

.

$ awk -f tst.awk file1
>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

$ awk -f tst.awk file2
$


问:
Stata and how to use local variables on a regression
I have 2 sets of variables which explain an outcome (motor and size) and I am interested in finding which part of the predicted outcome belongs to which set. local motor could contain 1 or more variables. In order to do this I want a code which understands which variables are in motor and adds their impact in a single variable called predict_motor_smart. In this example predict_motor_smart should be equal to predict_motor. In essence I need to find an expression for the last line of code which is robust to a change in specification of local motor variables.

```<code>sysuse auto, clear

local outcome "price"

local  motor "mpg rep78"

local  size "weight length"

regress `outcome' `motor' `size'

gen predict_motor = _b[_cons] + mpg * _b[mpg] + rep78*_b[rep78]

 * gen predict_motor_smart = _b[_cons] + var1  of motor * beta 1 of motor + var2 of motor * beta2 of motor
</code>```

答:
```<code> sysuse auto, clear
 local outcome "price"
 local  motor "mpg rep78"
 local  size "weight length"
 regress `outcome' `motor' `size'
 predict outcome_predict
 gen predict_motor = .
 replace predict_motor = _b[_cons] + mpg * _b[mpg] + rep78*_b[rep78] if
 outcome_predict!=.
 gen predict_motor_smart =.
 replace predict_motor_smart   = _b[_cons] if outcome_predict!=.
 foreach l of local circumstances{
 replace predict_motor_smart  = predict_motor_smart  +`l'*_b[`l']
   }
</code>```

Body:
I have 2 sets of variables which explain an outcome (motor and size) and I am interested in finding which part of the predicted outcome belongs to which set. local motor could contain 1 or more variables. In order to do this I want a code which understands which variables are in motor and adds their impact in a single variable called predict_motor_smart. In this example predict_motor_smart should be equal to predict_motor. In essence I need to find an expression for the last line of code which is robust to a change in specification of local motor variables.

sysuse auto, clear

local outcome "price"

local  motor "mpg rep78"

local  size "weight length"

regress `outcome' `motor' `size'

gen predict_motor = _b[_cons] + mpg * _b[mpg] + rep78*_b[rep78]

 * gen predict_motor_smart = _b[_cons] + var1  of motor * beta 1 of motor + var2 of motor * beta2 of motor


问:
How to set width of mat-table column in angular?
Here in my mat-table have 6 column when any column has not more words then it looks like Image-1, but when any column has more words then UI looks like Image-2, so how to set UI like Image-1 when any column has more words in angular 6 ?

Image-1

Image-2

user.component.html

```<code><div class="mat-elevation-z8">
 <table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="userimage">
    <th mat-header-cell *matHeaderCellDef> # </th>
    <td mat-cell *matCellDef="let element">
      <img src="{{commonUrlObj.commonUrl}}/images/{{element.userimage}}" style="height: 40px;width: 40px;"/>
    </td>
  </ng-container>

  <ng-container matColumnDef="username">
    <th mat-header-cell *matHeaderCellDef> Full Name </th>
    <td mat-cell *matCellDef="let element"> {{element.username}} ( {{element.usertype}} )</td>
  </ng-container>

  <ng-container matColumnDef="emailid">
    <th mat-header-cell *matHeaderCellDef> EmailId </th>
    <td mat-cell *matCellDef="let element"> {{element.emailid}} </td>
   </ng-container>

  <ng-container matColumnDef="contactno">
    <th mat-header-cell *matHeaderCellDef> Contact No. </th>
    <td mat-cell *matCellDef="let element"> {{element.contactno}} </td>
  </ng-container>

  <ng-container matColumnDef="enabled">
    <th mat-header-cell *matHeaderCellDef> Enabled </th>
    <td mat-cell *matCellDef="let element" style="color: blue">
      <ng-container *ngIf="element.enabled == 'true'; else otherss">Enabled</ng-container>
        <ng-template #otherss>Disabled</ng-template>
    </td>
  </ng-container>

  <ng-container matColumnDef="action">
    <th mat-header-cell *matHeaderCellDef> Action </th>
      <td mat-cell *matCellDef="let element" fxLayoutGap="5px">
        <button mat-mini-fab color="primary" routerLink="/base/editUserDetails/{{element.userid}}"><mat-icon>edit</mat-icon></button>
        <button mat-mini-fab color="primary" routerLink="/base/viewUserDetails/{{element.userid}}"><mat-icon>pageview</mat-icon></button>
      </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 20, 50 ,100]" showFirstLastButtons></mat-paginator>
</code>```

答:
You can easily do this one. In each column you will get a class with the field name prefixed with mat-column, so the class will be like mat-column-yourFieldName. So for that you can set the style like following

```<code>.mat-column-yourFieldName {
    flex: none;
    width: 100px;
}
</code>```

So we can give fixed width for column as per our requirement.

Hope this helps for someone.

Body:
Here in my mat-table have 6 column when any column has not more words then it looks like Image-1, but when any column has more words then UI looks like Image-2, so how to set UI like Image-1 when any column has more words in angular 6 ?

Image-1

Image-2

user.component.html

  <ng-container matColumnDef="userimage">
     #

  </ng-container>

  <ng-container matColumnDef="username">
     Full Name
     {{element.username}} ( {{element.usertype}} )
  </ng-container>

  <ng-container matColumnDef="emailid">
     EmailId
     {{element.emailid}}
   </ng-container>

  <ng-container matColumnDef="contactno">
     Contact No.
     {{element.contactno}}
  </ng-container>

  <ng-container matColumnDef="enabled">
     Enabled

      <ng-container *ngIf="element.enabled == 'true'; else otherss">Enabled</ng-container>
        <ng-template #otherss>Disabled</ng-template>

  </ng-container>

  <ng-container matColumnDef="action">
     Action

        <button mat-mini-fab color="primary" routerLink="/base/editUserDetails/{{element.userid}}"><mat-icon>edit</mat-icon></button>
        <button mat-mini-fab color="primary" routerLink="/base/viewUserDetails/{{element.userid}}"><mat-icon>pageview</mat-icon></button>

  </ng-container>

<mat-paginator [pageSizeOptions]="[5, 10, 20, 50 ,100]" showFirstLastButtons></mat-paginator>

Body:
You can easily do this one. In each column you will get a class with the field name prefixed with mat-column, so the class will be like mat-column-yourFieldName. So for that you can set the style like following

.mat-column-yourFieldName {
    flex: none;
    width: 100px;
}

So we can give fixed width for column as per our requirement.

Hope this helps for someone.


问:
How to validate GUID is a GUID
How to determine if a string contains a GUID vs just a string of numbers.

will a GUID always contain at least 1 alpha character?

答:
There is no guarantee that a GUID contains alpha characters. FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF is a valid GUID so is 00000000-0000-0000-0000-000000000000 and anything in between.

If you are using .NET 4.0, you can use the answer above for the Guid.Parse and Guid.TryParse. Otherwise, you can do something like this:

```<code>public static bool TryParseGuid(string guidString, out Guid guid)
{
    if (guidString == null) throw new ArgumentNullException("guidString");
    try
    {
        guid = new Guid(guidString);
        return true;
    }
    catch (FormatException)
    {
        guid = default(Guid);
        return false;
    }
}
</code>```

Title: How to validate GUID is a GUID

Body:
There is no guarantee that a GUID contains alpha characters. FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF is a valid GUID so is 00000000-0000-0000-0000-000000000000 and anything in between.

If you are using .NET 4.0, you can use the answer above for the Guid.Parse and Guid.TryParse. Otherwise, you can do something like this:

public static bool TryParseGuid(string guidString, out Guid guid)
{
    if (guidString == null) throw new ArgumentNullException("guidString");
    try
    {
        guid = new Guid(guidString);
        return true;
    }
    catch (FormatException)
    {
        guid = default(Guid);
        return false;
    }
}