问:
When select an spinner item, selecteditem changes to first item
i've implemented a spinner with custom adapter.
When i select any item of this spinner, it will cause to disappear from the spinners list.
The position gets overridden by the first item of the list, making in appear double.
e.g:

Click on spinner:

Item 1

Item 2

Item 3 <-- Select Item 3

Reopen spinner:

Item 1

Item 2

Item 1

Does somebody know, why the postion gets overridden and how to avoid that?

```<code>public class activityScheduler extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

   Spinner spinner;
   Adapter.spinner.spinAdapterActuator componentActuator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);

        spinner =  findViewById(R.id.spinner_sensors);

        spinner.setOnItemSelectedListener(this);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Actuator i = componentActuator.getActuator(position);
            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        Update();

         }
      });
    }

    public void Update() {

        ArrayList<Actuator> components = new ArrayList<>();
        List<Actuator> componentList = allOperationList();
        item = new Actuator();

        for (int i=0; i < componentList.size(); i++)
        {
            item = componentList.get(i);
            components.add(item);
            Log.d(componentList.size() + "",item.name);
        }

        componentActuator = new spinner.spinAdapterActuator(activityMain.getContextOfApplication(),components);
        spinner.setAdapter(componentActuator);
        componentActuator.notifyDataSetChanged();

}
  public List<Actuator> allOperationList (){
        return new Select()
                .from(Actuator.class)
                .execute();
    }
}

// And the adapter

 public static class spinAdapterActuator extends BaseAdapter {
        Context context;
        private ArrayList<Actuator> arrayList;

        public spinAdapterActuator (Context context, ArrayList<Actuator> arrayList) {
            this.context = context;
            this.arrayList = arrayList;
        }

        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        public Actuator getActuator(int position) {
            return arrayList.get(position);
        }

        public View getView (int position, View convertView, ViewGroup parent){

            if(convertView == null){
                convertView = View.inflate(context,R.layout.spinner_scheduler, null);

                ImageView icon = convertView.findViewById(R.id.imageView);
                TextView name = convertView.findViewById(R.id.txt_component);

                Actuator item = arrayList.get(position);
                name.setText(item.getDescription());
                icon.setImageResource(Converter.toImg(item.getName(),1));
            }
            return convertView;

        }
    }

</code>```

答:
I've tracked the issue myself, the issue is that I used the getview method in wrong way:

```<code>if(convertView == null){
                convertView = View.inflate(context,R.layout.spinner_scheduler, null);
                ImageView icon = convertView.findViewById(R.id.imageView);
                TextView name = convertView.findViewById(R.id.txt_component);
                name.setText(item.getDescription());
                icon.setImageResource(Converter.toImg(item.getName(),1));
            }
            return convertView;

</code>```

Should be

```<code>if(convertView == null){
                convertView = View.inflate(context,R.layout.spinner_scheduler, null);
            }
ImageView icon = convertView.findViewById(R.id.imageView);
                TextView name = convertView.findViewById(R.id.txt_component);
                name.setText(item.getDescription());
                icon.setImageResource(Converter.toImg(item.getName(),1));
            return convertView;
</code>```

Body:
i've implemented a spinner with custom adapter.
When i select any item of this spinner, it will cause to disappear from the spinners list.
The position gets overridden by the first item of the list, making in appear double.
e.g:

Click on spinner:

Item 1

Item 2

Item 3 <-- Select Item 3

Reopen spinner:

Item 1

Item 2

Item 1

Does somebody know, why the postion gets overridden and how to avoid that?

public class activityScheduler extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

   Spinner spinner;
   Adapter.spinner.spinAdapterActuator componentActuator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);

        spinner =  findViewById(R.id.spinner_sensors);

        spinner.setOnItemSelectedListener(this);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Actuator i = componentActuator.getActuator(position);
            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        Update();

         }
      });
    }

    public void Update() {

        ArrayList<Actuator> components = new ArrayList<>();
        List<Actuator> componentList = allOperationList();
        item = new Actuator();

        for (int i=0; i < componentList.size(); i++)
        {
            item = componentList.get(i);
            components.add(item);
            Log.d(componentList.size() + "",item.name);
        }

        componentActuator = new spinner.spinAdapterActuator(activityMain.getContextOfApplication(),components);
        spinner.setAdapter(componentActuator);
        componentActuator.notifyDataSetChanged();

}
  public List<Actuator> allOperationList (){
        return new Select()
                .from(Actuator.class)
                .execute();
    }
}

// And the adapter

 public static class spinAdapterActuator extends BaseAdapter {
        Context context;
        private ArrayList<Actuator> arrayList;

        public spinAdapterActuator (Context context, ArrayList<Actuator> arrayList) {
            this.context = context;
            this.arrayList = arrayList;
        }

        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        public Actuator getActuator(int position) {
            return arrayList.get(position);
        }

        public View getView (int position, View convertView, ViewGroup parent){

            if(convertView == null){
                convertView = View.inflate(context,R.layout.spinner_scheduler, null);

                ImageView icon = convertView.findViewById(R.id.imageView);
                TextView name = convertView.findViewById(R.id.txt_component);

                Actuator item = arrayList.get(position);
                name.setText(item.getDescription());
                icon.setImageResource(Converter.toImg(item.getName(),1));
            }
            return convertView;

        }
    }

Body:
I've tracked the issue myself, the issue is that I used the getview method in wrong way:

if(convertView == null){
                convertView = View.inflate(context,R.layout.spinner_scheduler, null);
                ImageView icon = convertView.findViewById(R.id.imageView);
                TextView name = convertView.findViewById(R.id.txt_component);
                name.setText(item.getDescription());
                icon.setImageResource(Converter.toImg(item.getName(),1));
            }
            return convertView;

Should be

if(convertView == null){
                convertView = View.inflate(context,R.layout.spinner_scheduler, null);
            }
ImageView icon = convertView.findViewById(R.id.imageView);
                TextView name = convertView.findViewById(R.id.txt_component);
                name.setText(item.getDescription());
                icon.setImageResource(Converter.toImg(item.getName(),1));
            return convertView;


来源: stackexchange

问:
How to apply conditional formatting (if cell is in another range) to a range of cells
So I have searched through several different questions related to this. None of them seem to be asking exactly what I'm looking for and none of the solutions I've found have worked for me thus far.

I have several columns of data (Player names) where each column's values are generated from a formula in the 2nd row of that column. The 1st row is a header (Game name). This whole range is the collection of which players are willing to play which games. These are columns D-J(ish, the list is dynamically generated with another formula, based on form responses)

I have another range of data where the 1st column is the Player and the 2nd is the player's PREFERRED game. This data is also generated with a formula based on form responses. These are columns A-B.

Here's what I'm trying to do

Using conditional formatting in columns D-J, I want to highlight the player's name if this game (in row 1 of this column) is their preferred game (range A2:B).

I've tried several different variations of VLOOKUPS, MATCHES, and FILTERS in the conditional formatting, but so far nothing has worked. The problem I run into every time is that I can't figure out how to reference the cell that the formatting is applying to, but still have it reference each individual cell over the whole range.

I know I could do this if I applied an individual conditional formatting to each individual cell. However that is a very time consuming and inelegant solution to this issue considering I'm expecting my data range to be much larger in the future. I need a conditional formatting formula that will work across the whole range or , at the very least, for an entire column.

This is a mock of what I'm trying to accomplish:

This is a link to a mock of my sheet so that you can clearly see the data layout and specific formulas I'm using:
https://docs.google.com/spreadsheets/d/1wy1T6dWJwNC_EfdCAbkuxtkJH7y4Cg3x4IyEk6R567M/edit?usp=sharing

答:
use:

```<code>=REGEXMATCH(D3, TEXTJOIN("|", 1, FILTER($A$3:$A, $B$3:$B=D$2)))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
use:

=REGEXMATCH(D3, TEXTJOIN("|", 1, FILTER($A$3:$A, $B$3:$B=D$2)))


问:
Thymeleaf path variable is not working. What am I doing wrong?
Something is keeping me from setting a path variable with Thymeleaf and HTML in an HTML Form.
I want to simply enter 33 into a form and get localhost:8080/blog/33  for a url, but I can only get a query string or malformed brackets and etc.

some example attempts and results:

th:action="@{/blog/{id}(id = ${id})}"

localhost:8080/blog/?id=33

th:action="@{/blog/+ ${id}}"

localhost:8080/blog/+%20$%7Bid%7D?id=33

what I want is:

localhost:8080/blog/33

the whole code for this form is below:

```<code><!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
    <head>
        <title>Form Submission</title>
        <style>
            button{
                margin-top:20px;
                width: 250px;
            }
        </style>
    </head>
    <body>
        <h2>Delete Entry</h2>
        <form action="#" th:action="@{/blog/{id}(id = ${id})}" th:object="${blog}" method="get" >
            <fieldset>
                <p>Delete ID: <input type="text" th:field="*{id}" required /></p>
                <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
            </fieldset>
        </form>
        <button onclick="window.location.href = '/'">Menu</button>
    </body>
</html>
</code>```

答:
This syntax is correct: @{/blog/{id}(id = ${id})}.

The reason you are getting localhost:8080/blog/?id=33 is probably because ${id} is empty when the form is created, and when you click the submit button, it is adding ?id=33 to the url (because the method is get and you have an input with the same name="id": <input type="text" th:field="*{id}" required />.

There is no html/thymeleaf way (without javascript) to get a form field into the path part of a URL (if that is what you're expecting).  You'll have to use a javascript library if you want that to happen.

Body:
Something is keeping me from setting a path variable with Thymeleaf and HTML in an HTML Form.
I want to simply enter 33 into a form and get localhost:8080/blog/33  for a url, but I can only get a query string or malformed brackets and etc.

some example attempts and results:

th:action="@{/blog/{id}(id = ${id})}"

localhost:8080/blog/?id=33

th:action="@{/blog/+ ${id}}"

localhost:8080/blog/+%20$%7Bid%7D?id=33

what I want is:

localhost:8080/blog/33

the whole code for this form is below:

<!DOCTYPE HTML>

        <title>Form Submission</title>

Delete Entry

        <form action="#" th:action="@{/blog/{id}(id = ${id})}" th:object="${blog}" method="get" >
            <fieldset>

Delete ID: <input type="text" th:field="*{id}" required />

<input type="submit" value="Submit" /> <input type="reset" value="Reset" />

            </fieldset>
        </form>
        <button onclick="window.location.href = '/'">Menu</button>


问:
LookupAccountSid() corrupts memory heap
I spent few days chasing a crash that manifests as structured exception 0xC0000374 (heap corruption)... Of course, reproducible only in customer environment.

Narrowed it down to this (very simplified) code:

```<code>    DWORD cchName = 0, cchDomain = 0;
    SID_NAME_USE type;
    if (!LookupAccountSidW(NULL, pSid, NULL, &cchName, NULL, &cchDomain, &type))
    {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
            <bail via exception or return>;
    }

    cout << cchName << ":" << cchDomain << " -> ";

    DWORD cchName1 = (cchName + 1), cchDomain1 = (cchDomain + 1);

    LPWSTR pName   = ... allocate cchName1   WCHARs ...;
    LPWSTR pDomain = ... allocate cchDomain1 WCHARs ...;

    if (!LookupAccountSidW(NULL, pSid, pName, &cchName1, pDomain, &cchDomain1, &type))
        <bail via exception or return>;

    cout << cchName1 << ":" << cchDomain1 << endl;

    ... deallocate pDomain; // <- here Application Verifier detects corrupted block
    ... deallocate pName;
</code>```

Please, ignore possibility of memory leak (code is simplified). Also, note that according to MSDN over-allocating by 1 symbol is not necessary. But let me describe what I see in debugger...

For all (but one) SIDs encountered it prints out things like 16:7 -> 15:6 or 6:7 -> 5:6 and everything is dandy. Basically, first call returns required buffer sizes (including terminating NUL), second one returns number of symbols written (excluding NUL) into provided buffers (which are over-allocated by 1, btw).

Now, one specific SID results in 6:3 -> 5:2 output. But when I look at pDomain buffer (which is 4 symbols long) I see truncated domain name ABCD (actual domain name is 6 symbols) followed by NUL (which corrupts heap control structures). So LookupAccountSidW claims it has written only 2(+1) symbols, while in reality is has written 4(+1) symbols into a buffer that is 4 symbols long.

From my standpoint it is a clear bug in LookupAccountSidW, but I would really like to figure out how that SID differ from others. Maybe it was migrated from another (shorter) domain?

P.S. It is Windows 10 (10.0.14393.2969)

P.P.S. SID is S-1-5-21-<3-part domain id>-<user id>

答:
I came across this issue, so I'm documenting my findings for whoever has the misfortune to fall into this trap.

It appears that there is a case where LookupAccountSidA will cause a heap overrun in certain environments.

It is possible to migrate users from one domain to another. The SIDs can remain as part of the domain for historical reasons. LookupAccountSidA is supposed to support looking up these SIDs, and it does so, except that it will overrun the heap internally, when the name of the old domain is longer than the new one.

Under the hood, LookupAccountSidA calls LsaLookupSids2 which gets a PLSA_TRANSLATED_NAME (the names array) and a PLSA_REFERENCED_DOMAIN_LIST. The issue here is that LookupAccountSidA makes use of the wrong array position in order to set up the size required for the domain data. If memory serves, it uses position zero where it should be something other than that. So, if the domain in position zero has a name shorter than the one associated with the SID you're looking up, LookupAccountSidA will overwrite the heap, all on its own.

The only work-around is to pass two buffers of 256 chars, and fill-initialize them to '\0'. Pass these in for your name and domain arrays, and do not trust the size that is returned for the domain. Copy these out of the buffers you get back, and careful not to overrun your buffers on read.

The better option, of course, is to use LsaLookupSids2 and do Unicode-to-multibyte conversion if necessary.

PS: A representative from Microsoft told me that this was a bug that was introduced between Windows 7 and 8. I don't know whether or not this affects LookupAccountSidW, but it most certainly is possible.

Title: LookupAccountSid() corrupts memory heap

Body:
I spent few days chasing a crash that manifests as structured exception 0xC0000374 (heap corruption)... Of course, reproducible only in customer environment.

Narrowed it down to this (very simplified) code:

    DWORD cchName = 0, cchDomain = 0;
    SID_NAME_USE type;
    if (!LookupAccountSidW(NULL, pSid, NULL, &cchName, NULL, &cchDomain, &type))
    {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
            <bail via exception or return>;
    }

    cout << cchName << ":" << cchDomain << " -> ";

    DWORD cchName1 = (cchName + 1), cchDomain1 = (cchDomain + 1);

    LPWSTR pName   = ... allocate cchName1   WCHARs ...;
    LPWSTR pDomain = ... allocate cchDomain1 WCHARs ...;

    if (!LookupAccountSidW(NULL, pSid, pName, &cchName1, pDomain, &cchDomain1, &type))
        <bail via exception or return>;

    cout << cchName1 << ":" << cchDomain1 << endl;

    ... deallocate pDomain; // <- here Application Verifier detects corrupted block
    ... deallocate pName;

Please, ignore possibility of memory leak (code is simplified). Also, note that according to MSDN over-allocating by 1 symbol is not necessary. But let me describe what I see in debugger...

For all (but one) SIDs encountered it prints out things like 16:7 -> 15:6 or 6:7 -> 5:6 and everything is dandy. Basically, first call returns required buffer sizes (including terminating NUL), second one returns number of symbols written (excluding NUL) into provided buffers (which are over-allocated by 1, btw).

Now, one specific SID results in 6:3 -> 5:2 output. But when I look at pDomain buffer (which is 4 symbols long) I see truncated domain name ABCD (actual domain name is 6 symbols) followed by NUL (which corrupts heap control structures). So LookupAccountSidW claims it has written only 2(+1) symbols, while in reality is has written 4(+1) symbols into a buffer that is 4 symbols long.

From my standpoint it is a clear bug in LookupAccountSidW, but I would really like to figure out how that SID differ from others. Maybe it was migrated from another (shorter) domain?

P.S. It is Windows 10 (10.0.14393.2969)

P.P.S. SID is S-1-5-21-<3-part domain id>-<user id>


问:
"Declare" clause before "Begin" clause in CREATE PROCEDURE
I wonder whether there is any difference between these two options of declaring variables in stored procedures? Any drawbacks?</p>

```<code>CREATE PROCEDURE dbo.HelloWorld
AS
    DECLARE @message NVARCHAR(30)
BEGIN
    SET @message = 'Hello World!'
    SELECT @message
END
GO

CREATE PROCEDURE dbo.HelloWorld2
AS
BEGIN
    DECLARE @message NVARCHAR(30)
    SET @message = 'Hello World!'
    SELECT @message
END
GO
</code>```

答:
No real difference basically the first one is the same as writing this:

```<code>CREATE PROCEDURE dbo.HelloWorld
AS
   BEGIN
     DECLARE @message NVARCHAR(30)
     BEGIN
       SET @message = 'Hello World!'
       SELECT @message
     END
   END
GO
</code>```

There is an implied code block after the AS.

cf https://learn.microsoft.com/en-us/sql/t-sql/statements/create-procedure-transact-sql?view=sql-server-ver15

Body:
I wonder whether there is any difference between these two options of declaring variables in stored procedures? Any drawbacks?

CREATE PROCEDURE dbo.HelloWorld
AS
    DECLARE @message NVARCHAR(30)
BEGIN
    SET @message = 'Hello World!'
    SELECT @message
END
GO

CREATE PROCEDURE dbo.HelloWorld2
AS
BEGIN
    DECLARE @message NVARCHAR(30)
    SET @message = 'Hello World!'
    SELECT @message
END
GO

Body:
No real difference basically the first one is the same as writing this:

CREATE PROCEDURE dbo.HelloWorld
AS
   BEGIN
     DECLARE @message NVARCHAR(30)
     BEGIN
       SET @message = 'Hello World!'
       SELECT @message
     END
   END
GO

There is an implied code block after the AS.

cf https://learn.microsoft.com/en-us/sql/t-sql/statements/create-procedure-transact-sql?view=sql-server-ver15


问:
Capture nethogs output in log file
I want to check the network bandwidth used by my process.
For this i found that nethogs tool is useful. Using this tool i can see which process is eating up a network bandwidth and process behaviour.
But how do I capture data from nethogs for a my process and store it into log file ?</p>

答:
You can run nethogs in background in tracemode and write output to a file like this:

```<code>sudo nethogs -t eth1 &> /var/tmp/nethogs.log &
</code>```

Download and build the nethogs-parser as described here.

Then after you have accumulated enough data you can run the parser to see the results:

```<code>./hogs -type=pretty /var/tmp/nethogs.log
</code>```

Make sure to kill the running nethogs process when you are done collecting data.

More info here on automating the task.

ContentLicense: CC BY-SA 3.0

Title: Capture nethogs output in log file

Body:
You can run nethogs in background in tracemode and write output to a file like this:

sudo nethogs -t eth1 &> /var/tmp/nethogs.log &

Download and build the nethogs-parser as described here.

Then after you have accumulated enough data you can run the parser to see the results:

./hogs -type=pretty /var/tmp/nethogs.log

Make sure to kill the running nethogs process when you are done collecting data.

More info here on automating the task.


问:
How to set a default value to datetime_field
I am trying to set a default value for datetime_field inside the view. I have checked multiple sources and all fail to give the correct results.

For instance this example does not work
https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

```<code>datetime_field("user", "born_on", min: "2014-05-20T00:00:00")
# => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />
</code>```

Here is my code:

```<code><div class="form-group">
   <%= f.datetime_field(:date_reported, class: "form-control col-sm-3", min: "2014-05-20T00:00:00") %>
</div>
</code>```

My code displays this:

答:
Answer to my question:

Inside controller

```<code>def new
  @mine = Mine.new
  @time_now = Time.new.strftime("%Y-%m-%dT%k:%M")
end
</code>```

Inside View

```<code><div class="form-group">
  <%= f.datetime_field(:date_reported, class: "form-control col-sm-3", value: @time_now ) %>
</div>
</code>```

Body:
I am trying to set a default value for datetime_field inside the view. I have checked multiple sources and all fail to give the correct results.

For instance this example does not work
https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

datetime_field("user", "born_on", min: "2014-05-20T00:00:00")
# => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />

Here is my code:

   <%= f.datetime_field(:date_reported, class: "form-control col-sm-3", min: "2014-05-20T00:00:00") %>

My code displays this:

Body:
Answer to my question:

Inside controller

def new
  @mine = Mine.new
  @time_now = Time.new.strftime("%Y-%m-%dT%k:%M")
end

Inside View

<div class="form-group">
  <%= f.datetime_field(:date_reported, class: "form-control col-sm-3", value: @time_now ) %>
</div>


问:
Fancybox 3 Transition Animation Effect Between IFrame Content
I have a form that pulls up in a Fancybox 3 iframe. The user submits the form, it processes and forwards to a confirmation page. When this transition happens, Fancybox updates the iframe size of the confirmation page to the size of the content (which is smaller than the form). So far, so good.

However, I'd like to make this transition animated so the iframe doesn't just change the size, rather animates it smoothly as it transitions from larger to smaller. I see how to do this with inline content in the FancyBox3 documentation, but have yet to find how to make this happen with iframe content. Is it possible and if so how would I go about doing this?

答: Sorry, but that is currently not possible out of the box, if you are using auto-size feature. Maybe you could use afterLoad callback to store initial width/height values, then on next load event you could read new values and animate iframe wrapping element to the new values. It could work, but I have not tried that.


问:
Carets Feature Selection using Genetic Algorithms: How to extract the results?
I am new to carets Genetic Algorithm Feature Selection and started with a simple run on the iris dataset. I want to extract the best features, their accuracy and also the total number of model trainings (evaluation of a feature subset). Furthermore i do not understand how the final model is build.

Caret provides a description of the method: https://topepo.github.io/caret/feature-selection-using-genetic-algorithms.html
However, i did not really understand how many model trainings they will need in the end and how the final model is build.

```<code>library(caret)

dataset <- iris
levels(dataset$Species) <- c(0, 0, 1)

ga_ctrl <- gafsControl(functions = caretGA, method = "cv", number = 3, verbose = TRUE)
res <- caret::gafs(x = dataset[, 1:(length(dataset)-1)],
 y = dataset[, length(dataset)],
 iters = 5,
 popSize = 6,
 pcrossover = 0.8,
 pmutation = 0.1,
 gafsControl = ga_ctrl,
 method = "glm", family = binomial(link = 'logit'),
 trControl = trainControl(method = "cv"))
</code>```

I got this output (without setting a specific seed now):

```<code>Fold1 1 0.96 (2)
Fold1 2 0.96->0.97 (2->4, 50.0%) *
Fold1 3 0.97->0.9788889 (4->2, 50.0%) *
Fold1 4 0.9788889->0.9809091 (2->2, 100.0%) *
Fold1 5 0.9809091->0.98 (2->2, 100.0%)
Fold2 1 0.9718182 (3)
Fold2 2 0.9718182->0.9709091 (3->4, 75.0%)
Fold2 3 0.9718182->0.9718182 (3->4, 75.0%)
Fold2 4 0.9718182->0.9709091 (3->1, 33.3%)
Fold2 5 0.9718182->0.9688889 (3->3, 50.0%)
Fold3 1 0.97 (3)
Fold3 2 0.97->0.9688889 (3->3, 100.0%)
Fold3 3 0.97->0.97 (3->3, 100.0%)
Fold3 4 0.97->0.969798 (3->2, 66.7%)
Fold3 5 0.97->0.9709091 (3->3, 100.0%) *
+ final GA
 1 0.9533333 (1)
 2 0.9533333->0.96 (1->2, 50.0%) *
 3 0.96->0.9533333 (2->2, 100.0%)
 4 0.96->0.98 (2->3, 66.7%) *
 5 0.98->0.9733333 (3->3, 100.0%)
+ final model
</code>```

res$ga$fit gives Accuracy 0.96 while res$fit gives Accuracy 0.9533333, but the 0.98 should be the correct value, shouldn't it?

For the total number of trainings i suppose it is something like

```<code>popSize * iters * folds
</code>```

with folds being the number from ga_ctrl, but I am not sure about it.

For the best features, is res$optVariables correct?

答:
I agree that documentation on both books (feature engineering and applied predictive) are hard to understand. There are couple of terms which are used interchangeably (eg. iteration vs generation) and make it all a bit ambiguous.

PopSize is one of them: it is unclear whether it refers to the number or length of the individuals (chromosomes).

I believe that popSize refers to the initial size of the population (number of individual/chromosomes). I am unsure whether next generations (also name iterations) will have those 50 individuals over and over again. If so, then, you calculations should be correct.

$optVariables should store the best variables. You can also (probably) find them within your final model.
I am running PLS and I can find them on MODEL$fit$finalModel$xNames

The final GA is run against all the observations on your dataset.

Body:
I am new to carets Genetic Algorithm Feature Selection and started with a simple run on the iris dataset. I want to extract the best features, their accuracy and also the total number of model trainings (evaluation of a feature subset). Furthermore i do not understand how the final model is build.

Caret provides a description of the method: https://topepo.github.io/caret/feature-selection-using-genetic-algorithms.html
However, i did not really understand how many model trainings they will need in the end and how the final model is build.

library(caret)

dataset <- iris
levels(dataset$Species) <- c(0, 0, 1)

ga_ctrl <- gafsControl(functions = caretGA, method = "cv", number = 3, verbose = TRUE)
res <- caret::gafs(x = dataset[, 1:(length(dataset)-1)],
 y = dataset[, length(dataset)],
 iters = 5,
 popSize = 6,
 pcrossover = 0.8,
 pmutation = 0.1,
 gafsControl = ga_ctrl,
 method = "glm", family = binomial(link = 'logit'),
 trControl = trainControl(method = "cv"))

I got this output (without setting a specific seed now):

Fold1 1 0.96 (2)
Fold1 2 0.96->0.97 (2->4, 50.0%) *
Fold1 3 0.97->0.9788889 (4->2, 50.0%) *
Fold1 4 0.9788889->0.9809091 (2->2, 100.0%) *
Fold1 5 0.9809091->0.98 (2->2, 100.0%)
Fold2 1 0.9718182 (3)
Fold2 2 0.9718182->0.9709091 (3->4, 75.0%)
Fold2 3 0.9718182->0.9718182 (3->4, 75.0%)
Fold2 4 0.9718182->0.9709091 (3->1, 33.3%)
Fold2 5 0.9718182->0.9688889 (3->3, 50.0%)
Fold3 1 0.97 (3)
Fold3 2 0.97->0.9688889 (3->3, 100.0%)
Fold3 3 0.97->0.97 (3->3, 100.0%)
Fold3 4 0.97->0.969798 (3->2, 66.7%)
Fold3 5 0.97->0.9709091 (3->3, 100.0%) *
+ final GA
 1 0.9533333 (1)
 2 0.9533333->0.96 (1->2, 50.0%) *
 3 0.96->0.9533333 (2->2, 100.0%)
 4 0.96->0.98 (2->3, 66.7%) *
 5 0.98->0.9733333 (3->3, 100.0%)
+ final model

res$ga$fit gives Accuracy 0.96 while res$fit gives Accuracy 0.9533333, but the 0.98 should be the correct value, shouldn't it?

For the total number of trainings i suppose it is something like

popSize * iters * folds

with folds being the number from ga_ctrl, but I am not sure about it.

For the best features, is res$optVariables correct?


问:
How does GridSearchCV use cores?
I'm doing a GridSearchCV, I had monitored the % of the core's and I have seen that when I was running a simple neural networ the 4 cores had the same %, but the when the grid search cv (n_jobs = 1) started there was a big confusion in the lines of the plot. Why? I Use Zorin

Below you can find the part of code where i do the gscv (but I changed n_jobs, inthe figure above it was used n_jobs = 1):

```<code>def build_regressor(opti, units1,units2, units3, acti, a, kern):

    model_TP = Sequential()
    model_TP.add(Dense(units = units1, input_shape = (X_train_TP.shape[1],), activation = acti, kernel_initializer = kern))
    model_TP.add(Dropout(a))
    model_TP.add(Dense(units = units2, activation = acti, kernel_initializer = kern))
    model_TP.add(Dropout(a))
    model_TP.add(Dense(units = units3, activation = acti, kernel_initializer = kern))
    model_TP.add(Dense(1,activation = 'linear'))
    model_TP.compile(loss = 'mse', optimizer = opti, metrics = ['mse'])
    return model_TP

parameters ={'units1' : [50,100,150],
             'units2' : [50,100,150],
             'units3' : [50,100,150],
             'batch_size' : [50,100,250],
              'kern':['random_normal','glorot_uniform','random_uniform'],
              'acti':['relu','sigmoid','linear'],
              'opti':[tf.keras.optimizers.Adamax(lr=0.001),
                      tf.keras.optimizers.Adam(lr=0.001)],
              'a' : [0.2,0.25]
                          }

regressor = KerasRegressor(build_fn = build_regressor, verbose = 1)

gridSearch = GridSearchCV(estimator=regressor,
                          param_grid=parameters,
                          cv=5, n_jobs = 4
                          )

grid_result = gridSearch.fit(X_train_TP, y_train_TP)

print('Grid Search Best score',gridSearch.best_score_)
print('Grid Search Best Parameters', gridSearch.best_params_)
print('Execution time',gridSearch.refit_time_)
</code>```

答:
As per the docs:

n_jobs: int or None, optional (default=None)

Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

You should be in a parallel context by default.

from sklearn.utils import _joblib
backend = _joblib.parallel_backend(_joblib.joblib.parallel.DEFAULT_BACKEND)
backend.new_backend_and_jobs
>>> (<joblib._parallel_backends.LokyBackend at 0x7f984f580dd8>, -1)
```

Hence the default n_jobs id -1 so GridSearchCV uses all of your CPUs when no n_jobs is passed.

Title: How does GridSearchCV use cores?

Body:
I'm doing a GridSearchCV, I had monitored the % of the core's and I have seen that when I was running a simple neural networ the 4 cores had the same %, but the when the grid search cv (n_jobs = 1) started there was a big confusion in the lines of the plot. Why? I Use Zorin

Below you can find the part of code where i do the gscv (but I changed n_jobs, inthe figure above it was used n_jobs = 1):

def build_regressor(opti, units1,units2, units3, acti, a, kern):

    model_TP = Sequential()
    model_TP.add(Dense(units = units1, input_shape = (X_train_TP.shape[1],), activation = acti, kernel_initializer = kern))
    model_TP.add(Dropout(a))
    model_TP.add(Dense(units = units2, activation = acti, kernel_initializer = kern))
    model_TP.add(Dropout(a))
    model_TP.add(Dense(units = units3, activation = acti, kernel_initializer = kern))
    model_TP.add(Dense(1,activation = 'linear'))
    model_TP.compile(loss = 'mse', optimizer = opti, metrics = ['mse'])
    return model_TP

parameters ={'units1' : [50,100,150],
             'units2' : [50,100,150],
             'units3' : [50,100,150],
             'batch_size' : [50,100,250],
              'kern':['random_normal','glorot_uniform','random_uniform'],
              'acti':['relu','sigmoid','linear'],
              'opti':[tf.keras.optimizers.Adamax(lr=0.001),
                      tf.keras.optimizers.Adam(lr=0.001)],
              'a' : [0.2,0.25]
                          }

regressor = KerasRegressor(build_fn = build_regressor, verbose = 1)

gridSearch = GridSearchCV(estimator=regressor,
                          param_grid=parameters,
                          cv=5, n_jobs = 4
                          )

grid_result = gridSearch.fit(X_train_TP, y_train_TP)

print('Grid Search Best score',gridSearch.best_score_)
print('Grid Search Best Parameters', gridSearch.best_params_)
print('Execution time',gridSearch.refit_time_)

Body:
As per the docs:

n_jobs: int or None, optional (default=None)

Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

You should be in a parallel context by default.

from sklearn.utils import _joblib
backend = _joblib.parallel_backend(_joblib.joblib.parallel.DEFAULT_BACKEND)
backend.new_backend_and_jobs
>>> (<joblib._parallel_backends.LokyBackend at 0x7f984f580dd8>, -1)

Hence the default n_jobs id -1 so GridSearchCV uses all of your CPUs when no n_jobs is passed.


问:
Android (3.0) Action Bar dont want to Go
I am working with XOOM and trying to hide action bar. So i follow the instruction did the following
in manifest file:

uses-sdk android:minSdkVersion="11" android:targetSdkVersion="11"

also set activity theme.

android:theme="@android:style/Theme.Holo.NoActionBar"

unfortunately i can still see the action bar. so i remove the holo action part from my manifest and added following code

ActionBar actionBar = getActionBar();
        actionBar.hide();

getting null pointer exception from hide() method. so i understand getActionBar() is returning null. Now i am curious what i am missing?

答:
you can hide the action bar (which will display in the top of the screen). If your activity is tab activity then use the following line after the setcontentview line

```<code>getParent().getActionBar().hide();
</code>```

If it is a normal activity then use

```<code>getActionBar().hide();
</code>```

And setting on manifest is also working for me, but only to the particular activity you can set like this not to application.

```<code>android:theme="@android:style/Theme.Holo.NoActionBar"
</code>```

Body:
you can hide the action bar (which will display in the top of the screen). If your activity is tab activity then use the following line after the setcontentview line

getParent().getActionBar().hide();

If it is a normal activity then use

getActionBar().hide();

And setting on manifest is also working for me, but only to the particular activity you can set like this not to application.

android:theme="@android:style/Theme.Holo.NoActionBar"


问:
Extract either two or three words and exclude duplicates and accronyms
I have a group of names worded in a bizarre fashion. Here is a sample:

```<code>Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster
</code>```

My goal is to clean it so either first and last name show for names or just team names is returned for teams. Here is what have tried:

```<code>df$name <- sub("^(.*[a-z])[A-Z]", "\\1", "\\1", df$name)
</code>```

This is what I'm getting returned

```<code>Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster
</code>```

To be clear, goal would be to have this:

```<code>Sammy Watkins
Buffalo Bills
New England Patriots
Tre'Quan Smith
JuJu Smith-Schuster
</code>```

data

```<code>df <- data.frame(name = c(
  "Sammy WatkinsS. Watkins",
  "Buffalo BillsBUF",
  "New England PatriotsNE",
  "Tre'Quan SmithT. Smith",
  "JuJu Smith-SchusterJ. Smith-Schuster"),
  stringsAsFactors = FALSE)
</code>```

答:
Two laps:

```<code>df$name <- gsub(".\\. .*", "", df$name)
df$name <- gsub("[A-Z]*$", "", df$name)
</code>```

The first line removes all cases of the form "x. surname" and the second removes all capital letters at the end of the string.

Body:
I have a group of names worded in a bizarre fashion. Here is a sample:

Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster

My goal is to clean it so either first and last name show for names or just team names is returned for teams. Here is what have tried:

df$name <- sub("^(.*[a-z])[A-Z]", "\\1", "\\1", df$name)

This is what I'm getting returned

Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster

To be clear, goal would be to have this:

Sammy Watkins
Buffalo Bills
New England Patriots
Tre'Quan Smith
JuJu Smith-Schuster

data

df <- data.frame(name = c(
  "Sammy WatkinsS. Watkins",
  "Buffalo BillsBUF",
  "New England PatriotsNE",
  "Tre'Quan SmithT. Smith",
  "JuJu Smith-SchusterJ. Smith-Schuster"),
  stringsAsFactors = FALSE)

Body:
Two laps:

df$name <- gsub(".\\. .*", "", df$name)
df$name <- gsub("[A-Z]*$", "", df$name)

The first line removes all cases of the form "x. surname" and the second removes all capital letters at the end of the string.


问:
How do I set size of colums in a table subform datasheet view in MS Access
I have a subform bugging me. The mainform contains buttons etc. Everytime the user close/open the form, the columns width is reset to whatever the table likes. If i open the table directly, the size is as i want. If i change it in the subform, it is not saved. (See screendump)

I would like "Phase" to stay about 2 cm width. I can enter the subform and edit the "Width" but that is only applied to the other views.

I hope you can help, Emil.

答:
Super annoying by default.
It seems to work as one would expect of you set the view mode to layout view. Drag column widths as needed and save. Go back to form view and it works. It's really dumb it doesn't work the same way in form view our design view.</p>


问:
Angular 8: max-height attribute for a material dialog is not working
I am working on a project in angular 8, where I have used a MatDialog to open new component with form inputs in a dialog. For example:

```<code>import {MatDialog} from '@angular/material/dialog';

import {AddDialogComponent} from '../add-dialog.component';

constructor(private dialog: MatDialog){
}

private addNewRow() {

    const dialogRef = this.dialog.open(AddDialogComponent, {

      width: 'auto',
      height: 'auto',
      maxHeight: '100vh',
      maxWidth:'100vw',
      data: Data
    });
    dialogRef.afterClosed().subscribe(
      result => {

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

Here when dialog get open, maxWidth: '100vw' works fine where as maxHeight: '100vh' is not supported. Also tried maxHeight: '100vh !important' and tried change style from .css file.

Both didn't work. Any suggestions or solution for this issue will be highly appreciated.

Thank you.

答:
It's because the .mat-dialog-content has a max-height: 65vh. You can either decide not to use the directive, or override this in your css:

```<code>.mat-dialog-content {
  max-height: initial;
}
</code>```

working example

Body:
I am working on a project in angular 8, where I have used a MatDialog to open new component with form inputs in a dialog. For example:

import {MatDialog} from '@angular/material/dialog';

import {AddDialogComponent} from '../add-dialog.component';

constructor(private dialog: MatDialog){
}

private addNewRow() {

    const dialogRef = this.dialog.open(AddDialogComponent, {

      width: 'auto',
      height: 'auto',
      maxHeight: '100vh',
      maxWidth:'100vw',
      data: Data
    });
    dialogRef.afterClosed().subscribe(
      result => {

         // statements
      });
  }

Here when dialog get open, maxWidth: '100vw' works fine where as maxHeight: '100vh' is not supported. Also tried maxHeight: '100vh !important' and tried change style from .css file.

Both didn't work. Any suggestions or solution for this issue will be highly appreciated.

Thank you.

Body:
It's because the .mat-dialog-content has a max-height: 65vh. You can either decide not to use the directive, or override this in your css:

.mat-dialog-content {
  max-height: initial;
}

working example


问:
Errno::ENOENT No such file or directory @ rb_sysopen
I'm trying to generate a simple Docx file and I'm getting the error:

Errno::ENOENT in ContratosController#page

No such file or directory @ rb_sysopen - /public/example.docx

I'm using the gem caracal

Routes.rb

```<code>Rails.application.routes.draw do
  get 'grayscale/index'
  get 'contratos/page'
</code>```

contratos.controller.rb

```<code>  def page

    Caracal::Document.save '/public/example.docx' do |docx|
      # page 1
      docx.h1 'Page 1 Header'
      docx.hr
      docx.p
      docx.h2 'Section 1'
      docx.p  'Lorem ipsum dolor....'
      docx.p

      # page 2
      docx.page
      docx.h1 'Page 2 Header'
      docx.hr
      docx.p
      docx.h2 'Section 2'
      docx.p  'Lorem ipsum dolor....'
      docx.ul do
        li 'Item 1'
        li 'Item 2'
      end
      docx.p
    end
    path = File.join(Rails.root, "public")
    send_file(File.join(path, "example.docx"))
  end
```
```

答:
You almost there, you need just edit a bit:</p>

```<code>def page
    Caracal::Document.save(Rails.root.join("public", "example.docx")) do |docx|
      # page 1
      docx.h1 'Page 1 Header'
      docx.hr
      docx.p
      docx.h2 'Section 1'
      docx.p  'Lorem ipsum dolor....'
      docx.p
    ...
end
</code>```

Body:
I'm trying to generate a simple Docx file and I'm getting the error:

Errno::ENOENT in ContratosController#page

No such file or directory @ rb_sysopen - /public/example.docx

I'm using the gem caracal

Routes.rb

Rails.application.routes.draw do
  get 'grayscale/index'
  get 'contratos/page'

contratos.controller.rb

  def page

    Caracal::Document.save '/public/example.docx' do |docx|
      # page 1
      docx.h1 'Page 1 Header'
      docx.hr
      docx.p
      docx.h2 'Section 1'
      docx.p  'Lorem ipsum dolor....'
      docx.p

      # page 2
      docx.page
      docx.h1 'Page 2 Header'
      docx.hr
      docx.p
      docx.h2 'Section 2'
      docx.p  'Lorem ipsum dolor....'
      docx.ul do
        li 'Item 1'
        li 'Item 2'
      end
      docx.p
    end
    path = File.join(Rails.root, "public")
    send_file(File.join(path, "example.docx"))
  end
```

Body:
You almost there, you need just edit a bit:

def page
    Caracal::Document.save(Rails.root.join("public", "example.docx")) do |docx|
      # page 1
      docx.h1 'Page 1 Header'
      docx.hr
      docx.p
      docx.h2 'Section 1'
      docx.p  'Lorem ipsum dolor....'
      docx.p
    ...
end


问:
C++ compilation error: error: expected primary-expression before ‘try’
Error:

```<code>/home/mike/Documents/PROJECTS/BUN/blib/bun/impl/DbBackend.hpp:61:21: error: expected primary-expression before ‘try’
                     try {
                     ^~~
/home/mike/Documents/PROJECTS/BUN/blib/bun/impl/DbBackend.hpp:67:21: error: expected ‘,’ or ‘;’ before ‘catch’
                     catch (std::exception const &except) {
                     ^~~~~
In file included from blib/bun/bun.hpp:3:0,
                 from main.cpp:12:
</code>```

Part of code:

```<code>                bool connect(std::string const &in_params) {
                    const auto backend_factory =
#ifdef BUN_SQLITE
                    soci::sqlite3;
#elif defined(BUN_POSTGRES)
                    soci::postgresql;
#elif defined(BUN_MYSQL)
                    soci::mysql;
#endif
                    try {
                         if (!_ok) {
                                          _sql_session.open(backend_factory, in_params);
                                          _ok = true;
                                   }
                    }
                    catch (std::exception const &except) {
                                     l().error(except.what());
                        _ok = false;
                    }
                              return _ok;
                }

                soci::session &session() {
                    return _sql_session;
                }
            };
</code>```

Makefile:

```<code>LDFLAGS := -L/usr/local/lib   \
-I/home/mike/Documents/PROJECTS/BUN/third_party/unqlite -I/home/mike/Documents/PROJECTS/BUN -I/home/mike/Documents/PROJECTS/BUN/third_party
# LDLIBS :=  -lpthread -lresolv
EXECUTABLE := main
# CXXFLAGS=-g -std=c++11 -Wall
CXXFLAGS=-g -std=c++17 -Wall

all: $(EXECUTABLE)

clean:
    rm -f $(EXECUTABLE) *.o
</code>```

I am trying to use Bun orm. In my program I only included bun.hpp file. I can't understand what is not ok for compiler before try ? Maybe because of that #ifdef operators above the try ? Also it says it expected , or ; before catch...

I am trying on ubuntu 18.04

答:
Your compile line doesn't define any of the options (unless they are coming from inside the file or another header) so you get:

```<code>bool connect(std::string const &in_params) {
                const auto backend_factory =
                try {
</code>```

To confirm you can add a "-E" to the g++ line to get the source after the preprocessor.

Another possibility is that you are defining more than one.
You could always #undef 2 of them and #define the last one to see if it compiles that way (just as a test).

Body:
Error:

/home/mike/Documents/PROJECTS/BUN/blib/bun/impl/DbBackend.hpp:61:21: error: expected primary-expression before ‘try’
                     try {
                     ^~~
/home/mike/Documents/PROJECTS/BUN/blib/bun/impl/DbBackend.hpp:67:21: error: expected ‘,’ or ‘;’ before ‘catch’
                     catch (std::exception const &except) {
                     ^~~~~
In file included from blib/bun/bun.hpp:3:0,
                 from main.cpp:12:

Part of code:

                bool connect(std::string const &in_params) {
                    const auto backend_factory =
#ifdef BUN_SQLITE
                    soci::sqlite3;
#elif defined(BUN_POSTGRES)
                    soci::postgresql;
#elif defined(BUN_MYSQL)
                    soci::mysql;
#endif
                    try {
                         if (!_ok) {
                                          _sql_session.open(backend_factory, in_params);
                                          _ok = true;
                                   }
                    }
                    catch (std::exception const &except) {
                                     l().error(except.what());
                        _ok = false;
                    }
                              return _ok;
                }

                soci::session &session() {
                    return _sql_session;
                }
            };

Makefile:

LDFLAGS := -L/usr/local/lib   \
-I/home/mike/Documents/PROJECTS/BUN/third_party/unqlite -I/home/mike/Documents/PROJECTS/BUN -I/home/mike/Documents/PROJECTS/BUN/third_party
# LDLIBS :=  -lpthread -lresolv
EXECUTABLE := main
# CXXFLAGS=-g -std=c++11 -Wall
CXXFLAGS=-g -std=c++17 -Wall

all: $(EXECUTABLE)

clean:
    rm -f $(EXECUTABLE) *.o

I am trying to use Bun orm. In my program I only included bun.hpp file. I can't understand what is not ok for compiler before try ? Maybe because of that #ifdef operators above the try ? Also it says it expected , or ; before catch...

I am trying on ubuntu 18.04

Body:
Your compile line doesn't define any of the options (unless they are coming from inside the file or another header) so you get:

bool connect(std::string const &in_params) {
                const auto backend_factory =
                try {

To confirm you can add a "-E" to the g++ line to get the source after the preprocessor.

Another possibility is that you are defining more than one.
You could always #undef 2 of them and #define the last one to see if it compiles that way (just as a test).


答:
API suggests that a number or a string is fine inside maxWidth or maxHeight...

But we can use ::ng-deep would help when putting this inside CSS... Note that the rendered .cdk-overlay-pane has an inline max-width of 80%, so we had to use 100% !important otherwise, we are able to do this via CSS

relevant CSS:

```<code>::ng-deep .cdk-overlay-pane { max-width: 100vw !important; max-height: 100vh; }
::ng-deep .cdk-overlay-pane .mat-dialog-container{
  background-color:lightgreen;
  max-width: 100vw;
  max-height: 100vh;
}
::ng-deep .cdk-overlay-pane .mat-dialog-container .mat-dialog-content { max-height: 100%; }
</code>```

working stackblitz here

Title: Angular 8: max-height attribute for a material dialog is not working

Body:
API suggests that a number or a string is fine inside maxWidth or maxHeight...

But we can use ::ng-deep would help when putting this inside CSS... Note that the rendered .cdk-overlay-pane has an inline max-width of 80%, so we had to use 100% !important otherwise, we are able to do this via CSS

relevant CSS:

::ng-deep .cdk-overlay-pane { max-width: 100vw !important; max-height: 100vh; }
::ng-deep .cdk-overlay-pane .mat-dialog-container{
  background-color:lightgreen;
  max-width: 100vw;
  max-height: 100vh;
}
::ng-deep .cdk-overlay-pane .mat-dialog-container .mat-dialog-content { max-height: 100%; }

working stackblitz here


问:
loop is increasing each time through select/inserts
I have a script that is pretty straight forward in theory, where I"m trying to select relational data on a development DB2 database, and insert into a separate production db2 server (creating new IDs and relationships on the production side in the process).

So in this script, I:

Select from the dev ITEM table

Store the original primary key

insert the data into the dev ITEM table

Get the ID of the newly inserted one

select SUBITEM from dev with the original ID

for each subitem I insert the data into the prod SUBITEM table with the newly created ITEM ID as the relationship

The problem is the script actually runs successfully, but as it goes, it simply increases by one so even though it inserts each ITEM correctly, it ends up just getting EVERY subitem in the database and storing the original (1st row's) ID. FOr instance:

My first ITEM select returns ID 1204. By the time I let it run for several items, my ITEM table shows records with IDs: 1204,1205,1206 and 1207

That's correct, but when I look at the subITEMS table, I have 10 subITEM records all with itemID of 1204. So it got the right subitem for each iteration of ITEMS but only ever inserted the very first newID variable.

What did I do wrong here:

```<code>if($DB2connDEV && $DB2connPROD){

    $getDevItems = "
                SELECT
                    itemt_ID,
                    DESCRIPTION
                FROM itemt
            ";

    $stmt = odbc_exec($DB2connDEV, $getDevItems);

    while($gettingDevItems = odbc_fetch_array($stmt)){
        $rows[] = $gettingDevItems;
    }

    foreach($rows as $row){
        $prepInsert = odbc_prepare($DB2connPROD, "INSERT INTO itemt (itemt_id, description) VALUES(?,?)");

        $originalID = $row['itemt_ID'];
        $description = $row['DESCRIPTION'];

        $insertTable = odbc_execute($prepInsert, array($description));

        //Get newly created ID
        $getIdentity = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";

        $stmt = odbc_exec($DB2connPROD, $getIdentity);
        $row = odbc_fetch_array($stmt);
        $newID = $row['LASTID'];

        if($newID) {
            echo "Last Insert ID is : " . $newID . "\n";
        } else {
            echo "No Last insert ID.\n";
        }

        //Get subItems and insert
        $getSubItems = "SELECT NAME, DESCRIPTION
                FROM SUBITEMT
                WHERE itemt_ID = $originalID";

        $selectSubItems = odbc_exec($DB2connDEV, $getSubItems);

        while($gettingSubItems = odbc_fetch_array($selectSubItems)){
            $subItemRows[] = $gettingSubItems;
        }

        foreach($subItemRows as $subItemRow){
            $subItemPrepInsert = odbc_prepare($DB2connPROD, "INSERT INTO subitemt (itemt_id, NAME, DESCRIPTION) VALUES(?,?,?)");
            $subItemName = $subItemRow['NAME'];
            $subItemDescription = $subItemRow['DESCRIPTION'];

            $subtaskInsertExec = odbc_execute($subtaskPrepInsert, array($newID, $subItemName, $subItemDescription));

            //get newly created ID for subitem
            $getsubtaskID = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";

            $subtaskIDSTMT = odbc_exec($DB2connPROD, $getsubtaskID);

            $newsubItemRow = odbc_fetch_array($subtaskIDSTMT);
            $newSubItemID = $newsubItemRow['LASTID'];

            if($newSubItemID) {
                echo "Last Insert subItem ID is : " . $newSubItemID . "\n";
            } else {
                echo "No Last insert subItem ID.\n";
            }
        }
    }

    odbc_close($DB2connPROD);
    odbc_close($DB2connDEV);
}
</code>```

答:
The problem is that you're not clearing out $subItemRows between iterations of the main loop. So each time you're adding the new subitems to the subitems from the previous iterations.

Put

```<code>$subItemRows = array();
</code>```

before the loop:

```<code>while($gettingSubItems = odbc_fetch_array($selectSubItems)){
    $subItemRows[] = $gettingSubItems;
}
</code>```

Body:
I have a script that is pretty straight forward in theory, where I"m trying to select relational data on a development DB2 database, and insert into a separate production db2 server (creating new IDs and relationships on the production side in the process).

So in this script, I:

Select from the dev ITEM table

Store the original primary key

insert the data into the dev ITEM table

Get the ID of the newly inserted one

select SUBITEM from dev with the original ID

for each subitem I insert the data into the prod SUBITEM table with the newly created ITEM ID as the relationship

The problem is the script actually runs successfully, but as it goes, it simply increases by one so even though it inserts each ITEM correctly, it ends up just getting EVERY subitem in the database and storing the original (1st row's) ID. FOr instance:

My first ITEM select returns ID 1204. By the time I let it run for several items, my ITEM table shows records with IDs: 1204,1205,1206 and 1207

That's correct, but when I look at the subITEMS table, I have 10 subITEM records all with itemID of 1204. So it got the right subitem for each iteration of ITEMS but only ever inserted the very first newID variable.

What did I do wrong here:

if($DB2connDEV && $DB2connPROD){

    $getDevItems = "
                SELECT
                    itemt_ID,
                    DESCRIPTION
                FROM itemt
            ";

    $stmt = odbc_exec($DB2connDEV, $getDevItems);

    while($gettingDevItems = odbc_fetch_array($stmt)){
        $rows[] = $gettingDevItems;
    }

    foreach($rows as $row){
        $prepInsert = odbc_prepare($DB2connPROD, "INSERT INTO itemt (itemt_id, description) VALUES(?,?)");

        $originalID = $row['itemt_ID'];
        $description = $row['DESCRIPTION'];

        $insertTable = odbc_execute($prepInsert, array($description));

        //Get newly created ID
        $getIdentity = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";

        $stmt = odbc_exec($DB2connPROD, $getIdentity);
        $row = odbc_fetch_array($stmt);
        $newID = $row['LASTID'];

        if($newID) {
            echo "Last Insert ID is : " . $newID . "\n";
        } else {
            echo "No Last insert ID.\n";
        }

        //Get subItems and insert
        $getSubItems = "SELECT NAME, DESCRIPTION
                FROM SUBITEMT
                WHERE itemt_ID = $originalID";

        $selectSubItems = odbc_exec($DB2connDEV, $getSubItems);

        while($gettingSubItems = odbc_fetch_array($selectSubItems)){
            $subItemRows[] = $gettingSubItems;
        }

        foreach($subItemRows as $subItemRow){
            $subItemPrepInsert = odbc_prepare($DB2connPROD, "INSERT INTO subitemt (itemt_id, NAME, DESCRIPTION) VALUES(?,?,?)");
            $subItemName = $subItemRow['NAME'];
            $subItemDescription = $subItemRow['DESCRIPTION'];

            $subtaskInsertExec = odbc_execute($subtaskPrepInsert, array($newID, $subItemName, $subItemDescription));

            //get newly created ID for subitem
            $getsubtaskID = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";

            $subtaskIDSTMT = odbc_exec($DB2connPROD, $getsubtaskID);

            $newsubItemRow = odbc_fetch_array($subtaskIDSTMT);
            $newSubItemID = $newsubItemRow['LASTID'];

            if($newSubItemID) {
                echo "Last Insert subItem ID is : " . $newSubItemID . "\n";
            } else {
                echo "No Last insert subItem ID.\n";
            }
        }
    }

    odbc_close($DB2connPROD);
    odbc_close($DB2connDEV);
}

Body:
The problem is that you're not clearing out $subItemRows between iterations of the main loop. So each time you're adding the new subitems to the subitems from the previous iterations.

Put

$subItemRows = array();

before the loop:

while($gettingSubItems = odbc_fetch_array($selectSubItems)){
    $subItemRows[] = $gettingSubItems;
}


问:
Not able to add "Privacy - Location Always and When in use usage description" in info.plist - Xcode 9 Beta
I am getting the following error while trying to ask permission from the user for location in Xcode 9 Beta. I tried adding "Privacy - Location When In Use Usage Description" and "Privacy - Location Usage Description" description in info.plist but still getting the same error.

This app has attempted to access privacy-sensitive data without a
  usage description. The app's Info.plist must contain both
  NSLocationAlwaysAndWhenInUseUsageDescription and
  NSLocationWhenInUseUsageDescription keys with string values explaining
  to the user how the app uses this data

When i try to add "Privacy - Location Always and When in use usage description" it is automatically getting renamed to "Privacy - Location Usage Description" in info.plist

答:
Just a heads up, it's not a typo as Hans suggested, it is correct. The format of the setting is confusing but conforms to something like

"[APIModule][Setting][KeyType]"

So the module the setting is for is the app's "NSLocation" calls, the setting is regarding the "Always and When in Use" setting for user location prefs, and the KeyType is a "Usage Description" therefore the resulting key is

NSLocationAlwaysAndWhenInUseUsageDescription

or separated into the composite terms:

NSLocation AlwaysAndWhenInUse UsageDescription


答: Try removing all #def macros and leave only one and check if it compiles, for example const auto backend_factory = soci::sqlite3; If it does compile that means you're not defining one of those 3 def you have in your code

Title: C++ compilation error: error: expected primary-expression before ‘try’


问:
r loop for filtering through each column
I have a data frame like this:
    gene expression data frame
Assuming column name as different samples and row name as different genes.
Now I want to know the number of genes left after I filter from each column with a number
For example,

```<code>sample1_more_than_5 <- df[(df[,1]>5),]
sample1_more_than_10 <- df[(df[,1]>10),]
sample1_more_than_20 <- df[(df[,1]>20),]
sample1_more_than_30 <- df[(df[,1]>30),]
</code>```

Then,

```<code>sample2_more_than_5 <- df[(df[,2]>5),]
sample2_more_than_10 <- df[(df[,2]>10),]
sample2_more_than_20 <- df[(df[,2]>20),]
sample2_more_than_30 <- df[(df[,2]>30),]
</code>```

But I don't want to repeat this 100 times as I have 100 samples.
Can anyone write a loop for me for this situation? Thank you

答:
Here is a solution using two loops that calculates, by each sample (columns), the number of genes (rows) that have a value greater than the one indicated in the nums vector.

```<code>#Create the vector with the numbers used to filter each columns
nums<-c(5, 10, 20, 30)

#Loop for each column
resul <- apply(df, 2, function(x){
  #Get the length of rows that have a higher value than each nums entry
  sapply(nums, function(y){
    length(x[x>y])
  })
})

#Transform the data into a data.frame and add the nums vector in the first column
resul<-data.frame(greaterthan = nums,
                  as.data.frame(resul))
</code>```

Body:
I have a data frame like this:
    gene expression data frame
Assuming column name as different samples and row name as different genes.
Now I want to know the number of genes left after I filter from each column with a number
For example,

sample1_more_than_5 <- df[(df[,1]>5),]
sample1_more_than_10 <- df[(df[,1]>10),]
sample1_more_than_20 <- df[(df[,1]>20),]
sample1_more_than_30 <- df[(df[,1]>30),]

Then,

sample2_more_than_5 <- df[(df[,2]>5),]
sample2_more_than_10 <- df[(df[,2]>10),]
sample2_more_than_20 <- df[(df[,2]>20),]
sample2_more_than_30 <- df[(df[,2]>30),]

But I don't want to repeat this 100 times as I have 100 samples.
Can anyone write a loop for me for this situation? Thank you

Body:
Here is a solution using two loops that calculates, by each sample (columns), the number of genes (rows) that have a value greater than the one indicated in the nums vector.

#Create the vector with the numbers used to filter each columns
nums<-c(5, 10, 20, 30)

#Loop for each column
resul <- apply(df, 2, function(x){
  #Get the length of rows that have a higher value than each nums entry
  sapply(nums, function(y){
    length(x[x>y])
  })
})

#Transform the data into a data.frame and add the nums vector in the first column
resul<-data.frame(greaterthan = nums,
                  as.data.frame(resul))


问:
Error importing tensorflow (just installed) python 3.7
I have python 3.7 installed on a Windows 10 machine, no custom stuff at all, to install tensorflow I used:

```<code>pip3 install --user --upgrade tensorflow
</code>```

but when I try importing it using:
import tensorflow
in a python script or shell it gives me the following error:

```<code>ImportError: DLL load failed: The specified module could not be found.
</code>```

Am I doing something wrong?

edit: By the way pip version is 20.0.2, I precedently tried with pip 10.x and got the same result.

答:
Regarding https://github.com/tensorflow/tensorflow/issues/35749 or https://github.com/tensorflow/tensorflow/issues/36859 (and the amount of same duplicate issues) there are some recents problems with tensorflow 2.1 for some windows computers.
A fix so far, is to use tensorflow 2.0 on windows :

```<code>pip install tensorflow==2.0
</code>```

For more details, this is quite detailed : https://github.com/tensorflow/tensorflow/issues/36167#issuecomment-577886156

Body:
I have python 3.7 installed on a Windows 10 machine, no custom stuff at all, to install tensorflow I used:

pip3 install --user --upgrade tensorflow

but when I try importing it using:
import tensorflow
in a python script or shell it gives me the following error:

ImportError: DLL load failed: The specified module could not be found.

Am I doing something wrong?

edit: By the way pip version is 20.0.2, I precedently tried with pip 10.x and got the same result.

Body:
Regarding https://github.com/tensorflow/tensorflow/issues/35749 or https://github.com/tensorflow/tensorflow/issues/36859 (and the amount of same duplicate issues) there are some recents problems with tensorflow 2.1 for some windows computers.
A fix so far, is to use tensorflow 2.0 on windows :

pip install tensorflow==2.0

For more details, this is quite detailed : https://github.com/tensorflow/tensorflow/issues/36167#issuecomment-577886156


问:
Schema version mismatch with 3.0.8 and 3.0.14
I am trying to upgrade the cassandra version from the 3.0.8 to 3.0.14. I am adding a new node with 3.0.14 version to 3.0.8. cluster and I see the schema disagreement between the nodes and the new node doesn't stream any data.

I am looking at : https://issues.apache.org/jira/browse/CASSANDRA-13559, does this mean, I will not be able to add nodes with the higher version than 3.0.13?

here is what I see in the nodetool describecluster output

```<code>$ nodetool describecluster
Cluster Information:
    Name: production
    Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
    Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
    Schema versions:
        45ad6427-30a8-3381-9e2c-266b446c6ea7: [192.168.1.2, 192.168.1.3, 192.168.1.4]

        c2a2bb4f-7d31-3fb8-a216-00b41a643650: [10.10.1.10]
</code>```

Any work around to mitigate this?

答:
This is a tad late but I ran into this previously too.

see https://github.com/apache/cassandra/blob/cassandra-3.0/NEWS.txt#L166 for release notes specific to 3.0.14.

you need a temporary flag: -Dcassandra.force_3_0_protocol_version=true on the 3.0.14 nodes to enable communication between these two versions. There is an gossip incompatibility that causes the schema not to be pulled during bootstrap. You should remove this flag after upgrading the entire cluster and do another rolling restart

I would guess that in the debug logs you would find a line like "shouldPullSchema returned false" due to this incompatibility.

Body:
I am trying to upgrade the cassandra version from the 3.0.8 to 3.0.14. I am adding a new node with 3.0.14 version to 3.0.8. cluster and I see the schema disagreement between the nodes and the new node doesn't stream any data.

I am looking at : https://issues.apache.org/jira/browse/CASSANDRA-13559, does this mean, I will not be able to add nodes with the higher version than 3.0.13?

here is what I see in the nodetool describecluster output

$ nodetool describecluster
Cluster Information:
    Name: production
    Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
    Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
    Schema versions:
        45ad6427-30a8-3381-9e2c-266b446c6ea7: [192.168.1.2, 192.168.1.3, 192.168.1.4]

        c2a2bb4f-7d31-3fb8-a216-00b41a643650: [10.10.1.10]

Any work around to mitigate this?


问:
What HTTP status code do you use when endpoint is disabled by feature-flag / feature-toggle?
I have been using 503 Service Unavailable or down for maintenance.

However some http client libraries i.e. axios treat 503 as retriable error.

It makes sense to retry it if the response is produced due to high load but 503 also fits the feature-toggle case.

Any suggestion on other codes people use ?

答:
Status codes are meta data that belong to the "transferring documents over a network" domain.  Shared semantics of the status codes is what allows general-purpose HTTP aware components to act intelligently.

So what you should be doing is thinking about the HTTP semantics.

For example, if your server doesn't have access to a current representation of the resource identified by the target-uri of the request, then you should be issuing a 404 Not Found response.  If the request is forbidden, then 403 Forbidden.  Or 451 Unavailable for Legal Reasons when that is the intended meaning.

In other words: it depends.

But what it doesn't depend on is "feature flag"; that's an implementation detail.  The "uniform interface" is a facade that hides those sorts of technical details that vary from one implementation to another.  From the outside, your API provides the illusion that your machine is just another boring web server.


问:
generating licenses.licx
I've got a bit of a problem. I'm moving my source repository from one machine to another, and in the process I'm doing some culling of what's stored as I've learned more about creating/managing a repository since I started.

The problem is that we're using dxperience tools from devexpress and it uses the .net license system (licenses.licx). Originally I had this license in the repository, and I'm hearing that this isn't necessarily the best idea. So I haven't included it in the repository. But now, when I checkout the project from the repository on my machine (same machine that I was checking out to before the move), it's looking for the license file and not generating it as (I think) it should be.

答:
We have run into the same problem using Infragistics controls.

Our solution has been to keep a blank licnenses.licx file in our source repository (Source Gear Vault) and then change the properties of the file to Read Only false on our local workations.  This way we do not end up stepping on each other with that file and it is generated with the proper keys off of our workstations.

Of course this is a bit of a manual work around that may not be suitable for you, but that is how we have been doing it.

OwnerDisplayName: SnOrfus

ContentLicense: CC BY-SA 2.5

Title: generating licenses.licx

OwnerDisplayName: Bryan Sebastian


问:
How to stop IOS app from responding to HTML Refresh in UIWebView
In my app I load a site that uses ad banners and HTML refresh tags.

Every minute (or however long the refresh HTML tag is set) the app goes out to the network to reloads the iframe banner ad on the website (even if it is hidden)

Is there a way to get webView to ignore these?

I tried stoploading and other things in webViewDidFinishLoading, but it still is responding to the HTML refreshes.

Any tips or ideas?

答:
Could it be that there is javascript on the webpage involved, and that is loading the data? You could try patching the javascript code accordingly, right after having loaded the page (there's a method to execute your own javascript in a loaded page, I think, and so you could inject your own js code that modified the loaded page, maybe disable the banner code or remove its entire div segment).

And isn't there another delegate function that gets called when the page follows a link or loads extra pictures etc? Not sure, been a long time I've touched the webView. Maybe you have to filter the banner picture loading there.

In fact, look at UIWebViewDelegate - there's webView:shouldStartLoadWithRequest:navigationType:
Have you implemented that to see if you can filter the banner loading there?


问:
how to authenticate mongoose connection mongodb in node.js
I have created mongodb user with command

```<code>use admin
db.createUser(
    {
      user: "superuser",
      pwd: "12345678",
      roles: [ "root" ]
    }
)
</code>```

then in my app I am trying to connect mongoose like this

```<code>var options = {
user: "superuser",
pass: "12345678"
};

var mongooseConnectionString = 'mongodb://localhost/twitter-mongo';

mongoose.connect(mongooseConnectionString,options);
mongoose.model('User', UserSchema);

var User = mongoose.model('User');
</code>```

I am getting this error when inserting data through mongoose

```<code>MongoError: not authorized for insert on twitter-mongo.users
</code>```

please tell me what is wrong in my code

答:
```<code>mongoose.createConnection('mongodb://username:password@35.238.xxx.xxx:27017/dashboards?authSource=admin', {
   useNewUrlParser: true
}, (e) => {

    if (e) throw console.error('Error connecting to mongo database master');
    console.log('Connected to mongo database master.');

});
</code>```

Body:
I have created mongodb user with command

use admin
db.createUser(
    {
      user: "superuser",
      pwd: "12345678",
      roles: [ "root" ]
    }
)

then in my app I am trying to connect mongoose like this

var options = {
user: "superuser",
pass: "12345678"
};

var mongooseConnectionString = 'mongodb://localhost/twitter-mongo';

mongoose.connect(mongooseConnectionString,options);
mongoose.model('User', UserSchema);

var User = mongoose.model('User');

I am getting this error when inserting data through mongoose

MongoError: not authorized for insert on twitter-mongo.users

please tell me what is wrong in my code


问:
Google Map style - can't produce a dark style that shows buildings
On mapstyle.withgoogle.com I can choose several themes. Standard shows building structure just nicely for my purpose. I can change its colors and everything works fine. But I need it dark.

If I choose a dark theme, there are no building structures to be seen, no matter what I do. (Well it shows some geometry, but not as much as the standard theme). I tried all kinds of features and settings. (Why is that?)

So, back to the standard theme, making it dark also has its limitations. No matter what I try, country areas won't get dark.

It appears that you have to start from a base theme that comes with a predefined set of parameters that cannot be changed. However, when I check the resulting JSON, there is no mention of that. So I guess I must be wrong.

Then I tried to manually merge this standard theme with the dark one, but the result just isn't satisfying. And it's funny, because I "merge" with an empty array []

Basically I want a map that looks like this. (Well, that's "snazzy maps", I hope I don't have to switch to another maps provider and so on. Btw, I'm developing on android.)

Here is my style.json (looks like a waste without buildings):

```<code>[
  {
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#212121"
      }
    ]
  },
  {
    "elementType": "labels",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "elementType": "labels.icon",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "administrative",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#002eea"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [
      {
        "color": "#002eea"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "administrative.neighborhood",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#002eea"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "landscape.man_made",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#002eea"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "landscape.man_made",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#181818"
      }
    ]
  },
  {
    "featureType": "road",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "road.arterial",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "road.highway.controlled_access",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "road.local",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      }
    ]
  }
]
</code>```

Please, somebody tell me I'm just tired and should try from scratch tomorrow, selectively testing every single entry of my style.

答: Once you edit the theme from the original, there is no way to get the map to render buildings/structures. </p>

Body:
On mapstyle.withgoogle.com I can choose several themes. Standard shows building structure just nicely for my purpose. I can change its colors and everything works fine. But I need it dark.

If I choose a dark theme, there are no building structures to be seen, no matter what I do. (Well it shows some geometry, but not as much as the standard theme). I tried all kinds of features and settings. (Why is that?)

So, back to the standard theme, making it dark also has its limitations. No matter what I try, country areas won't get dark.

It appears that you have to start from a base theme that comes with a predefined set of parameters that cannot be changed. However, when I check the resulting JSON, there is no mention of that. So I guess I must be wrong.

Then I tried to manually merge this standard theme with the dark one, but the result just isn't satisfying. And it's funny, because I "merge" with an empty array []

Basically I want a map that looks like this. (Well, that's "snazzy maps", I hope I don't have to switch to another maps provider and so on. Btw, I'm developing on android.)

Here is my style.json (looks like a waste without buildings):

[
  {
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#212121"
      }
    ]
  },
  {
    "elementType": "labels",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "elementType": "labels.icon",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "administrative",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#002eea"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [
      {
        "color": "#002eea"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "administrative.neighborhood",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#002eea"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "landscape.man_made",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#002eea"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "landscape.man_made",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#181818"
      }
    ]
  },
  {
    "featureType": "road",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "road.arterial",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "road.highway.controlled_access",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "road.local",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      },
      {
        "visibility": "on"
      }
    ]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#000000"
      }
    ]
  }
]

Please, somebody tell me I'm just tired and should try from scratch tomorrow, selectively testing every single entry of my style.


问:
Create new column that takes the sum of another column values and group by condition in R
I would like to add a new column that is titled "pop sum" which takes the sum of all rows that has population data and is grouped by location. I tried group_by with Building and then sum = sum(pop) but that did work. I will just show one building but there are 30+ UNIQUE buildings Reference dataframe below:

```<code>`Date Ran`           Year Month      Building   Population MonthN
  <dttm>              <dbl> <chr>        <fct>       <num>    <chr>
1 2018-09-28 00:00:00  2018 September     ALEX       1196    Sep
2 2018-08-30 00:00:00  2018 August        ALEX       1172    Aug
3 2018-07-19 00:00:00  2018 July          ALEX       1171    Jul
4 2018-06-30 00:00:00  2018 June          ALEX       1167    Jun
5 2018-05-11 00:00:00  2018 May           ALEX       1154    May
6 2018-04-09 00:00:00  2018 April         ALEX       1154    Apr
</code>```

Desired output would like something like this:

```<code>`Date Ran`           Year Month      Building   Population   MonthN  Pop Sum
  <dttm>              <dbl> <chr>         <fct>      <dbl>     <chr>      <num>
1 2018-09-28 00:00:00  2018 September     ALEX       1196       Sep        7014
2 2018-08-30 00:00:00  2018 August        ALEX       1172       Aug        7014
3 2018-07-19 00:00:00  2018 July          ALEX       1171       Jul        7014
4 2018-06-30 00:00:00  2018 June          ALEX       1167       Jun        7014
5 2018-05-11 00:00:00  2018 May           ALEX       1154       May        7014
6 2018-04-09 00:00:00  2018 April         ALEX       1154       Apr        7014
</code>```

A function or for loop would be great but if there are any R packages I could load in to generate new column that would be great

答:
Here is a base R solution using ave, maybe you can have a try with it

```<code>df <- within(df,PopSum <- ave(Population,Building,FUN = sum))
</code>```

Body:
I would like to add a new column that is titled "pop sum" which takes the sum of all rows that has population data and is grouped by location. I tried group_by with Building and then sum = sum(pop) but that did work. I will just show one building but there are 30+ UNIQUE buildings Reference dataframe below:

`Date Ran`           Year Month      Building   Population MonthN
  <dttm>              <dbl> <chr>        <fct>       <num>    <chr>
1 2018-09-28 00:00:00  2018 September     ALEX       1196    Sep
2 2018-08-30 00:00:00  2018 August        ALEX       1172    Aug
3 2018-07-19 00:00:00  2018 July          ALEX       1171    Jul
4 2018-06-30 00:00:00  2018 June          ALEX       1167    Jun
5 2018-05-11 00:00:00  2018 May           ALEX       1154    May
6 2018-04-09 00:00:00  2018 April         ALEX       1154    Apr

Desired output would like something like this:

`Date Ran`           Year Month      Building   Population   MonthN  Pop Sum
  <dttm>              <dbl> <chr>         <fct>      <dbl>     <chr>      <num>
1 2018-09-28 00:00:00  2018 September     ALEX       1196       Sep        7014
2 2018-08-30 00:00:00  2018 August        ALEX       1172       Aug        7014
3 2018-07-19 00:00:00  2018 July          ALEX       1171       Jul        7014
4 2018-06-30 00:00:00  2018 June          ALEX       1167       Jun        7014
5 2018-05-11 00:00:00  2018 May           ALEX       1154       May        7014
6 2018-04-09 00:00:00  2018 April         ALEX       1154       Apr        7014

A function or for loop would be great but if there are any R packages I could load in to generate new column that would be great

Body:
Here is a base R solution using ave, maybe you can have a try with it

df <- within(df,PopSum <- ave(Population,Building,FUN = sum))


问:
Blazor: How to change the URL dynamically?
I have a page which takes a string bookingReference as its route parameter Booking/{bookingReference}.

This page is the parent component, with a child component inside where booking details are managed. The child component calls back to the parent when booking details are updated.

```<code>@page "/Booking/{bookingReference}"

<div class="header">
   <h1> @Booking.BookingReference </h1>
</div>

<div>
   <BookingDetails Booking="Booking" OnUpdateBooking="UpdateBooking" />
</div>

@code {

    [Parameter]
    public string BookingReference { get; set; }

    private Booking Booking { get; set; }

    void UpdateBooking(Booking booking)
    {
        Booking = booking;
        StateHasChanged();
    }
}
</code>```

The BookingDetails component looks like this:

```<code><EditForm Model="FormState" OnValidSubmit="@saveChanges">
   //inputs etc.
</EditForm>

@code {
    [Parameter]
    public Booking Booking { get; set; }

    [Parameter]
    public EventCallback<Booking> OnUpdateBooking { get; set; }

private async Task saveChanges()
{
        // update booking object
        Booking.BookingReference = FormState.BookingReference;

        try
        {
            Booking = await BookingService.UpdateBooking(Booking);
            await OnUpdateBooking.InvokeAsync(Booking);
            Toaster.Success("Booking updated successfully");
        }
        catch
        {
            Toaster.Error("Failed to update booking");
        }
    }
}
</code>```

The user can update the booking reference from the child component, and thus, change the header of the page - that works fine, all good.

However, I would also like to change the URL to the updated bookingReference - is there any way I can achieve this without forcing a refresh?

答:
Ok, right now the only way to change the value of the BookingReference in the url is to navigate to the current url with the new BookingReference.
Note that this action is not reloading or refreshing the page component. It is rather a re-rendering action. The OnInitialized life cycle is executed only once, which indicates that the components are not destroyed and then re-created. They are only re-rendered. This is the way to go.</p>

```<code>@code {

[Parameter]
public string BookingReference { get; set; }

private Booking Booking { get; set; }

void UpdateBooking(Booking booking)
{
    Booking = booking;
    NavigationManager.NavigateTo($"/{Booking.BookingReference}");

}
}
</code>```

Body:
I have a page which takes a string bookingReference as its route parameter Booking/{bookingReference}.

This page is the parent component, with a child component inside where booking details are managed. The child component calls back to the parent when booking details are updated.

@page "/Booking/{bookingReference}"

 @Booking.BookingReference

   <BookingDetails Booking="Booking" OnUpdateBooking="UpdateBooking" />

@code {

    [Parameter]
    public string BookingReference { get; set; }

    private Booking Booking { get; set; }

    void UpdateBooking(Booking booking)
    {
        Booking = booking;
        StateHasChanged();
    }
}

The BookingDetails component looks like this:

<EditForm Model="FormState" OnValidSubmit="@saveChanges">
   //inputs etc.
</EditForm>

@code {
    [Parameter]
    public Booking Booking { get; set; }

    [Parameter]
    public EventCallback<Booking> OnUpdateBooking { get; set; }

private async Task saveChanges()
{
        // update booking object
        Booking.BookingReference = FormState.BookingReference;

        try
        {
            Booking = await BookingService.UpdateBooking(Booking);
            await OnUpdateBooking.InvokeAsync(Booking);
            Toaster.Success("Booking updated successfully");
        }
        catch
        {
            Toaster.Error("Failed to update booking");
        }
    }
}

The user can update the booking reference from the child component, and thus, change the header of the page - that works fine, all good.

However, I would also like to change the URL to the updated bookingReference - is there any way I can achieve this without forcing a refresh?

Body:
Ok, right now the only way to change the value of the BookingReference in the url is to navigate to the current url with the new BookingReference.
Note that this action is not reloading or refreshing the page component. It is rather a re-rendering action. The OnInitialized life cycle is executed only once, which indicates that the components are not destroyed and then re-created. They are only re-rendered. This is the way to go.

@code {

[Parameter]
public string BookingReference { get; set; }

private Booking Booking { get; set; }

void UpdateBooking(Booking booking)
{
    Booking = booking;
    NavigationManager.NavigateTo($"/{Booking.BookingReference}");

}
}


问:
How to update / delete in snowflake from the AWS Glue script
I want to delete a record in a dataframe object in snowflake table .

Similarly I want to perform update on basis of "key" in dataframe in snowflake table.

My research indicates that the utils method can perform the DDL operation but i am unable to find the some example to refer to.

答:
As you mentioned, you can use the runQuery() method of the Utils object to execute DDL/DML SQL statements:

https://docs.snowflake.net/manuals/user-guide/spark-connector-use.html#executing-ddl-dml-sql-statements

If you want to do it based on some keys, then you can iterate items on DataFrame, and run an SQL for each item:

how to loop through each row of dataFrame in pyspark

But this will be a performance killer. Snowflake is a data warehouse, so you should always prefer "batch updates" instead of single row updates.

I would suggest you to write your dataframe to a staging table in Snowflake, and then call a SQL to update the rows in target table based on the staging table.


问:
How to Display list from Firestore in an item builder
The getIngredients() method below returns a list from firestore.

```<code>Future getIngredients() async {
    return Firestore.instance
        .collection('ingredients')
        .where("name", isEqualTo: widget.dish_name.toString().toLowerCase()).getDocuments();
  }
</code>```

Now I want to display this list in an item builder below:

```<code> new ListView.builder(
                  itemExtent: 90,
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                      return SingleIngredient(
                        ingredient_name: snapshot.data[index].ingredients,
                      );
                  });
</code>```

I get the following error message:

_FutureBuilderState#7cbda): I/flutter (12164): Class 'QuerySnapshot' has no instance getter 'length'. I/flutter (12164):
  Receiver: Instance of 'QuerySnapshot' I/flutter (12164): Tried
  calling: length

Here's the scturcture of my firestore. I am fetching the ingredients list:

UPDATE
I have updated the code but I am only getting the first item from the list of ingredients (i.e, Onions). I want the itembuilder to build each item in the list because I am trying to display an image and the the ingredient list. That's what the SingleIngredient widget is doing. So, how can I loop through each list one by one?

```<code> Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
          future: getIngredients(),
          builder: (context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot user = snapshot.data.documents[index];

                  return SingleIngredient(
                    // Access the fields as defined in FireStore
                    ingredient_name: user.data['ingredients'][index].toString(),
                  );
                },
              );
            } else if (snapshot.connectionState == ConnectionState.done &&
                !snapshot.hasData) {
              // Handle no data
              return Center(
                child: Text("No users found."),
              );
            } else {
              // Still loading
              return CircularProgressIndicator();
            }
          }),
    );
  }
}
</code>```

答:
```<code>body: StreamBuilder(
stream: Firestore.instance
    .collection('ups')
.where('pc',
isEqualTo: widget.post.data["pc"])
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text("Loading..."),
);
} else {
final ups = snapshot.data.documents;
List<String> stateWidget = [];
for (var message in ups) {
final stateText = message.data['state'];
// final stateCollection = Text('$stateText');
stateWidget.add(stateText);
}enter code here
return  ListView(
children: stateWidget
    .map((data) => ListTile(`enter code here`
title: Text(data),
onTap: () => {_selectedItem(data)}))
    .toList(),`enter code here`
)
</code>```

Body:
The getIngredients() method below returns a list from firestore.

Future getIngredients() async {
    return Firestore.instance
        .collection('ingredients')
        .where("name", isEqualTo: widget.dish_name.toString().toLowerCase()).getDocuments();
  }

Now I want to display this list in an item builder below:

 new ListView.builder(
                  itemExtent: 90,
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                      return SingleIngredient(
                        ingredient_name: snapshot.data[index].ingredients,
                      );
                  });

I get the following error message:

_FutureBuilderState#7cbda): I/flutter (12164): Class 'QuerySnapshot' has no instance getter 'length'. I/flutter (12164):
  Receiver: Instance of 'QuerySnapshot' I/flutter (12164): Tried
  calling: length

Here's the scturcture of my firestore. I am fetching the ingredients list:

UPDATE
I have updated the code but I am only getting the first item from the list of ingredients (i.e, Onions). I want the itembuilder to build each item in the list because I am trying to display an image and the the ingredient list. That's what the SingleIngredient widget is doing. So, how can I loop through each list one by one?

 Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
          future: getIngredients(),
          builder: (context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot user = snapshot.data.documents[index];

                  return SingleIngredient(
                    // Access the fields as defined in FireStore
                    ingredient_name: user.data['ingredients'][index].toString(),
                  );
                },
              );
            } else if (snapshot.connectionState == ConnectionState.done &&
                !snapshot.hasData) {
              // Handle no data
              return Center(
                child: Text("No users found."),
              );
            } else {
              // Still loading
              return CircularProgressIndicator();
            }
          }),
    );
  }
}