问:
Run Excel macro from BERT
I'm trying to run an Excel 2016 macro in BERT. Within the spreadsheet, I can operate the macro as a button called "Button_To_Click". This is the name of the macro in the Excel document's list of macros as well. I'm using the command EXCEL$Application.Run("BERT.Call", "Button_To_Click") and receiving the message Error: attempt to apply non-function.

This is my first time using BERT or anything VBA-related (I'm more familiar with R), and the documentation is unclear to me on how to make macros that were created and stored in Excel work in BERT. A more complete example is below:

```<code>wb <- EXCEL$Application$get_ActiveWorkbook();
INsheet <- wb$get_Sheets(1); #get first sheet in active workbook

S = c(155,157,159)
range <- MEMsheet$get_Range( "B10:B10" ); #change B10 to S[1]
range$put_Value(S[1]);

### 'Run Model' button is named 'Button_To_Click'. ###
EXCEL$Application.Run("BERT.Call", "Button_To_Click");
</code>```

答:
The function to run a macro requires calling the name of the macro and the sheet that hosts it within the workbook. It uses the name of the macro as saved in the macros menu and the action associated with it, not the text written on the clickable button itself. In this case that button was labeled with the text "Button_To_Click", but the actual name of the macro was "CalculateButton", saved in Sheet2, and the action associated with it was "Click". The BERT command Run.Macro() was sufficient as long as the BERT scripts are sourced.

```<code>source(file.path("C:/Users/MyName/Documents/BERT2/examples/excel-functions.r" )) #loads special BERT functions needed to have Excel and R interact
Run.Macro ( "Sheet2.CalculateButton_Click") #runs the macro named 'CalculateButton' located in Sheet2
</code>```

Title: Run Excel macro from BERT

Body:
I'm trying to run an Excel 2016 macro in BERT. Within the spreadsheet, I can operate the macro as a button called "Button_To_Click". This is the name of the macro in the Excel document's list of macros as well. I'm using the command EXCEL$Application.Run("BERT.Call", "Button_To_Click") and receiving the message Error: attempt to apply non-function.

This is my first time using BERT or anything VBA-related (I'm more familiar with R), and the documentation is unclear to me on how to make macros that were created and stored in Excel work in BERT. A more complete example is below:

wb <- EXCEL$Application$get_ActiveWorkbook();
INsheet <- wb$get_Sheets(1); #get first sheet in active workbook

S = c(155,157,159)
range <- MEMsheet$get_Range( "B10:B10" ); #change B10 to S[1]
range$put_Value(S[1]);

### 'Run Model' button is named 'Button_To_Click'. ###
EXCEL$Application.Run("BERT.Call", "Button_To_Click");

Body:
The function to run a macro requires calling the name of the macro and the sheet that hosts it within the workbook. It uses the name of the macro as saved in the macros menu and the action associated with it, not the text written on the clickable button itself. In this case that button was labeled with the text "Button_To_Click", but the actual name of the macro was "CalculateButton", saved in Sheet2, and the action associated with it was "Click". The BERT command Run.Macro() was sufficient as long as the BERT scripts are sourced.

source(file.path("C:/Users/MyName/Documents/BERT2/examples/excel-functions.r" )) #loads special BERT functions needed to have Excel and R interact
Run.Macro ( "Sheet2.CalculateButton_Click") #runs the macro named 'CalculateButton' located in Sheet2


来源: stackexchange

问:
Using xpath with c#, help
I'm trying to select the content of MINRANGE of the below XML. This is the code I'm using, the string min just gives me a long block of text not the node i wanted.

```<code>XPathDocument _BTCall = new XPathDocument(callUrl);
XPathNavigator nav = _BTCall.CreateNavigator();
XPathExpression exp;
exp = nav.Compile("//MAX/MINRANGE");
XPathNodeIterator iterator = nav.Select(exp);
iterator.MoveNext();

XPathNavigator nav2 = iterator.Current.Clone();
string min = nav.Value;
return int.Parse(min);
</code>```

```<code><ADSL_CHECKER>
  <ERRORID>0</ERRORID>
  <INPUT>01491410786</INPUT>
  <INPUTTYPE>TELNO</INPUTTYPE>
  <FIXEDRATE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </FIXEDRATE>
  <RATEADAPTIVE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </RATEADAPTIVE>
  <MAX>
    <RAG>G</RAG>
    <SPEED>4500</SPEED>
    <MINRANGE>3500</MINRANGE>
    <MAXRANGE>5500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </MAX>
  <WBC>
    <RAG>G</RAG>
    <SPEED>5500</SPEED>
    <MINRANGE>4500</MINRANGE>
    <MAXRANGE>6500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBC>
  <WBCFTTC>
    <RAG>G</RAG>
    <DOWNSPEED>32500</DOWNSPEED>
    <UPSPEED>7200</UPSPEED>
    <MINRANGE />
    <MAXRANGE />
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBCFTTC>
  <EXCHANGECODE>THHT</EXCHANGECODE>
  <EXCHANGENAME>HENLEY-ON-THAMES</EXCHANGENAME>
  <REASONCODE>L</REASONCODE>
  <VPCONTENTION>N</VPCONTENTION>
  <SPNAME />
  <CAD />
  <CPNAME>BE UN LIMITED</CPNAME>
  <CPCONTACTNO>02074795000</CPCONTACTNO>
  <POSTCODE>RG9 1LT</POSTCODE>
  <SUGGESTEDMSG>Your exchange is ADSL enabled, and our initial test on your line indicates that your line should be able to have an ADSL broadband service that provides a fixed line speed up to 2Mbps.

    Our test also indicates that your line currently supports an estimated ADSL Max broadband line speed of 4.5Mbps. Similar lines predicted with this speed have achieved ADSL Max line speeds in the range of 3.5 to 5.5Mbps.
    Our test also indicates that your line currently supports an estimated ADSL2+ broadband line speed of 5.5Mbps. Similar lines predicted with this speed have achieved ADSL2+ line speed in the range of 4.5 to 6.5Mbps.
    Our test also indicates that your line currently supports a fibre technology with an estimated WBC FTTC Broadband where consumers have received downstream line speed of 32.5Mbps and upstream line speed of 7.2Mbps.
    The actual stable line speed supportable will be determined during the first 10 days of use. This speed may change over time, to ensure line stability is maintained.
    If you decide to place an order, a further test will be performed to confirm if your line is suitable for the service you wish to purchase.
    Thank you for your interest.
    Please note that postcode and address check results are indicative only. Most accurate results can be obtained from a telephone number check.
  </SUGGESTEDMSG>
  <SUPPLEMENTARYMSG>Note: If you already have a Broadband service enabled on this line and you want to switch service providers, you will need to contact both your current provider and your new provider to get your service changed over new and existing service provider to have this service transferred.
  </SUPPLEMENTARYMSG>
</ADSL_CHECKER>
</code>```

Text in XML was modified slightly for formatting purposes.  See previous version for exact.

答:
What version of the .Net framework are you using?  If you're using 3.5 or higher, I strongly recommend using Linq to work with the Xml, you'll have a much easier time.  Check out the XDocument and related classes.

http://msdn.microsoft.com/en-us/library/bb387044.aspx

ContentLicense: CC BY-SA 3.0

Title: Using xpath with c#, help

Body:
I'm trying to select the content of MINRANGE of the below XML. This is the code I'm using, the string min just gives me a long block of text not the node i wanted.

XPathDocument _BTCall = new XPathDocument(callUrl);
XPathNavigator nav = _BTCall.CreateNavigator();
XPathExpression exp;
exp = nav.Compile("//MAX/MINRANGE");
XPathNodeIterator iterator = nav.Select(exp);
iterator.MoveNext();

XPathNavigator nav2 = iterator.Current.Clone();
string min = nav.Value;
return int.Parse(min);

<ADSL_CHECKER>
  <ERRORID>0</ERRORID>
  <INPUT>01491410786</INPUT>
  <INPUTTYPE>TELNO</INPUTTYPE>
  <FIXEDRATE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </FIXEDRATE>
  <RATEADAPTIVE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </RATEADAPTIVE>
  <MAX>
    <RAG>G</RAG>
    <SPEED>4500</SPEED>
    <MINRANGE>3500</MINRANGE>
    <MAXRANGE>5500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </MAX>
  <WBC>
    <RAG>G</RAG>
    <SPEED>5500</SPEED>
    <MINRANGE>4500</MINRANGE>
    <MAXRANGE>6500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBC>
  <WBCFTTC>
    <RAG>G</RAG>
    <DOWNSPEED>32500</DOWNSPEED>
    <UPSPEED>7200</UPSPEED>
    <MINRANGE />
    <MAXRANGE />
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBCFTTC>
  <EXCHANGECODE>THHT</EXCHANGECODE>
  <EXCHANGENAME>HENLEY-ON-THAMES</EXCHANGENAME>
  <REASONCODE>L</REASONCODE>
  <VPCONTENTION>N</VPCONTENTION>
  <SPNAME />
  <CAD />
  <CPNAME>BE UN LIMITED</CPNAME>
  <CPCONTACTNO>02074795000</CPCONTACTNO>
  <POSTCODE>RG9 1LT</POSTCODE>
  <SUGGESTEDMSG>Your exchange is ADSL enabled, and our initial test on your line indicates that your line should be able to have an ADSL broadband service that provides a fixed line speed up to 2Mbps.

    Our test also indicates that your line currently supports an estimated ADSL Max broadband line speed of 4.5Mbps. Similar lines predicted with this speed have achieved ADSL Max line speeds in the range of 3.5 to 5.5Mbps.
    Our test also indicates that your line currently supports an estimated ADSL2+ broadband line speed of 5.5Mbps. Similar lines predicted with this speed have achieved ADSL2+ line speed in the range of 4.5 to 6.5Mbps.
    Our test also indicates that your line currently supports a fibre technology with an estimated WBC FTTC Broadband where consumers have received downstream line speed of 32.5Mbps and upstream line speed of 7.2Mbps.
    The actual stable line speed supportable will be determined during the first 10 days of use. This speed may change over time, to ensure line stability is maintained.
    If you decide to place an order, a further test will be performed to confirm if your line is suitable for the service you wish to purchase.
    Thank you for your interest.
    Please note that postcode and address check results are indicative only. Most accurate results can be obtained from a telephone number check.
  </SUGGESTEDMSG>
  <SUPPLEMENTARYMSG>Note: If you already have a Broadband service enabled on this line and you want to switch service providers, you will need to contact both your current provider and your new provider to get your service changed over new and existing service provider to have this service transferred.
  </SUPPLEMENTARYMSG>
</ADSL_CHECKER>

Text in XML was modified slightly for formatting purposes.  See previous version for exact.


问:
How to use boost::serialization with nested structs and minimal code changes?
Currently we use POD which is stored in nested structs. Example:

```<code>#define MaxNum1 100;
#define MaxNum2 50;

struct A
{
    int Value[MaxNum1];
    char SomeChar = 'a';
};

struct B
{
    A data[MaxNum2];
    float SomeFloat = 0.1f;
};

int main()
{
    B StructBObject = {};
}
</code>```

We want to enhance our data structures using std::vector just like this:

```<code>struct NewA
{
    std::vector<int> Value;
    char SomeChar = 'a';
};

struct NewB
{
    std::vector<NewA> data;
    float SomeFloat = 0.1f;
};

int main()
{
    NewB StructNewBObject = {};
}
</code>```

The only argument against this modification is that NewA and NewB are no POD anymore and this makes reading/writing to a file more complicated.

How is it possible to read/write NewA and NewB to a file using boost::serialization with minimal
code changes to NewA and NewB? Minimal code changes are important because we use for example big structs which have up to 7 nested levels.

答:
You can serialize using boost serialization¹:

```<code>template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
    ar & a.Value & a.SomeChar;
}
template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
    ar & b.data & b.SomeFloat;
}
</code>```

Using these, you will already have the correct behaviour out of the box with both the C-array and std::vector approaches.

If you want to keep using fixed-size trivially-copyable types², you can use something like Boost Container's static_vector: it will keep track of the current size, but the data is statically allocated right inside the structures.

TRIPLE DEMO

Here's a triple demo program with three implementations depending on the IMPL variable.

As you can see the bulk of the code is kept invariant. However, for "best comparison" I've made sure that all the containers are at half capacity (50/25) before serialization.

The main program also deserializes.

Live On Coliru

```<code>#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>

#include <boost/serialization/access.hpp>
#include <boost/serialization/is_bitwise_serializable.hpp>
#include <boost/serialization/binary_object.hpp>

#include <iostream>

#if (IMPL==0) // C arrays
    struct A {
        int Value[100];
        char SomeChar = 'a';
    };

    struct B {
        A data[50];
        float SomeFloat = 0.1f;
    };

    template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
        ar & a.Value & a.SomeChar;
    }
    template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
        ar & b.data & b.SomeFloat;
    }

#elif (IMPL==1) // std::vector
    #include <boost/serialization/vector.hpp>
    struct A {
        std::vector<int> Value;
        char SomeChar = 'a';
    };

    struct B {
        std::vector<A> data;
        float SomeFloat = 0.1f;
    };

    template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
        ar & a.Value & a.SomeChar;
    }
    template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
        ar & b.data & b.SomeFloat;
    }

#elif (IMPL==2) // static_vector
    #include <boost/serialization/vector.hpp>
    #include <boost/container/static_vector.hpp>
    struct A {
        boost::container::static_vector<int, 100> Value;
        char SomeChar = 'a';
    };

    struct B {
        boost::container::static_vector<A, 50> data;
        float SomeFloat = 0.1f;
    };

    template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
        ar & boost::serialization::make_array(a.Value.data(), a.Value.size()) & a.SomeChar;
    }
    template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
        ar & boost::serialization::make_array(b.data.data(), b.data.size()) & b.SomeFloat;
    }

#endif

namespace bio = boost::iostreams;
static constexpr auto flags = boost::archive::archive_flags::no_header;
using BinaryData = std::vector</*unsigned*/ char>;

int main() {
    char const* impls[] = {"C style arrays", "std::vector", "static_vector"};
    std::cout << "Using " << impls[IMPL] << " implementation: ";
    BinaryData serialized_data;

    {
        B object = {};
#if IMPL>0
        {
            // makes sure all containers half-full
            A element;
            element.Value.resize(50);
            object.data.assign(25, element);
        }
#endif

        bio::stream<bio::back_insert_device<BinaryData>> os { serialized_data };
        boost::archive::binary_oarchive oa(os, flags);

        oa << object;
    }

    std::cout << "Size: " << serialized_data.size() << "\n";

    {
        bio::array_source as { serialized_data.data(), serialized_data.size() };
        bio::stream<bio::array_source> os { as };
        boost::archive::binary_iarchive ia(os, flags);

        B object;
        ia >> object;
    }
}
</code>```

Printing

```<code>Using C style arrays implementation: Size: 20472
Using std::vector implementation: Size: 5256
Using static_vector implementation: Size: 5039
</code>```

Final Thoughts

See also:

Boost serialization bitwise serializability

https://www.boost.org/doc/libs/1_72_0/libs/serialization/doc/wrappers.html#binaryobjects

¹ (but keep in mind portability, as you probably already are aware with the POD approach, see C++ Boost::serialization : How do I archive an object in one program and restore it in another?)

² not POD, as with the NSMI your types weren't POD

ContentLicense: CC BY-SA 4.0

Body:
Currently we use POD which is stored in nested structs. Example:

#define MaxNum1 100;
#define MaxNum2 50;

struct A
{
    int Value[MaxNum1];
    char SomeChar = 'a';
};

struct B
{
    A data[MaxNum2];
    float SomeFloat = 0.1f;
};

int main()
{
    B StructBObject = {};
}

We want to enhance our data structures using std::vector just like this:

struct NewA
{
    std::vector<int> Value;
    char SomeChar = 'a';
};

struct NewB
{
    std::vector<NewA> data;
    float SomeFloat = 0.1f;
};

int main()
{
    NewB StructNewBObject = {};
}

The only argument against this modification is that NewA and NewB are no POD anymore and this makes reading/writing to a file more complicated.

How is it possible to read/write NewA and NewB to a file using boost::serialization with minimal
code changes to NewA and NewB? Minimal code changes are important because we use for example big structs which have up to 7 nested levels.

Body:
You can serialize using boost serialization¹:

template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
    ar & a.Value & a.SomeChar;
}
template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
    ar & b.data & b.SomeFloat;
}

Using these, you will already have the correct behaviour out of the box with both the C-array and std::vector approaches.

If you want to keep using fixed-size trivially-copyable types², you can use something like Boost Container's static_vector: it will keep track of the current size, but the data is statically allocated right inside the structures.

TRIPLE DEMO

Here's a triple demo program with three implementations depending on the IMPL variable.

As you can see the bulk of the code is kept invariant. However, for "best comparison" I've made sure that all the containers are at half capacity (50/25) before serialization.

The main program also deserializes.

Live On Coliru

#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>

#include <boost/serialization/access.hpp>
#include <boost/serialization/is_bitwise_serializable.hpp>
#include <boost/serialization/binary_object.hpp>

#include <iostream>

#if (IMPL==0) // C arrays
    struct A {
        int Value[100];
        char SomeChar = 'a';
    };

    struct B {
        A data[50];
        float SomeFloat = 0.1f;
    };

    template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
        ar & a.Value & a.SomeChar;
    }
    template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
        ar & b.data & b.SomeFloat;
    }

#elif (IMPL==1) // std::vector
    #include <boost/serialization/vector.hpp>
    struct A {
        std::vector<int> Value;
        char SomeChar = 'a';
    };

    struct B {
        std::vector<A> data;
        float SomeFloat = 0.1f;
    };

    template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
        ar & a.Value & a.SomeChar;
    }
    template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
        ar & b.data & b.SomeFloat;
    }

#elif (IMPL==2) // static_vector
    #include <boost/serialization/vector.hpp>
    #include <boost/container/static_vector.hpp>
    struct A {
        boost::container::static_vector<int, 100> Value;
        char SomeChar = 'a';
    };

    struct B {
        boost::container::static_vector<A, 50> data;
        float SomeFloat = 0.1f;
    };

    template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
        ar & boost::serialization::make_array(a.Value.data(), a.Value.size()) & a.SomeChar;
    }
    template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
        ar & boost::serialization::make_array(b.data.data(), b.data.size()) & b.SomeFloat;
    }

#endif

namespace bio = boost::iostreams;
static constexpr auto flags = boost::archive::archive_flags::no_header;
using BinaryData = std::vector</*unsigned*/ char>;

int main() {
    char const* impls[] = {"C style arrays", "std::vector", "static_vector"};
    std::cout << "Using " << impls[IMPL] << " implementation: ";
    BinaryData serialized_data;

    {
        B object = {};
#if IMPL>0
        {
            // makes sure all containers half-full
            A element;
            element.Value.resize(50);
            object.data.assign(25, element);
        }
#endif

        bio::stream<bio::back_insert_device<BinaryData>> os { serialized_data };
        boost::archive::binary_oarchive oa(os, flags);

        oa << object;
    }

    std::cout << "Size: " << serialized_data.size() << "\n";

    {
        bio::array_source as { serialized_data.data(), serialized_data.size() };
        bio::stream<bio::array_source> os { as };
        boost::archive::binary_iarchive ia(os, flags);

        B object;
        ia >> object;
    }
}

Printing

Using C style arrays implementation: Size: 20472
Using std::vector implementation: Size: 5256
Using static_vector implementation: Size: 5039

Final Thoughts

See also:

Boost serialization bitwise serializability

https://www.boost.org/doc/libs/1_72_0/libs/serialization/doc/wrappers.html#binaryobjects

¹ (but keep in mind portability, as you probably already are aware with the POD approach, see C++ Boost::serialization : How do I archive an object in one program and restore it in another?)

² not POD, as with the NSMI your types weren't POD


问:
Spark dataframe replace null values for different data types in scala
Similar question has answers in SO,  but this requirement is little different.
na.fill in Spark DataFrame Scala

I have a  sample dataframe like below. Each column in the dataframe is different data types.
So using df.na.fill is not working to replace all the null values.

```<code>+-------------------------+-------------------------+-------------------------+
| date                    | id                      | name                    |
+-------------------------+-------------------------+-------------------------+
| 2000-01-01              | NULL                    | ABC                     |
| NULL                    | 123                     | NULL                    |
| NULL                    | NULL                    | CDE                     |
+-------------------------+-------------------------+-------------------------+
</code>```

So irrespective of the data type of the column all the NULL should be replaced by empty string.
The number,and name of the columns in the dataframe will be keep changing.

Based on the input dataframe data type NULLs should be replaced.

Schema of this dataframe:

```<code>root
 |-- date: timestamp (nullable = false)
 |-- id: integer (nullable = true)
 |-- points_redeemed: string (nullable = false)
</code>```

Expected Result:

```<code>+-------------------------+-------------------------+-------------------------+
| date                    | id                      | name                    |
+-------------------------+-------------------------+-------------------------+
| 2000-01-01              |                         | ABC                     |
|                         | 123                     |                         |
|                         |                         | CDE                     |
+-------------------------+-------------------------+-------------------------+
</code>```

Can someone advise ?

答:
Use foldLeft on dataframe columns and check if the value is literal NULL or .isNull or length(trim(col)) === 0 then replace with "" else don't change the value.

Example:

```<code>import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
val df= Seq(("2000-01-01","NULL","ABC"),("NULL","123","NULL")).
toDF("date","id","name").
withColumn("date",col("date").cast("timestamp")).
withColumn("id",col("id").cast("int"))

df.printSchema
//root
// |-- date: timestamp (nullable = true)
// |-- id: integer (nullable = true)
// |-- name: string (nullable = true)

df.show()

//+--------------------+----+----+
//|                date|  id|name|
//+--------------------+----+----+
//|2000-01-01 00:00:...|null| ABC|
//|                null| 123|NULL|
//+--------------------+----+----+

#using when otherwise to determine NULL value and replacing with "" if matches.
val df2=df.columns.foldLeft(df)((df, c) => {
  df.withColumn(s"$c",when((lower(col(s"$c")) === lit("null")) || (col(s"$c").isNull)|| (length(trim(col(s"$c"))) === 0),lit("")).otherwise(col(s"$c")))
})

df2.show()
//+-------------------+---+----+
//|               date| id|name|
//+-------------------+---+----+
//|2000-01-01 00:00:00|   | ABC|
//|                   |123|    |
//+-------------------+---+----+
</code>```

You can also add more checks in when statement if needed!

Body:
Similar question has answers in SO,  but this requirement is little different.
na.fill in Spark DataFrame Scala

I have a  sample dataframe like below. Each column in the dataframe is different data types.
So using df.na.fill is not working to replace all the null values.

+-------------------------+-------------------------+-------------------------+
| date                    | id                      | name                    |
+-------------------------+-------------------------+-------------------------+
| 2000-01-01              | NULL                    | ABC                     |
| NULL                    | 123                     | NULL                    |
| NULL                    | NULL                    | CDE                     |
+-------------------------+-------------------------+-------------------------+

So irrespective of the data type of the column all the NULL should be replaced by empty string.
The number,and name of the columns in the dataframe will be keep changing.

Based on the input dataframe data type NULLs should be replaced.

Schema of this dataframe:

root
 |-- date: timestamp (nullable = false)
 |-- id: integer (nullable = true)
 |-- points_redeemed: string (nullable = false)

Expected Result:

+-------------------------+-------------------------+-------------------------+
| date                    | id                      | name                    |
+-------------------------+-------------------------+-------------------------+
| 2000-01-01              |                         | ABC                     |
|                         | 123                     |                         |
|                         |                         | CDE                     |
+-------------------------+-------------------------+-------------------------+

Can someone advise ?

Body:
Use foldLeft on dataframe columns and check if the value is literal NULL or .isNull or length(trim(col)) === 0 then replace with "" else don't change the value.

Example:

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
val df= Seq(("2000-01-01","NULL","ABC"),("NULL","123","NULL")).
toDF("date","id","name").
withColumn("date",col("date").cast("timestamp")).
withColumn("id",col("id").cast("int"))

df.printSchema
//root
// |-- date: timestamp (nullable = true)
// |-- id: integer (nullable = true)
// |-- name: string (nullable = true)

df.show()

//+--------------------+----+----+
//|                date|  id|name|
//+--------------------+----+----+
//|2000-01-01 00:00:...|null| ABC|
//|                null| 123|NULL|
//+--------------------+----+----+

#using when otherwise to determine NULL value and replacing with "" if matches.
val df2=df.columns.foldLeft(df)((df, c) => {
  df.withColumn(s"$c",when((lower(col(s"$c")) === lit("null")) || (col(s"$c").isNull)|| (length(trim(col(s"$c"))) === 0),lit("")).otherwise(col(s"$c")))
})

df2.show()
//+-------------------+---+----+
//|               date| id|name|
//+-------------------+---+----+
//|2000-01-01 00:00:00|   | ABC|
//|                   |123|    |
//+-------------------+---+----+

You can also add more checks in when statement if needed!


问:
Effective way to write function in BigQuery
I have a function, which i want to optimize:

```<code>CREATE OR REPLACE FUNCTION <project>.<dataset>.<function_name>( tv1 STRING, tv2 STRING) <br>
RETURNS STRING <br>
AS ( <br>
CASE
when lower(tv1) = 'val1' then '11' <br>
when lower(tv1) = 'val2' then 'ABC1' <br>
when lower(tv1) = 'val3' then 'XYZ5' <br>
when lower(tv2) = 'val4' then 'MyVal' <br>
when lower(tv2) = 'val5' then 'HisVal' <br>
else 'nothing' <br>
end <br>
); <br>
</code>```

Here, how i can avoid using the lower() in every sentence and do it once INSIDE the function itself. I don't want to call the lower function with the lower() call to it from outside. How can i make it inside the function itself ?

答:
If you feel more comfortable with, you can also use JavaScript to define your functions (JavaScript UDF structure), but as @Mikhail pointed out, you need to convert to lowercase both tv1 and tv2 at least once for each variable:</p>

```<code>CREATE TEMP FUNCTION test(tv1 STRING, tv2 STRING)
RETURNS STRING
LANGUAGE js
AS """

  tv1 = tv1.toLowerCase();
  tv2 = tv2.toLowerCase();

  if(tv1 == "val1") return "11";
  if(tv1 == "val2") return "ABC1";
  if(tv1 == "val3") return "XYZ5";
  if(tv2 == "val4") return "MyVal";
  if(tv2 == "val5") return "HisVal";

  return "nothing";

""";
</code>```

Body:
I have a function, which i want to optimize:

CREATE OR REPLACE FUNCTION <project>.<dataset>.<function_name>( tv1 STRING, tv2 STRING)

RETURNS STRING

AS (

CASE
when lower(tv1) = 'val1' then '11'

when lower(tv1) = 'val2' then 'ABC1'

when lower(tv1) = 'val3' then 'XYZ5'

when lower(tv2) = 'val4' then 'MyVal'

when lower(tv2) = 'val5' then 'HisVal'

else 'nothing'

end

);

Here, how i can avoid using the lower() in every sentence and do it once INSIDE the function itself. I don't want to call the lower function with the lower() call to it from outside. How can i make it inside the function itself ?

Body:
If you feel more comfortable with, you can also use JavaScript to define your functions (JavaScript UDF structure), but as @Mikhail pointed out, you need to convert to lowercase both tv1 and tv2 at least once for each variable:

CREATE TEMP FUNCTION test(tv1 STRING, tv2 STRING)
RETURNS STRING
LANGUAGE js
AS """

  tv1 = tv1.toLowerCase();
  tv2 = tv2.toLowerCase();

  if(tv1 == "val1") return "11";
  if(tv1 == "val2") return "ABC1";
  if(tv1 == "val3") return "XYZ5";
  if(tv2 == "val4") return "MyVal";
  if(tv2 == "val5") return "HisVal";

  return "nothing";

""";


问:
Can I use DataGrid in web assembly?
I have been trying to get data grid control to work in my web assembly project. The data grid control works fine in UWP but in web assembly, it just shows the headers of the list but no list items. (The headers show even if they are auto-generated).

Can I even work with DataGrid in web assembly or do I have to use the ListView for tables(or something else) or is it my code?

The NuGet package that I am using: Uno.Microsoft.Toolkit.Uwp.UI.Controls.DataGrid
 (5.1.0-build.200.gf9c311b069)

```<code><controls:DataGrid
                    Height="250"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    AutoGenerateColumns="False"
                    ItemsSource="{Binding OpenCaseList}">
                    <controls:DataGrid.Columns>
                        <controls:DataGridTextColumn
                            Header="Id"
                            Binding="{Binding Id}" />
                        <controls:DataGridTextColumn
                            Header="Title"
                            Binding="{Binding Tittel}" />
                        <controls:DataGridTextColumn
                            Header="Comment"
                            Binding="{Binding Comment}" />
                    </controls:DataGrid.Columns>
                </controls:DataGrid>
</code>```

答:
Unfortunately, this control is not yet implemented for WASM.

There's already an issue on GitHub for this. I suggest you upvote it and subscribe to it so you can track the progress and also provide any feedback.

Here's the link: https://github.com/unoplatform/uno/issues/1943

Title: Can I use DataGrid in web assembly?

Body:
I have been trying to get data grid control to work in my web assembly project. The data grid control works fine in UWP but in web assembly, it just shows the headers of the list but no list items. (The headers show even if they are auto-generated).

Can I even work with DataGrid in web assembly or do I have to use the ListView for tables(or something else) or is it my code?

The NuGet package that I am using: Uno.Microsoft.Toolkit.Uwp.UI.Controls.DataGrid
 (5.1.0-build.200.gf9c311b069)

<controls:DataGrid
                    Height="250"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    AutoGenerateColumns="False"
                    ItemsSource="{Binding OpenCaseList}">
                    <controls:DataGrid.Columns>
                        <controls:DataGridTextColumn
                            Header="Id"
                            Binding="{Binding Id}" />
                        <controls:DataGridTextColumn
                            Header="Title"
                            Binding="{Binding Tittel}" />
                        <controls:DataGridTextColumn
                            Header="Comment"
                            Binding="{Binding Comment}" />
                    </controls:DataGrid.Columns>
                </controls:DataGrid>


问:
How to query- Where In Array Key Value Laravel with Mongodb
This is my database Structure

```<code>{
    "_id":"5e4d4d6fc01c0000cc0009bd",
    "UID":"5e30376327050000b3006cde",
    "delevery_charge":25,
    "order_item":[
        {
            "id":"5e2f4a636c630000f20053bc",
            "Name":"XXXXX",
            "info":"5e26098d94500000870044ac",
        }
    ],
    "subtotal":110,
    "status":1,
    "updated_at":"2020-02-19T14:59:59.000Z",
    "created_at":"2020-02-19T14:59:59.000Z"
}
</code>```

I want to Find data where order_item=>info ID .. Im using Mongo db

```<code>$db = Table::where(''Dont Know what to do)->first();
</code>```

How can I do that ???

答:
Have a look at the $elemMatch documentation in MongoDB

db.orders.find({ "order_item" : { "$elemMatch" : { "info" : "5e26098d94500000870044ac" } } });

Should do the trick.

Body:
This is my database Structure

{
    "_id":"5e4d4d6fc01c0000cc0009bd",
    "UID":"5e30376327050000b3006cde",
    "delevery_charge":25,
    "order_item":[
        {
            "id":"5e2f4a636c630000f20053bc",
            "Name":"XXXXX",
            "info":"5e26098d94500000870044ac",
        }
    ],
    "subtotal":110,
    "status":1,
    "updated_at":"2020-02-19T14:59:59.000Z",
    "created_at":"2020-02-19T14:59:59.000Z"
}

I want to Find data where order_item=>info ID .. Im using Mongo db

$db = Table::where(''Dont Know what to do)->first();

How can I do that ???


问:
C++ to Java Code Conversion
I have in C++

```<code>r.bits[k] &= 0xFF ^ msk;
</code>```

So in Java

```<code>r.bits[k] = r.bits[k] & 0xFF,
</code>```

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.

答:
The ^ symbol represents the bitwise XOR operator in C, C++. List of operators in C, C++.

The same operator is available for Java as well. XOR Operator in Java.

Title: C++ to Java Code Conversion

Body:
I have in C++

r.bits[k] &= 0xFF ^ msk;

So in Java

r.bits[k] = r.bits[k] & 0xFF,

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.


问:
UISearchController clears UISearchBar text when dismissed
In viewDidLoad of my custom subclass of UITableViewController, I've set navigationItem.titleView to the searchBar of a UISearchController, which I initialized with nil for searchResultsController.

When I tap into the search bar, enter text, and tap on the dimmed underlying content, then the UISearchController gets deactivated (as expected) and the search text I entered gets cleared (unexpectedly).

The search text is also cleared (also unexpectedly) when I explicitly (programmatically) set the search controller to be inactive. To get around that, I store the search text before and set it back after dismissing the search controller. Although hacky, it works.

```<code>let searchText = searchBar.text // #hack
searchController.isActive = false
searchBar.text = searchText     // #hack
</code>```

For when the search controller is automatically dismissed, I tried something similar using the UISearchControllerDelegate methods, i.e., storing the search text in willDismissSearchController(_:) and setting it back in didDismissSearchController(_:). But, this solution still shows the search text getting cleared and then getting set back to what it was before.

How do I seamlessly keep the search bar text as is when the search controller is dismissed automatically?

答:
I solved this problem by comparing one of Apple's sample projects to my own. As it turns out, you want to show your results in a separate table view controller than in the unfiltered data. Before you initialize your UISearchController, set up a separate TableViewController, and when you initialize your UISearchController, send the separate table view controller as the searchResultsController: argument.

searchController = UISearchController(searchResultsController:
                       self.searchResultsController)
```

Then in the updateSearchResults(for:) method I called self.searchResultsController.tableView.reloadData() after filtering my results.

This separate view controller will make the search controller behave in the way you would expect. I know that it's not by far a simple solution. In the interest of displaying search results in a way that makes it feel like they are being presented in the same table view as the unfiltered data, I'm not sure why Apple designed it this way but that's how it goes.

Body:
In viewDidLoad of my custom subclass of UITableViewController, I've set navigationItem.titleView to the searchBar of a UISearchController, which I initialized with nil for searchResultsController.

When I tap into the search bar, enter text, and tap on the dimmed underlying content, then the UISearchController gets deactivated (as expected) and the search text I entered gets cleared (unexpectedly).

The search text is also cleared (also unexpectedly) when I explicitly (programmatically) set the search controller to be inactive. To get around that, I store the search text before and set it back after dismissing the search controller. Although hacky, it works.

let searchText = searchBar.text // #hack
searchController.isActive = false
searchBar.text = searchText     // #hack

For when the search controller is automatically dismissed, I tried something similar using the UISearchControllerDelegate methods, i.e., storing the search text in willDismissSearchController(_:) and setting it back in didDismissSearchController(_:). But, this solution still shows the search text getting cleared and then getting set back to what it was before.

How do I seamlessly keep the search bar text as is when the search controller is dismissed automatically?

Body:
I solved this problem by comparing one of Apple's sample projects to my own. As it turns out, you want to show your results in a separate table view controller than in the unfiltered data. Before you initialize your UISearchController, set up a separate TableViewController, and when you initialize your UISearchController, send the separate table view controller as the searchResultsController: argument.

searchController = UISearchController(searchResultsController:
                       self.searchResultsController)

Then in the updateSearchResults(for:) method I called self.searchResultsController.tableView.reloadData() after filtering my results.

This separate view controller will make the search controller behave in the way you would expect. I know that it's not by far a simple solution. In the interest of displaying search results in a way that makes it feel like they are being presented in the same table view as the unfiltered data, I'm not sure why Apple designed it this way but that's how it goes.


问:
How do i add foreign key to existing table?
I am trying to add a foreign key to the table STUDENTS from the table PROGRAMS

```<code>ALTER TABLE COLLEGE.dbo.STUDENTS
        ADD FOREIGN KEY(ProgramId) REFERENCES
        PROGRAMS(ProgramId);
</code>```

But it giving the following error :

Foreign key 'ProgramId' references invalid column 'ProgramId' in referencing table 'STUDENTS'

Not sure what i am doing wrong here any tip or solution would be a great help.

答:
The column needs to exist in the table before it can be used for a foreign key reference.  So I assume you intend something like:</p>

```<code>ALTER TABLE COLLEGE.dbo.STUDENTS
        ADD ProgramId INT;  -- have to guess at the type

ALTER TABLE COLLEGE.dbo.STUDENTS
        ADD FOREIGN KEY (ProgramId) REFERENCES
        PROGRAMS(ProgramId);
</code>```

Body:
I am trying to add a foreign key to the table STUDENTS from the table PROGRAMS

ALTER TABLE COLLEGE.dbo.STUDENTS
        ADD FOREIGN KEY(ProgramId) REFERENCES
        PROGRAMS(ProgramId);

But it giving the following error :

Foreign key 'ProgramId' references invalid column 'ProgramId' in referencing table 'STUDENTS'

Not sure what i am doing wrong here any tip or solution would be a great help.

Body:
The column needs to exist in the table before it can be used for a foreign key reference.  So I assume you intend something like:

ALTER TABLE COLLEGE.dbo.STUDENTS
        ADD ProgramId INT;  -- have to guess at the type

ALTER TABLE COLLEGE.dbo.STUDENTS
        ADD FOREIGN KEY (ProgramId) REFERENCES
        PROGRAMS(ProgramId);


问:
If value is between two other values, do something and continue until it is not. If it is not, try again until it is, then stop when it is not
I have a column of dates in a dataframe that begins with yesterday's date and goes through today+13 days. I'm posting this on 2/19/20, so my dates would be from 2/18/20 - 3/3/20.

I need to write a loop that grabs data in a corresponding column if the date in my date column is between today and today+6. I know how to get the data out of the dataframe, but I'm struggling to get the loop right.

Below is an outline of what I'm trying to do

```<code>df_date = list of dates from dataframe column that I'm checking
current_day = today
seven_day = today + 6

n=0
while df_date[n] >= current_day and df_date[n] <= seven_day:
    grab the data
    n=+1
    continue grabbing data until condition is false, then break
else:
    If the condition is false, add 1 to n until it is true.
    Then grab the data until it is false again and break
</code>```

答:
Perfect problem for a generator:</p>

```<code>df_date = list of dates from dataframe column that I'm checking
current_day = today
seven_day = today + 6

def grab_dates(df_data, min_date, max_date):
    got_one = False
    for d in df_data:
        if min_date <= d <= max_date:
            yield d
            got_one = True
        elif got_one:
            break

for a_date in grab_dates(df_data, current_day, seven_day):
    print(a_date)
</code>```

Body:
I have a column of dates in a dataframe that begins with yesterday's date and goes through today+13 days. I'm posting this on 2/19/20, so my dates would be from 2/18/20 - 3/3/20.

I need to write a loop that grabs data in a corresponding column if the date in my date column is between today and today+6. I know how to get the data out of the dataframe, but I'm struggling to get the loop right.

Below is an outline of what I'm trying to do

df_date = list of dates from dataframe column that I'm checking
current_day = today
seven_day = today + 6

n=0
while df_date[n] >= current_day and df_date[n] <= seven_day:
    grab the data
    n=+1
    continue grabbing data until condition is false, then break
else:
    If the condition is false, add 1 to n until it is true.
    Then grab the data until it is false again and break

Body:
Perfect problem for a generator:

df_date = list of dates from dataframe column that I'm checking
current_day = today
seven_day = today + 6

def grab_dates(df_data, min_date, max_date):
    got_one = False
    for d in df_data:
        if min_date <= d <= max_date:
            yield d
            got_one = True
        elif got_one:
            break

for a_date in grab_dates(df_data, current_day, seven_day):
    print(a_date)


问:
How to exclude or remove specific items from snapshot.data.documents?
```<code>final List<DocumentSnapshot> userList = snapshot.data.documents
.where((DocumentSnapshot documentSnapshot) => documentSnapshot['username'] != "John123145").toList();
</code>```

this works with excluding specific username with value "John123145".

Question is how can I exclude 2 or more username?

```<code>List<String> listitems= ["John", "James"];
final List<DocumentSnapshot> userList = snapshot.data.documents
.where((DocumentSnapshot documentSnapshot) => documentSnapshot['username'] != listitems).toList();
</code>```

Thanks in advance.

答:
you can do this;

```<code>List<String> listitems= ["John", "James"];
final List<DocumentSnapshot> userList = snapshot.data.documents
.where((DocumentSnapshot documentSnapshot) => listItem.indexOf(documentSnapshot['username'] > -1)).toList();
</code>```

the method indexOf searcha a list for a given value, returns the index of the item if found, if not, it will return -1; so we are checking for it to be greater than -1 to be true. then it gets removed from the snapshot data.

Body:
final List<DocumentSnapshot> userList = snapshot.data.documents
.where((DocumentSnapshot documentSnapshot) => documentSnapshot['username'] != "John123145").toList();

this works with excluding specific username with value "John123145".

Question is how can I exclude 2 or more username?

List<String> listitems= ["John", "James"];
final List<DocumentSnapshot> userList = snapshot.data.documents
.where((DocumentSnapshot documentSnapshot) => documentSnapshot['username'] != listitems).toList();

Thanks in advance.

Body:
you can do this;

List<String> listitems= ["John", "James"];
final List<DocumentSnapshot> userList = snapshot.data.documents
.where((DocumentSnapshot documentSnapshot) => listItem.indexOf(documentSnapshot['username'] > -1)).toList();

the method indexOf searcha a list for a given value, returns the index of the item if found, if not, it will return -1; so we are checking for it to be greater than -1 to be true. then it gets removed from the snapshot data.


问:
Calculate how many days to go until I have lived 25,000 days, and what that date will be
I wrote the program below to calculate how many days I have been alive, and a friend wanted to know on what date in the future will he hit 25,000 days.

Here is my code:

```<code>import datetime as dt

now = dt.datetime.now()
print("Mike")
birthdatetime = dt.datetime(1963, 4, 1)
age = now - birthdatetime
print(age)
</code>```

I want to figure out a way to determine on what date I hit 25,000 days.

答:
Just use the birthday and add 25000 days to it using timedelta.</p>

```<code>from datetime import timedelta, date
date(1963, 4, 1) + timedelta(days = 25000)
# datetime.date(2031, 9, 11)
</code>```

Body:
I wrote the program below to calculate how many days I have been alive, and a friend wanted to know on what date in the future will he hit 25,000 days.

Here is my code:

import datetime as dt

now = dt.datetime.now()
print("Mike")
birthdatetime = dt.datetime(1963, 4, 1)
age = now - birthdatetime
print(age)

I want to figure out a way to determine on what date I hit 25,000 days.

Body:
Just use the birthday and add 25000 days to it using timedelta.

from datetime import timedelta, date
date(1963, 4, 1) + timedelta(days = 25000)
# datetime.date(2031, 9, 11)


问:
Using the addition function over the natural numbers, give a recursive definition of multiplication of natural numbers?
I have the following exercise but am not sure on how I should begin. The wording doesn't make sense to me:

Using the addition function over the
  natural numbers, give a recursive
  definition of multiplication of
  natural numbers.

答:
```<code>mul(n,1) = n
mul(n,m) = mul(n,m-1) + n
</code>```

something like this

Body:
mul(n,1) = n
mul(n,m) = mul(n,m-1) + n

something like this


问:
How can I force all facets in a ggplot2 plot to have the same x:y scale ratio, but allow the scales themselves to vary?
I am working with plotting data where the slope of x-y relationships between groups is what I want my readers to compare. The groups of data have very different ranges, though, so if i make a line plot and facet the plot by groups, a lot of white space on some of the plots.

```<code>library(ggplot2)
data <- data.frame(x=c(1,2,3,1,2,3,3,6,9), y=c(1,2,3,2,4,6,3,6,9), group=c('A','A','A','B','B','B','C','C','C'))

ggplot(data=data, mapping=aes(x=x, y=y))+
  facet_wrap(~group)+
  geom_line()
</code>```

So this plot lets you see that facets A and C have the same slopes, but there's a lot of white space in facet A, which I want to eliminate. (The problem is even worse in my real data... The line in A basically compresses down to a point)

But of course, if I let the scales vary freely, all the lines appear to have the same slope.

```<code>ggplot(data=data, mapping=aes(x=x, y=y))+
  facet_wrap(~group, scales='free')+
  geom_line()
</code>```

How can I make it so that each plot's scale has the same unit RATIO of x:y, preserving the visual slope comparison, while allowing the scales to vary so that at least one axis in each facet is fully "used"? (The axis that is fully "used" will of course vary depending on the data.)

答:
I think you'll need to make separate plots for each group and then lay them out together. For example:

```<code>library(tidyverse)
theme_set(theme_bw())
library(patchwork)

data <- data.frame(x=c(1,2,3,1,2,3,3,6,9), y=c(1,2,3,2,4,6,3,6,9), group=c('A','A','A','B','B','B','C','C','C'))

pl = data %>%
  group_split(group) %>%
  map(
    ~ggplot(.x, aes(x=x, y=y))+
      facet_grid(. ~ group) +
      geom_line()
  )

# Get ratio of axis ranges
ar = pl %>% map_dbl(function(p) {
  yr = layer_scales(p)$y$get_limits()
  xr = layer_scales(p)$x$get_limits()
  diff(xr)/diff(yr)
})

# Remove redundant axis labels
pl[2:3] = map(pl[2:3], ~.x + theme(axis.title.y=element_blank()))
pl[c(1,3)] = map(pl[c(1,3)], ~.x + theme(axis.title.x=element_blank()))

wrap_plots(pl, nrow=1, widths=ar)
</code>```

Note that this approach will not work well if the range of aspect ratios is quite large. In that case, another option is, for example, to have equal-width plots and vary the y-range of each plot to result in the correct relative slopes across plots.

Body:
I am working with plotting data where the slope of x-y relationships between groups is what I want my readers to compare. The groups of data have very different ranges, though, so if i make a line plot and facet the plot by groups, a lot of white space on some of the plots.

library(ggplot2)
data <- data.frame(x=c(1,2,3,1,2,3,3,6,9), y=c(1,2,3,2,4,6,3,6,9), group=c('A','A','A','B','B','B','C','C','C'))

ggplot(data=data, mapping=aes(x=x, y=y))+
  facet_wrap(~group)+
  geom_line()

So this plot lets you see that facets A and C have the same slopes, but there's a lot of white space in facet A, which I want to eliminate. (The problem is even worse in my real data... The line in A basically compresses down to a point)

But of course, if I let the scales vary freely, all the lines appear to have the same slope.

ggplot(data=data, mapping=aes(x=x, y=y))+
  facet_wrap(~group, scales='free')+
  geom_line()

How can I make it so that each plot's scale has the same unit RATIO of x:y, preserving the visual slope comparison, while allowing the scales to vary so that at least one axis in each facet is fully "used"? (The axis that is fully "used" will of course vary depending on the data.)

Body:
I think you'll need to make separate plots for each group and then lay them out together. For example:

library(tidyverse)
theme_set(theme_bw())
library(patchwork)

data <- data.frame(x=c(1,2,3,1,2,3,3,6,9), y=c(1,2,3,2,4,6,3,6,9), group=c('A','A','A','B','B','B','C','C','C'))

pl = data %>%
  group_split(group) %>%
  map(
    ~ggplot(.x, aes(x=x, y=y))+
      facet_grid(. ~ group) +
      geom_line()
  )

# Get ratio of axis ranges
ar = pl %>% map_dbl(function(p) {
  yr = layer_scales(p)$y$get_limits()
  xr = layer_scales(p)$x$get_limits()
  diff(xr)/diff(yr)
})

# Remove redundant axis labels
pl[2:3] = map(pl[2:3], ~.x + theme(axis.title.y=element_blank()))
pl[c(1,3)] = map(pl[c(1,3)], ~.x + theme(axis.title.x=element_blank()))

wrap_plots(pl, nrow=1, widths=ar)

Note that this approach will not work well if the range of aspect ratios is quite large. In that case, another option is, for example, to have equal-width plots and vary the y-range of each plot to result in the correct relative slopes across plots.


问:
Ignoring the connected WCF Service when registering a .Net Standard 2.0 DLL?
I currently have a .Net Standard DLL that I create through Visual Studio 2019. This library has a WCF service connected within it that contains a GetPassword and GetHealthCheck method in it.
When I build the .Net Standard project in release mode (I have it set to build for both Standard and Framework 4.7.1) the DLL is created, but when I register it all that I can see in my registry is the WCF methods. My actual class methods aren't there, and they don't appear in the registry either.

I would like to think that the registry values would be the CyberarkUserIDPasswordRetrieval class instead.
Is there another setting within visual studio that I should flip to have it ignore the connected service?

答:
It's possible that your .cs files have been included in a manner which means they are not compiled. Files added to a solution have an action associated with them:

(Example is for .vb or Visual Basic .net code files but the behaviour is the same)

It usually doesn't make sense for the build action of a .cs file to be anything other than Compile.


答:
You appear to want to add a column with a related foreign key.

In SQL Server, you can do this in a single commad, like so:

```<code>ALTER TABLE COLLEGE.dbo.STUDENTS
    ADD ProgramId INTEGER
    CONSTRAINT StudentsProgramIdFk FOREIGN KEY(ProgramId) REFERENCES PROGRAMS(ProgramId);
</code>```

You should adjust the datatype of the column to your exact need. The key point is that the new column must have the same datatype as the column it references (that is PROGRAMS(ProgramId)).

Title: How do i add foreign key to existing table?

Body:
You appear to want to add a column with a related foreign key.

In SQL Server, you can do this in a single commad, like so:

ALTER TABLE COLLEGE.dbo.STUDENTS
    ADD ProgramId INTEGER
    CONSTRAINT StudentsProgramIdFk FOREIGN KEY(ProgramId) REFERENCES PROGRAMS(ProgramId);

You should adjust the datatype of the column to your exact need. The key point is that the new column must have the same datatype as the column it references (that is PROGRAMS(ProgramId)).


答:
Welcome to StackOverflow. Use timedelta, see here</p>

```<code>    import datetime as dt
    now = dt.datetime.now()
    print("Andrew")
    birthdatetime = dt.datetime(1963, 6, 13,)
    age = now - birthdatetime
    print(age)

</code>```

Title: Calculate how many days to go until I have lived 25,000 days, and what that date will be

Body:
Welcome to StackOverflow. Use timedelta, see here

    import datetime as dt
    now = dt.datetime.now()
    print("Andrew")
    birthdatetime = dt.datetime(1963, 6, 13,)
    age = now - birthdatetime
    print(age)


问:
Send a mail with exchange server without using SMTP in scala or java
In my app, we are using MS exchange server for sending emails. But we are not using SMTP . We have to send mails without using SMTP.

Earlier i send the mail with Gail server with SMTP. but I didn't find any solution for sending mail with exchange server without the use of SMTP.

Please suggest me a good solution for this

EDIT :
Php code

```<code><?php

// Set basic message parameters
$from = 'noreply@company.com';
$to = 'customer@example.com';
$subject = 'Test Message';
$message = 'Hello';

// Set additional headers for HTML email
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\n";
$headers .= 'X-Mailer: PHP/' . phpversion() . "\n";
$headers .= 'From: ' . $from;

// Send mail
if (mail($to, $subject, $message, $headers)) {
      echo 'Message sent';
} else {
      echo 'Message sending failed';
}

?>
</code>```

Is it possible to send mail without use of SMTP port and host ?

答:
I wrote a function that I find myself using quite frequently within Spark Pipelines that uses the sendmail function (built into almost all linux distributions) and sends the emails as HTML(s). I mainly use it in situations where the admins already have postfix configured (almost all).

It uses base64 encoding to encode an html template in scala then seamlessly decodes and executes in bash without any of the monstrous headaches that come with combining bash string interpolation with scala and process execution. No temp files, just pure execution.

NOTES:
  1) if you use it like me in spark cluster mode you should test it on all of your data nodes first because it will execute from one of them and fail.
  2) I don't catch stdout because I don't need it. If you do just add a Stringbuffer and split the output with a logger at the end of message_success val.

Send Html email

import java.util.Base64
import java.nio.charset.StandardCharsets
import scala.sys.process._

def scalaSendMail(html_message: String, subject: String, to: Array[String], from: String=""): String = {
    val message64 = Base64.getEncoder.encodeToString(html_message.getBytes(StandardCharsets.UTF_8))
    val prepped_recipients = to.mkString(",")
    val bash_wrapper = """(echo "From: """ + from + """";
       echo "To: """ + prepped_recipients + """";
       echo "Subject: """ + subject + """";
       echo "Content-Type: text/html";
       echo "MIME-Version: 1.0";
       echo "";
       echo """" + message64 + """" | base64 --decode
    ) | sendmail -t """
    val mesage_success = Seq("sh", "-c", bash_wrapper).!!
    return mesage_success
}
```

Body:
In my app, we are using MS exchange server for sending emails. But we are not using SMTP . We have to send mails without using SMTP.

Earlier i send the mail with Gail server with SMTP. but I didn't find any solution for sending mail with exchange server without the use of SMTP.

Please suggest me a good solution for this

EDIT :
Php code

<?php

// Set basic message parameters
$from = 'noreply@company.com';
$to = 'customer@example.com';
$subject = 'Test Message';
$message = 'Hello';

// Set additional headers for HTML email
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\n";
$headers .= 'X-Mailer: PHP/' . phpversion() . "\n";
$headers .= 'From: ' . $from;

// Send mail
if (mail($to, $subject, $message, $headers)) {
      echo 'Message sent';
} else {
      echo 'Message sending failed';
}

?>

Is it possible to send mail without use of SMTP port and host ?


问:
Refresh required to detect authentication state using nuxt auth module
My app is unable to detect the state change that occurs when a user logs in without completely refreshing the page. Upon refreshing everything displays correctly. I am using Nuxt and its included auth module documented here - https://auth.nuxtjs.org/.

Here is the v-if statement that is unable to detect the state change:

```<code>  <template v-if="$auth.$state.loggedIn">
    <nuxt-link
      to="/profile"
    >
      Hello, {{ $auth.$state.user.name }}
    </nuxt-link>
  </template>
  <template v-else>
    <nuxt-link
      to="/logIn"
    >
      Sign In
    </nuxt-link>
  </template>
</code>```

Here is the login method in my login page.

```<code>  methods: {
    async onLogin() {
      try{

        this.$auth.loginWith("local", {
          data: {
            email: this.email,
            password: this.password
          }
        });

        this.$router.push("/");

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

    }
  }
</code>```

I tried fetching the state via a computed property but got the same result. I can see the vuex store data change to indicate I am correctly logged in/out in the 'Application' tab in Chrome Dev Tools but the Vue Dev seems to constantly indicate I'm logged in.. Not sure if its just buggy though..

I also encounter the same problem in reverse when logging out. Here's the method:

```<code>async onLogout() {
  try{
    await this.$auth.logout();
  }catch(err){
    console.log(err);
  }
}
</code>```

I am happy to provide further details.

答:
In store/index.js add this :

```<code> export const getters = {
   isAuthenticated(state) {
   return state.auth.loggedIn
  },
   loggedInUser(state) {
   return state.auth.user
  },
};
</code>```

In the pages you are suppose to be authenticated

use middle ware auth as : middleware: 'auth'

use import { mapGetters } from 'vuex'

in computed add ...mapGetters(['isAuthenticated', 'loggedInUser']),

you can use  loggedInUser to get your user details or check if isAuthenticated

and the logout would work as expected as long as your are importing the map getters in the computed

Body:
My app is unable to detect the state change that occurs when a user logs in without completely refreshing the page. Upon refreshing everything displays correctly. I am using Nuxt and its included auth module documented here - https://auth.nuxtjs.org/.

Here is the v-if statement that is unable to detect the state change:

  <template v-if="$auth.$state.loggedIn">
    <nuxt-link
      to="/profile"
    >
      Hello, {{ $auth.$state.user.name }}
    </nuxt-link>
  </template>
  <template v-else>
    <nuxt-link
      to="/logIn"
    >
      Sign In
    </nuxt-link>
  </template>

Here is the login method in my login page.

  methods: {
    async onLogin() {
      try{

        this.$auth.loginWith("local", {
          data: {
            email: this.email,
            password: this.password
          }
        });

        this.$router.push("/");

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

    }
  }

I tried fetching the state via a computed property but got the same result. I can see the vuex store data change to indicate I am correctly logged in/out in the 'Application' tab in Chrome Dev Tools but the Vue Dev seems to constantly indicate I'm logged in.. Not sure if its just buggy though..

I also encounter the same problem in reverse when logging out. Here's the method:

async onLogout() {
  try{
    await this.$auth.logout();
  }catch(err){
    console.log(err);
  }
}

I am happy to provide further details.

Body:
In store/index.js add this :

 export const getters = {
   isAuthenticated(state) {
   return state.auth.loggedIn
  },
   loggedInUser(state) {
   return state.auth.user
  },
};

In the pages you are suppose to be authenticated

use middle ware auth as : middleware: 'auth'

use import { mapGetters } from 'vuex'

in computed add ...mapGetters(['isAuthenticated', 'loggedInUser']),

you can use  loggedInUser to get your user details or check if isAuthenticated

and the logout would work as expected as long as your are importing the map getters in the computed


问:
Conditional filtering for Tableau worksheets using Tabcmd
I have a dashboard which has two worksheets in it. I have a filter that is applied to only one of the two sheets. It works perfectly when I upload it on the Tableau server. However, when I use tabcmd to get pdf of the dashboard by just iterating over that one filter, it applies to both the sheets within the dashboard.
I have already set that filter to apply to the desired worksheet.
How can I solve this issue?

I tried creating a copy of the same filter and applying to the sheet I don't want it to affect. I also did add context to the original filter and then tried to run it through tabcmd. Both options didn't seem to work.

Here is my code: The '&Location%20Group=' + LocGroup.replace(' ','%20') filter is getting applied to both sheets instead of 1
Also, I am running tabcmd in python

```<code>for LocGroup in LocationGroup:
    BatchString = 'tabcmd get "' + View + Dashboard + SnapType + SnapSize + '&Year=' + Year + '&Month=' + Month + '&Location%20Group=' + LocGroup.replace(' ','%20') + '" -f "' + SnapFolder + '\\' + Year + '_' + Month + '_' + LocGroup + SnapType + '"\n'
    print(BatchString)
    GetSnaps(BatchString)
</code>```

答:
Use fixed (LOD) calculations in the sheet where you don't want the filter to be applied.

https://help.tableau.com/current/pro/desktop/en-us/calculations_calculatedfields_lod.htm#FIXED

Body:
I have a dashboard which has two worksheets in it. I have a filter that is applied to only one of the two sheets. It works perfectly when I upload it on the Tableau server. However, when I use tabcmd to get pdf of the dashboard by just iterating over that one filter, it applies to both the sheets within the dashboard.
I have already set that filter to apply to the desired worksheet.
How can I solve this issue?

I tried creating a copy of the same filter and applying to the sheet I don't want it to affect. I also did add context to the original filter and then tried to run it through tabcmd. Both options didn't seem to work.

Here is my code: The '&Location%20Group=' + LocGroup.replace(' ','%20') filter is getting applied to both sheets instead of 1
Also, I am running tabcmd in python

for LocGroup in LocationGroup:
    BatchString = 'tabcmd get "' + View + Dashboard + SnapType + SnapSize + '&Year=' + Year + '&Month=' + Month + '&Location%20Group=' + LocGroup.replace(' ','%20') + '" -f "' + SnapFolder + '\\' + Year + '_' + Month + '_' + LocGroup + SnapType + '"\n'
    print(BatchString)
    GetSnaps(BatchString)


问:
Python loop iterates after expected termination
The below Python code has an odd behavior, which I can't figure out.

The program calls testQuery, which asks the used to reply 'yes' to call scoreAverager, or 'no' to exit the program. If scoreAverager is called, it then requests the user enter a series of scores, or 'x' to finish, which returns the user to testQuery, where they can chose to average another test or exit.

The weirdness happens if a user averages the results for several tests (e.g. 2 or more).
At that point giving 'no' to testQuery will fail to terminated the program. It will iterate an additional cycle for every test that was averaged. I can't figure out why this would be the case. It looks and behaves like an off-by-one erros, but the conditions to close the loop appear satisfied. It can be solved with a 'break', but I'd rather know what the problem is to solve it more organically.

Can anyone let me know why this odd behavior is happening?

CODE:

```<code>def scoreAverager():
    done=0
    scoreTot=0
    numScores=0
    average=0
    while done == 0:
        score=input("Enter the numerical score, or enter 'x' to finish entering scores:")
        acceptedXs={"X","x"}
        if score in acceptedXs:
            print ("The average of the scores is: ",average)
            #break #this break is necessary for proper function.
            done=1
            testQuery()
        else:
            try:
                score=float(score)
                scoreTot=scoreTot+score
                numScores=numScores+1
                average=scoreTot/numScores
            except ValueError:
                print("EXCEPTION: The entry was invalid, please try again.")

def testQuery():
    done=0
    while done == 0:
        moreTests=input("Do you have a set of score to average? Enter 'Yes' or 'No':")
        acceptedNos=("No","NO","no")
        acceptedYess=("Yes","YES","yes")
        if moreTests in acceptedNos:
            print("Program Complete.")
            done=1
        elif moreTests in acceptedYess:
            scoreAverager()
        else:
            print ("ERROR: The entry was invalid. Please try again.")

def main():
    testQuery()

main()
</code>```

EXAMPLE INPUT/OUTPUT:

```<code>Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is:  1.5
Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is:  1.5
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
</code>```

答:
The problem is pretty complex, where the solution is pretty simple. By debugging the code tens of times, I recognised that the problem is in your testQuery() line in the scoreAverager function definition. You are entering the loop inside testQuery function while it's still running, and that makes the program stop when the value of done becomes 1 in the two running loops.

To solve this problem, simply delete the testQuery line in the scoreAverager function definition and the function will work with the same efficiency as when the loop in scoreAverager is ended, it will return back to the first launched loop in testQuery.

Body:
The below Python code has an odd behavior, which I can't figure out.

The program calls testQuery, which asks the used to reply 'yes' to call scoreAverager, or 'no' to exit the program. If scoreAverager is called, it then requests the user enter a series of scores, or 'x' to finish, which returns the user to testQuery, where they can chose to average another test or exit.

The weirdness happens if a user averages the results for several tests (e.g. 2 or more).
At that point giving 'no' to testQuery will fail to terminated the program. It will iterate an additional cycle for every test that was averaged. I can't figure out why this would be the case. It looks and behaves like an off-by-one erros, but the conditions to close the loop appear satisfied. It can be solved with a 'break', but I'd rather know what the problem is to solve it more organically.

Can anyone let me know why this odd behavior is happening?

CODE:

def scoreAverager():
    done=0
    scoreTot=0
    numScores=0
    average=0
    while done == 0:
        score=input("Enter the numerical score, or enter 'x' to finish entering scores:")
        acceptedXs={"X","x"}
        if score in acceptedXs:
            print ("The average of the scores is: ",average)
            #break #this break is necessary for proper function.
            done=1
            testQuery()
        else:
            try:
                score=float(score)
                scoreTot=scoreTot+score
                numScores=numScores+1
                average=scoreTot/numScores
            except ValueError:
                print("EXCEPTION: The entry was invalid, please try again.")

def testQuery():
    done=0
    while done == 0:
        moreTests=input("Do you have a set of score to average? Enter 'Yes' or 'No':")
        acceptedNos=("No","NO","no")
        acceptedYess=("Yes","YES","yes")
        if moreTests in acceptedNos:
            print("Program Complete.")
            done=1
        elif moreTests in acceptedYess:
            scoreAverager()
        else:
            print ("ERROR: The entry was invalid. Please try again.")

def main():
    testQuery()

main()

EXAMPLE INPUT/OUTPUT:

Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is:  1.5
Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is:  1.5
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.


问:
_vuex.default.store is not a constructor
I'm trying to test a component that uses vuex inside it, I'm trying to pass the store of the respective component so that it can be assembled, but I'm getting the following error:

_vuex.default.store is not a constructor

I have no idea what's going on and I couldn't find anything on the internet to help me, if anyone can help me, I would be very grateful!

Spec file

```<code>import {shallowMount,createLocalVue} from '@vue/test-utils'
import Vuex from 'vuex'

import sateliteComponent from '@/components/satelite/listaSatelite.vue'
import sateliteStore from '@/core/modules/satelite/index.js'

var vueWithVuex = createLocalVue()
vueWithVuex.use(Vuex)
const store = new Vuex.store({
    sateliteStore
})
describe('testes componente satelite', () => {

    test('instanciado', () => {
        const wrapper = shallowMount(sateliteComponent,{
            localVue:vueWithVuex,
            store
        })
        expect(wrapper.isVueInstance()).toBeTruthy()

    });
});
</code>```

if necessary, I can post my component that is being rendered

答:
Correct with this:</p>

```<code>const store = new Vuex.Store({
    sateliteStore
})
</code>```

Body:
I'm trying to test a component that uses vuex inside it, I'm trying to pass the store of the respective component so that it can be assembled, but I'm getting the following error:

_vuex.default.store is not a constructor

I have no idea what's going on and I couldn't find anything on the internet to help me, if anyone can help me, I would be very grateful!

Spec file

import {shallowMount,createLocalVue} from '@vue/test-utils'
import Vuex from 'vuex'

import sateliteComponent from '@/components/satelite/listaSatelite.vue'
import sateliteStore from '@/core/modules/satelite/index.js'

var vueWithVuex = createLocalVue()
vueWithVuex.use(Vuex)
const store = new Vuex.store({
    sateliteStore
})
describe('testes componente satelite', () => {

    test('instanciado', () => {
        const wrapper = shallowMount(sateliteComponent,{
            localVue:vueWithVuex,
            store
        })
        expect(wrapper.isVueInstance()).toBeTruthy()

    });
});

if necessary, I can post my component that is being rendered

Body:
Correct with this:

const store = new Vuex.Store({
    sateliteStore
})


问:
Python Data science beginner function question
I'm prepping for a Data science bootcamp and know nothing about coding. Im stuck on this lab im doing right now.

so I have this list:

```<code>travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
</code>```

I need to write a function called number_of_destinations that returns the number of destinations in the list travel_destinations.

Here's my code:

```<code>def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    print (x)
</code>```

Which returns:

```<code><function __main__.number_of_destinations(travel_destinations)>
</code>```

Ive tried so many different approaches and python just keeps spitting out "yes this is a function" basically. Can anyone help me figure out what im doing wrong here?

答:
To call a function you need to add brackets to its name (and some parameters in the brackets, if the function takes parameters). Otherwise, as you have seen, Python just lets you know that you have entered the name of a function.

```<code>def my_function():
    return "hello"

>>> my_function
<function __main__.my_function()>
>>> my_function()
'hello'
</code>```

Even though your bootcamp supposedly requires no coding knowledge, you should probably try to work through the examples in the Python tutorial.

Body:
I'm prepping for a Data science bootcamp and know nothing about coding. Im stuck on this lab im doing right now.

so I have this list:

travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']

I need to write a function called number_of_destinations that returns the number of destinations in the list travel_destinations.

Here's my code:

def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    print (x)

Which returns:

<function __main__.number_of_destinations(travel_destinations)>

Ive tried so many different approaches and python just keeps spitting out "yes this is a function" basically. Can anyone help me figure out what im doing wrong here?

Body:
To call a function you need to add brackets to its name (and some parameters in the brackets, if the function takes parameters). Otherwise, as you have seen, Python just lets you know that you have entered the name of a function.

def my_function():
    return "hello"

>>> my_function
<function __main__.my_function()>
>>> my_function()
'hello'

Even though your bootcamp supposedly requires no coding knowledge, you should probably try to work through the examples in the Python tutorial.


问:
Invalid Object Name when i execute a procedure that update a table
I have  the following

```<code>use salesdb
go

create procedure monthlysales as
begin

create table MyTable( SalesFactID integer identity(1,1),
ReportingMth date,
customer_id varchar(50),
ReferenceID navarchar(50),
LstOrderDte date);

Insert into MyTable

select
businessMth,
saleid as referenceid,
null as lastorderte

from sourcetble;

update MyTable
set lastorderte = sls.max_orderdte
from ( select
st.customer_id,
ftmytbl.ReportingMth,
max(salesdate) as max_orderdte

from sales_table st

left outer join mytable ftmytbl
on ftmytbl.customerid=st.customerRef

where saleste<=ftmytbl.ReportingMth

group by customer_id

)up

where mytable.customer_id=up.customer_id
and mytable.reportingmth=up.ReportingMth;

end;

execute monthlysales
</code>```

error invalid object name mytable.reportingmth

How can i fix this? Please assist.

答:
Search for that text. Where is it? It is in the where clause of the outermost select statement. You used a derived table named up (which is a crap name, btw - as are many of your names) in the join. The outer query knows only 2 tables - up and MyTable (or is it mytable? BE CONSISTENT!) and can only refer to columns in those tables.

To correct this particular problem, change this:

```<code>and mytable.reportingmth=up.ReportingMth;
</code>```

to

```<code>and MyTable.ReportingMth = up.ReportingMth;
</code>```

But that will only fix one problem. There seem to be others yet to be found.

Body:
I have  the following

use salesdb
go

create procedure monthlysales as
begin

create table MyTable( SalesFactID integer identity(1,1),
ReportingMth date,
customer_id varchar(50),
ReferenceID navarchar(50),
LstOrderDte date);

Insert into MyTable

select
businessMth,
saleid as referenceid,
null as lastorderte

from sourcetble;

update MyTable
set lastorderte = sls.max_orderdte
from ( select
st.customer_id,
ftmytbl.ReportingMth,
max(salesdate) as max_orderdte

from sales_table st

left outer join mytable ftmytbl
on ftmytbl.customerid=st.customerRef

where saleste<=ftmytbl.ReportingMth

group by customer_id

)up

where mytable.customer_id=up.customer_id
and mytable.reportingmth=up.ReportingMth;

end;

execute monthlysales

error invalid object name mytable.reportingmth

How can i fix this? Please assist.

Body:
Search for that text. Where is it? It is in the where clause of the outermost select statement. You used a derived table named up (which is a crap name, btw - as are many of your names) in the join. The outer query knows only 2 tables - up and MyTable (or is it mytable? BE CONSISTENT!) and can only refer to columns in those tables.

To correct this particular problem, change this:

and mytable.reportingmth=up.ReportingMth;

to

and MyTable.ReportingMth = up.ReportingMth;

But that will only fix one problem. There seem to be others yet to be found.


问:
Java While loop condition isn't being exicuted
I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code: </p>

```<code>import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int counter = 0;
    String[] arr = new String[15];
    System.out.println("Enter item or type 'zzz' to quit");
    arr[0] = input.nextLine();
    counter++;

     do{
         arr[counter] = input.nextLine();
         if (input.equals("zzz")){
             System.out.println("bleh");
         }
         counter++;

     } while (!input.equals("zzz") && counter <= 14);

     Arrays.sort(arr);
     System.out.println("Array is " + Arrays.toString(arr));
}
</code>```

答:
```<code>import java.util.*;
public class StringSort2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter = 0;
        String[] arr = new String[15];
        System.out.println("Enter item or type 'zzz' to quit");
        arr[counter] = input.nextLine();
        counter++;

         do{
              arr[counter] = input.nextLine();
             if (arr[counter].equals("zzz")){System.out.println("bleh");}
                counter++;

        }while (!arr[counter].equals("zzz") && counter <= 14);

         Arrays.sort(arr);
        System.out.println("Array is " + Arrays.toString(arr));
    }

}
</code>```

<p>You meant to compare the input String, not the Scanner object. I also removed your magic number "0" index that you had , since you already set your counter to 0. </p>

Body:
I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code:

import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int counter = 0;
    String[] arr = new String[15];
    System.out.println("Enter item or type 'zzz' to quit");
    arr[0] = input.nextLine();
    counter++;

     do{
         arr[counter] = input.nextLine();
         if (input.equals("zzz")){
             System.out.println("bleh");
         }
         counter++;

     } while (!input.equals("zzz") && counter <= 14);

     Arrays.sort(arr);
     System.out.println("Array is " + Arrays.toString(arr));
}

Body:
import java.util.*;
public class StringSort2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter = 0;
        String[] arr = new String[15];
        System.out.println("Enter item or type 'zzz' to quit");
        arr[counter] = input.nextLine();
        counter++;

         do{
              arr[counter] = input.nextLine();
             if (arr[counter].equals("zzz")){System.out.println("bleh");}
                counter++;

        }while (!arr[counter].equals("zzz") && counter <= 14);

         Arrays.sort(arr);
        System.out.println("Array is " + Arrays.toString(arr));
    }

}

You meant to compare the input String, not the Scanner object. I also removed your magic number "0" index that you had , since you already set your counter to 0.


问:
Public key authenticity in Bitcoin
I have a fundamental confusion about the public key cryptography in the Bitcoin (Blockchain) field.

For example, I understand that, in Bitcoin, when Bob wants to make a transaction, he sends out a transaction that contains the following:

The plain transaction message (such as Bob sends 5 Bitcoins to Alice).

Bob's public key

The digital signature of the transaction, signed using Bob's private key

I understand the whole Bitcoin network will validate this transaction based on Bob's public key and digital signature, which is broadcasted along with the plain transaction info all across the network.

However, what if the above transaction (that Bob sends Alice 5 bitcoins) is initiated by Eve? Eve broadcasts the plain transaction message, her public key, the digital signature signed using her private key. It seems the whole Bitcoin network will also validate the transaction based on the provided information.

Can you please clarify what type of wrong thinking I'm having?

Thanks a lot!

Cheers,
M.

答:
Everything is correct. But, Bob cannot send any Public Key. He must provide the Pubkey, related to the address, from which he take 5 BTC for send further. In the Bitcon design, the address is hash of the Pubkey.

As result, Eve does not know pubkey for Bob's address, and she unable send transaction, which spends Bob's money. But, of course, she able to send transaction with pubkey for address, she owns. By other words, Eve can spend her own money, and this is OK.

If you will see details of the Bitcoin script, you will see typical spending script:

ScriptPubKey = OP_DUP OP_HASH160  OP_EQUAL OP_CHECKSIG

This script duplicate pubkey, hashing one copy, compare hashed copy with btc_address, and if equal - checks signature. As you see, no any pubkey acceptable.

Title: Public key authenticity in Bitcoin


问:
How to check the application in Firebase Functions
I have two Android apps that I'm calling "appClient" and "appServer". I'm using Firebase authentication to register and further log in on both apps, but a user registered on appClient cannot log in on appServer and vice versa. So I found a way to differentiate those users calling a Firebase Function every time a new user is registered and including Custom Claims to them. Here is the Custom Claims documentation: https://firebase.google.com/docs/auth/admin/custom-claims

I'm using this code

```<code>// On sign up.
exports.processSignUp = functions.auth.user().onCreate((user) => {
  // Check if user meets role criteria.
  if ("how to check if the incoming user came from appClient or appServer???") {
    const customClaims = {
      client: true
    };
    // Set custom user claims on this newly created user.
    return admin.auth().setCustomUserClaims(user.uid, customClaims)
      .then(() => {
        // Update real-time database to notify client to force refresh.
        const metadataRef = admin.database().ref("metadata/" + user.uid);
        // Set the refresh time to the current UTC timestamp.
        // This will be captured on the client to force a token refresh.
        return metadataRef.set({refreshTime: new Date().getTime()});
      })
      .catch(error => {
        console.log(error);
      });
  }
});
</code>```

But I didn't find a way to check from which application the new user came.
Is there a way to check this?

答:
It's currently not possible to determine which app a user was using when the account was created.  The only inputs to an auth onCreate type function are the two arguments of type UserRecord and EventContext.

If you look through the properties of those objects thoroughly, you will see nothing that discerns the app.  You'll need to find another way of setting up the custom claims, perhaps by passing the user's UID and some identifying data into an HTTP or callable type function.

Body:
I have two Android apps that I'm calling "appClient" and "appServer". I'm using Firebase authentication to register and further log in on both apps, but a user registered on appClient cannot log in on appServer and vice versa. So I found a way to differentiate those users calling a Firebase Function every time a new user is registered and including Custom Claims to them. Here is the Custom Claims documentation: https://firebase.google.com/docs/auth/admin/custom-claims

I'm using this code

// On sign up.
exports.processSignUp = functions.auth.user().onCreate((user) => {
  // Check if user meets role criteria.
  if ("how to check if the incoming user came from appClient or appServer???") {
    const customClaims = {
      client: true
    };
    // Set custom user claims on this newly created user.
    return admin.auth().setCustomUserClaims(user.uid, customClaims)
      .then(() => {
        // Update real-time database to notify client to force refresh.
        const metadataRef = admin.database().ref("metadata/" + user.uid);
        // Set the refresh time to the current UTC timestamp.
        // This will be captured on the client to force a token refresh.
        return metadataRef.set({refreshTime: new Date().getTime()});
      })
      .catch(error => {
        console.log(error);
      });
  }
});

But I didn't find a way to check from which application the new user came.
Is there a way to check this?


答:
The reason your code isn't working is that input is the scanner object, and the equals method on the scanner object doesn't refer to the data being read by it. A way of doing this so that it works would be:</p>

```<code>import java.util.*;
public class Help {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter = 0;
        String[] arr = new String[15];
        String inputString = null;

        System.out.println("Enter item or type 'zzz' to quit");
        do{
            inputString = input.nextLine();
            arr[counter] = inputString;
            if (inputString.equals("zzz")){System.out.println("bleh");}
            counter++;

        }while (!inputString.equals("zzz") && counter <= 14);

        Arrays.sort(arr);
        System.out.println("Array is " + Arrays.toString(arr));
    }
}
</code>```

Title: Java While loop condition isn't being exicuted

Body:
The reason your code isn't working is that input is the scanner object, and the equals method on the scanner object doesn't refer to the data being read by it. A way of doing this so that it works would be:

import java.util.*;
public class Help {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter = 0;
        String[] arr = new String[15];
        String inputString = null;

        System.out.println("Enter item or type 'zzz' to quit");
        do{
            inputString = input.nextLine();
            arr[counter] = inputString;
            if (inputString.equals("zzz")){System.out.println("bleh");}
            counter++;

        }while (!inputString.equals("zzz") && counter <= 14);

        Arrays.sort(arr);
        System.out.println("Array is " + Arrays.toString(arr));
    }
}


问:
C++ to Java Code Conversion
I have in C++

```<code>r.bits[k] &= 0xFF ^ msk;
</code>```

So in Java

```<code>r.bits[k] = r.bits[k] & 0xFF,
</code>```

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.

答: Caret symbol in C++ means XOR logical operation. Meaning for the code 0xFF ^ msk; is that you take bits in msk and invert them (zeroes to ones and vice versa)

Title: C++ to Java Code Conversion

Body:
I have in C++

r.bits[k] &= 0xFF ^ msk;

So in Java

r.bits[k] = r.bits[k] & 0xFF,

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.