问:
I want to get unixtime in Datepicker
I am using react, typescript.

Datepicker uses react-dates.

I want to select unix time when I select a date.

If anyone is familiar with react-dates, please let me know.

enter link description here

```<code>import { DayPickerRangeController } from "react-dates";
import React, { useState } from "react";
import moment from "moment";

import "moment/locale/ja";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

export default function App() {
  const dateFormat = "YYYY/MM/DD";
  const [startDate, setStartDate] = useState<moment.Moment | null>(null);
  const [endDate, setEndDate] = useState<moment.Moment | null>(null);
  const [focusedInput, setFocusedInput] = useState<"startDate" | "endDate">(
    "startDate"
  );

  console.log(startDate);
  return (
    <DayPickerRangeController
      startDate={startDate}
      endDate={endDate}
      focusedInput={focusedInput}
      numberOfMonths={2}
      onFocusChange={(focusedInput) => {
        setFocusedInput(!focusedInput ? "startDate" : focusedInput);
      }}
      onDatesChange={(selectedDates) => {
        if (focusedInput === "startDate") {
          setStartDate(selectedDates.startDate);
        } else {
          setEndDate(selectedDates.endDate);
        }
      }}
    />
  );
}

</code>```

答:
```<code>  console.log(new Date(startDate).getTime() / 1000);
</code>```

Title: I want to get unixtime in Datepicker

Body:
I am using react, typescript.

Datepicker uses react-dates.

I want to select unix time when I select a date.

If anyone is familiar with react-dates, please let me know.

enter link description here

import { DayPickerRangeController } from "react-dates";
import React, { useState } from "react";
import moment from "moment";

import "moment/locale/ja";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

export default function App() {
  const dateFormat = "YYYY/MM/DD";
  const [startDate, setStartDate] = useState<moment.Moment | null>(null);
  const [endDate, setEndDate] = useState<moment.Moment | null>(null);
  const [focusedInput, setFocusedInput] = useState<"startDate" | "endDate">(
    "startDate"
  );

  console.log(startDate);
  return (
    <DayPickerRangeController
      startDate={startDate}
      endDate={endDate}
      focusedInput={focusedInput}
      numberOfMonths={2}
      onFocusChange={(focusedInput) => {
        setFocusedInput(!focusedInput ? "startDate" : focusedInput);
      }}
      onDatesChange={(selectedDates) => {
        if (focusedInput === "startDate") {
          setStartDate(selectedDates.startDate);
        } else {
          setEndDate(selectedDates.endDate);
        }
      }}
    />
  );
}


来源: stackexchange

问:
LWUIT 1.5 Table - horizontal spanning layout
I am wondering if this is a bug or just my faulty code. I've been trying to render table with some horizontal spanning. This is how it should look like:

In LWUIT 1.4 everything worked correctly. Since 1.5 the table looks like:

My implementation:

```<code>DefaultTableModel model = new DefaultTableModel(new String[]{"", "", "", ""}, new String[][]{
                {"Header", null, null, null},
                {"1", "2", "3", "4"},
                {"1", "2", "3", "4"},
                {"String", null, "String", null}});

Table tab = new Table(model, false) {

        protected Component createCell(Object value, final int row, final int column, boolean editable) {
            Component c = super.createCell(value, row, column, editable);
            c.setFocusable(false);
            return c;
        }

        protected TableLayout.Constraint createCellConstraint(java.lang.Object value, int row, int column) {
            TableLayout.Constraint tlay = super.createCellConstraint(value, row, column);
            if (row == 0 && column == 0) {
                tlay.setHorizontalSpan(4);
                tlay.setHorizontalAlign(Table.CENTER);
            } else if (row == 3)) {
                if (column == 0) {
                    tlay.setHorizontalSpan(2);
                    tlay.setWidthPercentage(50);
                } else if (column == 2) {
                    tlay.setHorizontalSpan(2);
                    tlay.setWidthPercentage(50);
                }
            } else if (row != 0) {
                tlay.setWidthPercentage(25);
            }
            return tlay;
        }

    };
</code>```

答:
The bug (in LWUIT) is triggered by the tlay.setWidthPercentage(50); which you can remove and still get the expected result. It seems the width percentage value doesn't take spanning into consideration which I'm guessing it should.

You should file a bug for this in the issue tracker, thanks for the bug.

ContentLicense: CC BY-SA 3.0

Body:
I am wondering if this is a bug or just my faulty code. I've been trying to render table with some horizontal spanning. This is how it should look like:

In LWUIT 1.4 everything worked correctly. Since 1.5 the table looks like:

My implementation:

DefaultTableModel model = new DefaultTableModel(new String[]{"", "", "", ""}, new String[][]{
                {"Header", null, null, null},
                {"1", "2", "3", "4"},
                {"1", "2", "3", "4"},
                {"String", null, "String", null}});

Table tab = new Table(model, false) {

        protected Component createCell(Object value, final int row, final int column, boolean editable) {
            Component c = super.createCell(value, row, column, editable);
            c.setFocusable(false);
            return c;
        }

        protected TableLayout.Constraint createCellConstraint(java.lang.Object value, int row, int column) {
            TableLayout.Constraint tlay = super.createCellConstraint(value, row, column);
            if (row == 0 && column == 0) {
                tlay.setHorizontalSpan(4);
                tlay.setHorizontalAlign(Table.CENTER);
            } else if (row == 3)) {
                if (column == 0) {
                    tlay.setHorizontalSpan(2);
                    tlay.setWidthPercentage(50);
                } else if (column == 2) {
                    tlay.setHorizontalSpan(2);
                    tlay.setWidthPercentage(50);
                }
            } else if (row != 0) {
                tlay.setWidthPercentage(25);
            }
            return tlay;
        }

    };


问:
I'm learning Python and want to remove data from a CSV file
The CSV file I'm trying to change has 2 columns

```<code>Part Number.    Qty
h36fsde (1)      6
gr3jgr  (1)      2
qmdd12  (2)      9
</code>```

It is basically a list of part numbers in the first column followed by quantities in the second column. I need to remove the (number in brackets) in column one as above (1) (1) (2) because this relates to page numbers and it causes a problem when I try to import it.

Ideally my list should be:

```<code>Part Number.    Qty
h36fsde          6
gr3jgr           2
qmdd12           9
</code>```

So far the code I have allows me to choose the file I wish to change with Tkinter, then I'm trying to replace "(1)" with " " and then create a new directory if it doesn't exist called quotations and write the csv to that directory. So far it loads the file okay and writes a file new5.csv to the quotations folder, however it does not replace the "(1)" with a " " so please can someone let me know what I am doing wrong? I either need to simply remove the bracketed numbers all together or replace them with a " "

Please see my code so far below. I will try to tidy it up with def functions, however I'd like to get it working first and then see how I can improve it and make it more modular.

```<code>import tkinter as tk
from tkinter.filedialog import askopenfilename
import pandas as pd
import os
from pathlib import Path

root = tk.Tk()
root.withdraw() #Prevents the Tkinter window to come up
csvpath = askopenfilename()
root.destroy()

df = pd.read_csv(csvpath)
df.replace('(1)', ' ', inplace=True)

filepath = Path('quotations/new5.csv')
filepath.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(filepath)
</code>```

Once I have it working I will need to set it to remove (numbers in brackets) from (1) to (20). Plus is there an easy way for me to write the edited file straight back over the top of the file that was opened rather than keep saving the edited file as "New5.csv" and then renaming it in explorer?

答:
df.replace finds and replaces whole cells, not text within them, unless the string to find is given as a regular expression:

```<code>df.replace(r" \(1\)", "", regex=True, inplace=True)
</code>```

Alternatively, use Series.str.replace instead.

```<code>df["Part Number."] = df["Part Number."].str.replace('(1)', '')
</code>```

To replace all the bracketed numbers in one go, use a more general regex:

```<code>df["Part Number."] = df["Part Number."].str.replace(r" \(\d\d?\)", '', regex=True)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The CSV file I'm trying to change has 2 columns

Part Number.    Qty
h36fsde (1)      6
gr3jgr  (1)      2
qmdd12  (2)      9

It is basically a list of part numbers in the first column followed by quantities in the second column. I need to remove the (number in brackets) in column one as above (1) (1) (2) because this relates to page numbers and it causes a problem when I try to import it.

Ideally my list should be:

Part Number.    Qty
h36fsde          6
gr3jgr           2
qmdd12           9

So far the code I have allows me to choose the file I wish to change with Tkinter, then I'm trying to replace "(1)" with " " and then create a new directory if it doesn't exist called quotations and write the csv to that directory. So far it loads the file okay and writes a file new5.csv to the quotations folder, however it does not replace the "(1)" with a " " so please can someone let me know what I am doing wrong? I either need to simply remove the bracketed numbers all together or replace them with a " "

Please see my code so far below. I will try to tidy it up with def functions, however I'd like to get it working first and then see how I can improve it and make it more modular.

import tkinter as tk
from tkinter.filedialog import askopenfilename
import pandas as pd
import os
from pathlib import Path

root = tk.Tk()
root.withdraw() #Prevents the Tkinter window to come up
csvpath = askopenfilename()
root.destroy()

df = pd.read_csv(csvpath)
df.replace('(1)', ' ', inplace=True)

filepath = Path('quotations/new5.csv')
filepath.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(filepath)

Once I have it working I will need to set it to remove (numbers in brackets) from (1) to (20). Plus is there an easy way for me to write the edited file straight back over the top of the file that was opened rather than keep saving the edited file as "New5.csv" and then renaming it in explorer?

Body:
df.replace finds and replaces whole cells, not text within them, unless the string to find is given as a regular expression:

df.replace(r" \(1\)", "", regex=True, inplace=True)

Alternatively, use Series.str.replace instead.

df["Part Number."] = df["Part Number."].str.replace('(1)', '')

To replace all the bracketed numbers in one go, use a more general regex:

df["Part Number."] = df["Part Number."].str.replace(r" \(\d\d?\)", '', regex=True)


问:
Question mark in URL is removed with Express Route Parameters. How can I get a post by title with a question mark? (Node.js/Express/MongoDB)
I tried to find and retrieve a post by a title but it failed and when I console log requestedTitle = req.params.postTitle it shows the ? is removed from http://localhost:1035/posts/Is%20Google%20Analytics%20is%20illegal? to just "Is Google Analytics is illegal" which fails to find the article with the title "Is Google Analytics is illegal?" with a ?.

```<code>  app.get('/posts/:postTitle', function (req, res) {
      //single blog post
      // const postId = req.params.postId
      const requestedTitle = req.params.postTitle
      Post.findOne({title: requestedTitle}, function (err, post) {
        console.log(requestedTitle);
        if (post) {res.render('post', {
          singleTitle: post.title,
          singleContent: post.content,
          singleAuthor: post.author,
          uploadedImg: post.img,
          postCreated: post.created_at
      })} else {
        res.send(`No "${requestedTitle}" article was found.`)
      }
</code>```

答:
A question mark is interpreted by Express (and per the http spec) as the delimiter for the URL query string.  As such, Express has already parsed out the query string and does not match that against your route.  The parsed query string will be in req.query.

So, if you send a request for a URL such as:

```<code>http://localhost:1035/posts/Is%20Google%20Analytics%20is%20illegal?
</code>```

Then, the ? will be seen as the delimiter for the query string and your postTitle will just be Is Google Analytics is illegal.

If you want a question mark to be part of what you get in postTitle, then the client will have to properly encode the postTitle using encodeURIComponent() before constructing the URL.  That would "hide" the ? from Express (it would be encoded as %3F and it would then be left in the decoded value of postTitle as a ?.

FYI, there are many other characters which are also reserved so ANY end-user content you're trying to put into the URL piece that you want to be postTitle MUST be encoded with encodeURIComponent() when constructing the URL.  Note, you don't call encodeURIComponent() on the entire URL, just on the piece of user data that becomes the postTitle.  Express will then handle the decoding for you.

Body:
I tried to find and retrieve a post by a title but it failed and when I console log requestedTitle = req.params.postTitle it shows the ? is removed from http://localhost:1035/posts/Is%20Google%20Analytics%20is%20illegal? to just "Is Google Analytics is illegal" which fails to find the article with the title "Is Google Analytics is illegal?" with a ?.

  app.get('/posts/:postTitle', function (req, res) {
      //single blog post
      // const postId = req.params.postId
      const requestedTitle = req.params.postTitle
      Post.findOne({title: requestedTitle}, function (err, post) {
        console.log(requestedTitle);
        if (post) {res.render('post', {
          singleTitle: post.title,
          singleContent: post.content,
          singleAuthor: post.author,
          uploadedImg: post.img,
          postCreated: post.created_at
      })} else {
        res.send(`No "${requestedTitle}" article was found.`)
      }

Body:
A question mark is interpreted by Express (and per the http spec) as the delimiter for the URL query string.  As such, Express has already parsed out the query string and does not match that against your route.  The parsed query string will be in req.query.

So, if you send a request for a URL such as:

http://localhost:1035/posts/Is%20Google%20Analytics%20is%20illegal?

Then, the ? will be seen as the delimiter for the query string and your postTitle will just be Is Google Analytics is illegal.

If you want a question mark to be part of what you get in postTitle, then the client will have to properly encode the postTitle using encodeURIComponent() before constructing the URL.  That would "hide" the ? from Express (it would be encoded as %3F and it would then be left in the decoded value of postTitle as a ?.

FYI, there are many other characters which are also reserved so ANY end-user content you're trying to put into the URL piece that you want to be postTitle MUST be encoded with encodeURIComponent() when constructing the URL.  Note, you don't call encodeURIComponent() on the entire URL, just on the piece of user data that becomes the postTitle.  Express will then handle the decoding for you.


问:
Child processes are sharing the same variable in memory which is created after fork() is called (C)
I am working on a script where fork() is called in a for loop to create many children, these children do a random number of loops and then print the name of the child

I'm having some odd behavior where the memory address that i is at is shared for all of the child processes even though the variable is created after the fork()

Is this the intended behavior? And if so is there any way for these variables to be stored at different memory indexes as I do not want another child process affecting another

Here is some example output from the print that is commented out in the childCall function

```<code>In child 1 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
Child 2
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
Child 3
In child 1 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
Child 4
In child 5 i is located at 0xbef49508
Child 1
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
Child 5
</code>```

Below is the for loop in the parent function that creates the child processes and below that is the childCall function

Thank you!

```<code>for(int i = 0; i<children; i++)
    {
        if(fork() == 0) //If I am the child
        {
            childCall(i + 1);
            return 0;
        }
    }
</code>```

The childCall function is as follows

```<code>void childCall(int children)
{
    for(int i = 0; i<children; i++)
    {
        //printf("In child %d i is located at %p\n", children, &i);
        int newrand = rand() % 2; //This implementation is because when I was declaring a random value before the loop all of the children shared the same random value, due to pseudorandomness!
        //printf("%d is the random number\n", newrand);
        i -= newrand;
    }
    printf("Child %d\n", children);
}
</code>```

答: Every child created by fork gets its own independent virtual memory space.  So while the variables are at the same address within each process's virtual memory, the fact that they are separate processes means that they are separate and modifications in one process have no effect on any other process.</p>

Body:
I am working on a script where fork() is called in a for loop to create many children, these children do a random number of loops and then print the name of the child

I'm having some odd behavior where the memory address that i is at is shared for all of the child processes even though the variable is created after the fork()

Is this the intended behavior? And if so is there any way for these variables to be stored at different memory indexes as I do not want another child process affecting another

Here is some example output from the print that is commented out in the childCall function

In child 1 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
Child 2
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
Child 3
In child 1 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
Child 4
In child 5 i is located at 0xbef49508
Child 1
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
Child 5

Below is the for loop in the parent function that creates the child processes and below that is the childCall function

Thank you!

for(int i = 0; i<children; i++)
    {
        if(fork() == 0) //If I am the child
        {
            childCall(i + 1);
            return 0;
        }
    }

The childCall function is as follows

void childCall(int children)
{
    for(int i = 0; i<children; i++)
    {
        //printf("In child %d i is located at %p\n", children, &i);
        int newrand = rand() % 2; //This implementation is because when I was declaring a random value before the loop all of the children shared the same random value, due to pseudorandomness!
        //printf("%d is the random number\n", newrand);
        i -= newrand;
    }
    printf("Child %d\n", children);
}


问:
Why is this Query statement not displaying "text" formatted phone numbers" on Google Sheets?
This formula is returning eveything right,but the phone numbers, which are preceded by an apostrophe. If I happen to delete the apostrophe, it displays the numbers, but since there may be a 0 at the beginning, it has to come as text.

Here's the formula:

```<code>=iferror(QUERY('Form Responses'!$A$4:$P; "select N, B, C, D, E, F, G, H, I, J, K, L, A where N >= 1 and todate(A)=date '"&TEXT(B3;"yyyy-mm-dd")&"' order by N Asc");"Pick a date")
</code>```

Here's how the data looks:

...and this is the result right now:

Here's the link to an example:
https://docs.google.com/spreadsheets/d/1vxCwfcXRrpuvmkhpRsFrKQSq5aMjkdqlUYY-6_UknuE/edit?usp=sharing

Appreciate your time/help - as usual!

答:
try:

```<code>=INDEX(SUBSTITUTE(IFERROR(QUERY(
 {'Form Responses'!A4:P\ TEXT('Form Responses'!E4:E; "\×0")};
 "select Col14,Col2,Col3,Col4,Col17,Col6,Col7,Col8,Col9,Col10,Col11,Col12,Col1
  where Col14 >= 1
    and todate(Col1) = date '"&TEXT(B3; "yyyy-mm-dd")&"'
  order by Col14 asc"); "Pick a date"); "×"; ))
</code>```

update:

try:

```<code>=ARRAYFORMULA(TEXT(SUBSTITUTE(IFERROR(QUERY(
 {'Form Responses'!A4:P\ TEXT('Form Responses'!E4:E; "\×0")};
 "select Col14,Col2,Col3,Col4,Col17,Col6,Col7,Col8,Col9,Col10,Col11,Col12,Col1
  where Col14 >= 1
    and todate(Col1) = date '"&TEXT(B3; "yyyy-mm-dd")&"'
  order by Col14 asc"); "Pick a date"); "×"; );
 {"@"\"@"\"@"\"@"\"\0#"\"@"\"@"\"@"\"@"\"@"\"@"\"@"\"mm/dd/yyyy"}))
</code>```

Body:
This formula is returning eveything right,but the phone numbers, which are preceded by an apostrophe. If I happen to delete the apostrophe, it displays the numbers, but since there may be a 0 at the beginning, it has to come as text.

Here's the formula:

=iferror(QUERY('Form Responses'!$A$4:$P; "select N, B, C, D, E, F, G, H, I, J, K, L, A where N >= 1 and todate(A)=date '"&TEXT(B3;"yyyy-mm-dd")&"' order by N Asc");"Pick a date")

Here's how the data looks:

...and this is the result right now:

Here's the link to an example:
https://docs.google.com/spreadsheets/d/1vxCwfcXRrpuvmkhpRsFrKQSq5aMjkdqlUYY-6_UknuE/edit?usp=sharing

Appreciate your time/help - as usual!

Body:
try:

=INDEX(SUBSTITUTE(IFERROR(QUERY(
 {'Form Responses'!A4:P\ TEXT('Form Responses'!E4:E; "\×0")};
 "select Col14,Col2,Col3,Col4,Col17,Col6,Col7,Col8,Col9,Col10,Col11,Col12,Col1
  where Col14 >= 1
    and todate(Col1) = date '"&TEXT(B3; "yyyy-mm-dd")&"'
  order by Col14 asc"); "Pick a date"); "×"; ))

update:

try:

=ARRAYFORMULA(TEXT(SUBSTITUTE(IFERROR(QUERY(
 {'Form Responses'!A4:P\ TEXT('Form Responses'!E4:E; "\×0")};
 "select Col14,Col2,Col3,Col4,Col17,Col6,Col7,Col8,Col9,Col10,Col11,Col12,Col1
  where Col14 >= 1
    and todate(Col1) = date '"&TEXT(B3; "yyyy-mm-dd")&"'
  order by Col14 asc"); "Pick a date"); "×"; );
 {"@"\"@"\"@"\"@"\"\0#"\"@"\"@"\"@"\"@"\"@"\"@"\"@"\"mm/dd/yyyy"}))


问:
DatetimeIndex.get_loc is deprecated
I updated Pandas to 1.4.0 with yfinance 0.1.70.  Previously, I had to stay with Pandas 1.3.5 as Pandas and yfinance did't play well together.  These latest versions of Pandas and yfinance now work together, BUT Pandas now gives me this warning:

```<code>Future Warning: Passing method to DatetimeIndex.get_loc is deprecated... Use index.get_indexer([item], method=...) instead
</code>```

I had enough trouble as a novice Python person getting the original get_loc statement to work:

```<code>last_week = format((df.index[df.index.get_loc(last_week, method='nearest')]).strftime('%Y-%m-%d'))
</code>```

This statement allowed me to get a date from the dataframe that I could use further in determining the value associated with that date:

```<code>week_value = df.loc[last_week, ans]
</code>```

Truth be known, I am intimidated in trying to change this statement to be compliant with the new and improved get_indexer function.  Can someone help me out please?

答:
Should be pretty simple. Just change get_loc(XXX, ...) to get_indexer([XXX], ...)[0]:

```<code>last_week = format((df.index[df.index.get_indexer([last_week], method='nearest')[0]]).strftime('%Y-%m-%d'))
</code>```

Title: DatetimeIndex.get_loc is deprecated

Body:
I updated Pandas to 1.4.0 with yfinance 0.1.70.  Previously, I had to stay with Pandas 1.3.5 as Pandas and yfinance did't play well together.  These latest versions of Pandas and yfinance now work together, BUT Pandas now gives me this warning:

Future Warning: Passing method to DatetimeIndex.get_loc is deprecated... Use index.get_indexer([item], method=...) instead

I had enough trouble as a novice Python person getting the original get_loc statement to work:

last_week = format((df.index[df.index.get_loc(last_week, method='nearest')]).strftime('%Y-%m-%d'))

This statement allowed me to get a date from the dataframe that I could use further in determining the value associated with that date:

week_value = df.loc[last_week, ans]

Truth be known, I am intimidated in trying to change this statement to be compliant with the new and improved get_indexer function.  Can someone help me out please?

Body:
Should be pretty simple. Just change get_loc(XXX, ...) to get_indexer([XXX], ...)[0]:

last_week = format((df.index[df.index.get_indexer([last_week], method='nearest')[0]]).strftime('%Y-%m-%d'))


问:
Remove file location from document print using Javascript
I am using Javascript to print a div contents it works fine but it also prints the file location on top-right position which gives an odd impression on the output. here i attached the snap of it.

Thanks.

答:
Thanks to all specially zzzzBov From the menu in the top left corner of your browser, choose "File", then "Page setup..". Go to the second tab called "Margins & Header / Footer", in the drop down lists choose "Blank" for all the items you don't want printed. The screenshot below gives a better view of what I mean.

And for other browsers you can read the complete article on enter link description here


问:
Is there any way to increase API request limit on GCP Workflows?
Our GCP project is expected to call many GCP Workflows requests.
We are afraid of exceeding the Execution API write requests below.
https://cloud.google.com/workflows/quotas#request_limit

Is there any way to increase Execution API write requests ?

答: Quota increases can be requested from Cloud Customer Care. Many of the limits for Workflows can be raised after answering a few simple questions about how Workflows is being used. The team is raising the general limits over time.</p>


问:
Constructing a complete control flow graph for Linux kernel
Are there any tools that can build the control flow graph for an entire Linux kernel binary? For example, consider Linux kernel compiled for x86 architecture (vmlinux file). Is it possible to determine all execution paths (regarding indirect call) using both static analysis and dynamic analysis? Are there any tools suitable for this?</p>

答:
I assume you mean analyzing the source code used to produce the Linux binaries.

Hope you are prepared for a lot of work.  There are reasons you can't get this off the shelf.

You need two kinds of tools:

Machinery to construct a control flow graph of individual C source files, that work for real dialects of C as used by the Linux kernel.

Something that can construct a global call graph including indirect calls; if you don't handle indirect calls well, your call graph is either ridiculously over connected (the famous "scribble" diagram), or ridiculously underconnected (most functions won't be reachable).

For [1],

You could build your own custom tool from scratch, after all, you "just need a parser".  This path is simply madness.  See http://www.semdesigns.com/Products/DMS/LifeAfterParsing.html

Most modern C compilers will do that as part of the process of compiling a source file, so that's a promising place to look. Given that GCC is used to compile Linux, that's the most obvious place to look: https://gcc.gnu.org/  Getting GCC to cough up that control flow graph in some usable form for  your purpose may be harder; GCC's internals are famously hard to work with.  Clang can compile C programs; I don't know about its compatibility with the GCC dialect but I'd guess it was highly probable.  Clang (https://clang.llvm.org/) appears to be built with the intention of customization so CFG extraction is likely to be technically straightforward, and I'd bet that Google has done this for internal projects.  There are other C compilers out there (e.g., Intel's) , but if they don't do the GCC dialect used on Linux, you will find yourself first have to adapt them and than extracting what you want, and getting the source code of those compilers so you can make these changes is likely difficult.

You can try to adapt some security scanning tool such as Coverity or KlocWork.  I doubt you will make much progress getting such a tool in a form that you can adapt.

You can use a (commercial) general program transformation tool like our DMS Software Reengineering Toolkit.  DMS is customizable compiler technology which was designed to be internally accessible to motivated engineers.  DMS can process many GCC dialects, and has been used on real embedded software systems of tens of millions of lines of code.  DMS's GCC front end constructs control and data flow graphs; see http://www.semdesigns.com/products/DMS/FlowAnalysis.html#DataFlowAnalysis. Another (research) program transformation tool is RascalMPL https://www.rascal-mpl.org/ might work, but I have not heard of it being applied to GCC dialects or operating at this scale; it may do so.

For [2],

You can build your call-graph construction tool custom tool.  Doing a pointer-sensitive flow analysis at this scale isn't as hard as building your flow graph construction, but its pretty close in the amount of audacity required to do it.  (Google likely has the audacity).

DMS has a points-to analysis subsystem, that has been been used on a 16 million line embedded system (for a client, to enable a custom code generation task for them).  It also has call-graph construction that uses this points-to information.  See http://www.semdesigns.com/products/DMS/FlowAnalysis.html#CallGraphAnalysis. Specifically see the Sample Call graph link, which shows the results of points-to analysis.

Once you have these pieces, you can consider what you might do with the result.   I can tell you that a flow graph for a million line system will cover a football field at 1 inch resolution; you'll need serious computing power to traverse/analyze such a graph.

If your intent was to analyze the Linux binaries (well you'd want to process the linker modules) directly, you don't have nearly as bad a problem of building the control flow graph because you don't have to deal with what amounts to most of a compiler.  Now you just have to worry about the entire Intel instruction set.  But if you model the machine instructions accurately, your CFG is likely to be 10x the size of one for the source code and a whole lot less helpful in tracing any issues back to the source.


问:
GitLab CI pull docker from private registry

The situation

I'm currently working on a project where I migrate the CI environment from Jenkins to GitLab CI. To get everything working I've built a few docker containers that should serve as base images for the CI pipeline.
These containers cannot be stored in the GitLab internal container registry and should be pushed to a Artifactory instance.

What I already did/tried

So far I got everything going by using Kaniko for the Docker builds and the resulting images are correctly pushed to the artifactory registry - so far, so good.

However I've now reached a point where I have CI-Jobs that should make use of previously built container-images as their base image, so they should be pulled from the artifactory instance, which serves as private registry.

example config

.docker-build-abstract:
  image: custom.kaniko.fork.from.internal.gitlab-registry:<tag>
  script:
    - |>
      echo "build container with image tag: ${IMAGE_TAG}"
      # kaniko default build..

# This job builds an image that is pushed to private registry.
docker-build-1:
  stage: "build"
  variables:
    IMAGE_TAG: some.nice.tag
    BUILD_ARGS: --build-arg foo=bar --build-arg bar=baz
  extends:
    - .docker-build-abstract

# This job should make use of the previously built image
other-job-1:
  stage: "build"
  image: docker.from.docker-build-1:<tag>
  script: #...
```
<p>The Problem with this is that I cannot make use of <code>DOCKER_AUTH_CONFIG</code> variable in the CI-Settings that is proposed in the official docs.
This is because (my understanding) when providing this variable in the project settings this would overwrite the default registry-settings (<code>CI_REGISTRY</code>, <code>CI_REGISTRY_USER</code>, <code>CI_REGISTRY_PASSWORD</code>) but I need to preserve the values behind these internal variables because some of the first jobs make use of Container-images that are only present within this private gitlab instance.</p>
<p>Is it possible to provide multiple auth-configs in the CI/CD Variable settings? And how would I reference the predefined variables in here since this important to keep the internal registry known?</p>
<p>I would imagine something like below (which is part of the kaniko pre-configuration), but cannot come up with a possible solution for this scenario.</p>
<pre class="lang-json prettyprint-override"><code>{
  "auths": {
    "$PRIVATE_REGISTRY": {
      "username": "$PRIV_REGISTRY_USER",
      "password": "$PRIV_REGISTRY_API_KEY",
      "email": "$PRIV_REGISTRY_USER_EMAIL"
    },
    "$CI_REGISTRY": {
      "username": "$CI_REGISTRY_USER",
      "password": "$CI_REGISTRY_PASSWORD"
    }
  }
}
</code>```

In my understanding the variables can be overwritten in the ci-configuration, but this did not work for me.
Would this require advanced configuration of the ci-runner to achieve the desired behavior, like outlined here in the docs?

Really appreciate your help or hints!

答:
You can use DOCKER_AUTH_CONFIG for this. The config can support multiple registries. So it's possible to have this set for both your GitLab internal registry as well as your JFrog Artifactory instance. See: credential helpers in the docker documentation, which supports multiple registries.

Alternatively, you can use docker login as-needed in your job, which will apply auth information to your (docker) config dynamically.

my_job:
  before_script:
    # authenticate to pull from GitLab registry
    # https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
    - docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN

    # authenticate to pull from Artifactory
    # you must define these variables
    - docker login $ARTIFACTORY_REGISTRY -u $ARTIFACTORY_USER -p $ARTIFACTORY_PASSWORD
```

You could also use a combination of the two -- DOCKER_AUTH_CONFIG for artifactory and docker login for GitLab registry, as an example.

Alternatively still, you can also configure JFrog Artifactory virtual repos that will serve images from your GitLab registry. That way you only need to configure one registry on the job side. However, this requires setup in advance and can have authorization implications.

Body:
The situation

I'm currently working on a project where I migrate the CI environment from Jenkins to GitLab CI. To get everything working I've built a few docker containers that should serve as base images for the CI pipeline.
These containers cannot be stored in the GitLab internal container registry and should be pushed to a Artifactory instance.

What I already did/tried

So far I got everything going by using Kaniko for the Docker builds and the resulting images are correctly pushed to the artifactory registry - so far, so good.

However I've now reached a point where I have CI-Jobs that should make use of previously built container-images as their base image, so they should be pulled from the artifactory instance, which serves as private registry.

example config

.docker-build-abstract:
  image: custom.kaniko.fork.from.internal.gitlab-registry:<tag>
  script:
    - |>
      echo "build container with image tag: ${IMAGE_TAG}"
      # kaniko default build..

# This job builds an image that is pushed to private registry.
docker-build-1:
  stage: "build"
  variables:
    IMAGE_TAG: some.nice.tag
    BUILD_ARGS: --build-arg foo=bar --build-arg bar=baz
  extends:
    - .docker-build-abstract

# This job should make use of the previously built image
other-job-1:
  stage: "build"
  image: docker.from.docker-build-1:<tag>
  script: #...

The Problem with this is that I cannot make use of DOCKER_AUTH_CONFIG variable in the CI-Settings that is proposed in the official docs.
This is because (my understanding) when providing this variable in the project settings this would overwrite the default registry-settings (CI_REGISTRY, CI_REGISTRY_USER, CI_REGISTRY_PASSWORD) but I need to preserve the values behind these internal variables because some of the first jobs make use of Container-images that are only present within this private gitlab instance.

Is it possible to provide multiple auth-configs in the CI/CD Variable settings? And how would I reference the predefined variables in here since this important to keep the internal registry known?

I would imagine something like below (which is part of the kaniko pre-configuration), but cannot come up with a possible solution for this scenario.

{
  "auths": {
    "$PRIVATE_REGISTRY": {
      "username": "$PRIV_REGISTRY_USER",
      "password": "$PRIV_REGISTRY_API_KEY",
      "email": "$PRIV_REGISTRY_USER_EMAIL"
    },
    "$CI_REGISTRY": {
      "username": "$CI_REGISTRY_USER",
      "password": "$CI_REGISTRY_PASSWORD"
    }
  }
}

In my understanding the variables can be overwritten in the ci-configuration, but this did not work for me.
Would this require advanced configuration of the ci-runner to achieve the desired behavior, like outlined here in the docs?

Really appreciate your help or hints!

Body:
You can use DOCKER_AUTH_CONFIG for this. The config can support multiple registries. So it's possible to have this set for both your GitLab internal registry as well as your JFrog Artifactory instance. See: credential helpers in the docker documentation, which supports multiple registries.

Alternatively, you can use docker login as-needed in your job, which will apply auth information to your (docker) config dynamically.

my_job:
  before_script:
    # authenticate to pull from GitLab registry
    # https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
    - docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN

    # authenticate to pull from Artifactory
    # you must define these variables
    - docker login $ARTIFACTORY_REGISTRY -u $ARTIFACTORY_USER -p $ARTIFACTORY_PASSWORD

You could also use a combination of the two -- DOCKER_AUTH_CONFIG for artifactory and docker login for GitLab registry, as an example.

Alternatively still, you can also configure JFrog Artifactory virtual repos that will serve images from your GitLab registry. That way you only need to configure one registry on the job side. However, this requires setup in advance and can have authorization implications.


问:
adopting RandomAccessCollection protocol
```<code>public class Container2: RandomAccessCollection
{
    public typealias Indices = DefaultIndices<Container2>

    public typealias Index = Int
    //typealias SubSequence = Container2
    public var arr:[Int] = [1,2,3,4,5]

    public var endIndex: Index {
        return 5
    }

    public var startIndex:Index{
        return 0
    }

    public func index(after i: Int) -> Int{
        return i+1
    }

    public subscript(position: Int) -> Int{
        get{
            return arr[position]
        }
        set{
            arr[position] = newValue
        }
    }

    /*func index(before i: Int) -> Int{
        return i-1
    }*/

     public subscript(bounds: Range<Int>) -> Container2{
        get{
            return Container2()
        }
    }
}
</code>```

I'm trying to adopt the RandomAccessCollection protocol from a class. I deliberately leave out the func index(before:) function because there is already a default implementation of that function in RandomAccessCollection. I do understand that that function's implementation is required because of BiDirectionalCollection from which RandomAccessCollection inherits. My question is why would the compiler complain that func index(before:) implementation is required when there is already a default implementation in RandomAccessCollection that i can use? Thanks.

答:
why would the compiler complain that func index(before:) implementation is required when there is already a default implementation in RandomAccessCollection that i can use?

I had a similar problem as you and wondered the same. In the comments, Hamish answers our question, but I want to give more detail.

Read the main code comments to RandomAccessCollection.

```<code>/// The `RandomAccessCollection` protocol adds further constraints on the
/// associated `Indices` and `SubSequence` types, but otherwise imposes no
/// additional requirements over the `BidirectionalCollection` protocol.
/// However, in order to meet the complexity guarantees of a random-access
/// collection, either the index for your custom type must conform to the
/// `Strideable` protocol
</code>```

You defined Indices as DefaultIndices<Container2>. This conflicts with typealias Index = Int because Int is a different type than Container2. The Indices element type has to be a collection of the Index type.

Another problem is that Container2 does not conform to Strideable like the code comment says. Because your index type of Container2 does not conform to Strideable then the protocol extensions for index(before:) on RandomAccessCollection cannot be used. Thus, the complier complains.

I copied your code into a playground, and made the complier error go away by changing 1 line:

```<code>    public typealias Indices = Range<Int>
</code>```

Also, subscript(position:) makes sense but subscript(bounds:) is wrong. You have Container2 coded to return Int not copies of itself. You can delete that func because it is not needed.

The reason I hit a similar problem as you was because I tried to implement a type that conformed to RandomAccessCollection by using the errors that the Xcode code completion gave me. This is folly.

This question has a minimal conformance example. However, I pared that down to something even smaller.

```<code>struct SomeInts : RandomAccessCollection {
    var startIndex: Int { 0 }
    var endIndex: Int  { 5 }
    subscript(position: Int) -> Int {
        get { [51, 53, 59, 61, 67, 71][position] }
    }
}
</code>```

The lesson from this is: ignore Xcode code completion telling you to define those generic type aliases as concrete types. Instead, implement the minimum functions using concrete types, and let type inference tell the complier what those generic type aliases should be.

Body:
public class Container2: RandomAccessCollection
{
    public typealias Indices = DefaultIndices<Container2>

    public typealias Index = Int
    //typealias SubSequence = Container2
    public var arr:[Int] = [1,2,3,4,5]

    public var endIndex: Index {
        return 5
    }

    public var startIndex:Index{
        return 0
    }

    public func index(after i: Int) -> Int{
        return i+1
    }

    public subscript(position: Int) -> Int{
        get{
            return arr[position]
        }
        set{
            arr[position] = newValue
        }
    }

    /*func index(before i: Int) -> Int{
        return i-1
    }*/

     public subscript(bounds: Range<Int>) -> Container2{
        get{
            return Container2()
        }
    }
}

I'm trying to adopt the RandomAccessCollection protocol from a class. I deliberately leave out the func index(before:) function because there is already a default implementation of that function in RandomAccessCollection. I do understand that that function's implementation is required because of BiDirectionalCollection from which RandomAccessCollection inherits. My question is why would the compiler complain that func index(before:) implementation is required when there is already a default implementation in RandomAccessCollection that i can use? Thanks.

Body:
why would the compiler complain that func index(before:) implementation is required when there is already a default implementation in RandomAccessCollection that i can use?

I had a similar problem as you and wondered the same. In the comments, Hamish answers our question, but I want to give more detail.

Read the main code comments to RandomAccessCollection.

/// The `RandomAccessCollection` protocol adds further constraints on the
/// associated `Indices` and `SubSequence` types, but otherwise imposes no
/// additional requirements over the `BidirectionalCollection` protocol.
/// However, in order to meet the complexity guarantees of a random-access
/// collection, either the index for your custom type must conform to the
/// `Strideable` protocol

You defined Indices as DefaultIndices<Container2>. This conflicts with typealias Index = Int because Int is a different type than Container2. The Indices element type has to be a collection of the Index type.

Another problem is that Container2 does not conform to Strideable like the code comment says. Because your index type of Container2 does not conform to Strideable then the protocol extensions for index(before:) on RandomAccessCollection cannot be used. Thus, the complier complains.

I copied your code into a playground, and made the complier error go away by changing 1 line:

    public typealias Indices = Range<Int>

Also, subscript(position:) makes sense but subscript(bounds:) is wrong. You have Container2 coded to return Int not copies of itself. You can delete that func because it is not needed.

The reason I hit a similar problem as you was because I tried to implement a type that conformed to RandomAccessCollection by using the errors that the Xcode code completion gave me. This is folly.

This question has a minimal conformance example. However, I pared that down to something even smaller.

struct SomeInts : RandomAccessCollection {
    var startIndex: Int { 0 }
    var endIndex: Int  { 5 }
    subscript(position: Int) -> Int {
        get { [51, 53, 59, 61, 67, 71][position] }
    }
}

The lesson from this is: ignore Xcode code completion telling you to define those generic type aliases as concrete types. Instead, implement the minimum functions using concrete types, and let type inference tell the complier what those generic type aliases should be.


问:
Fetch data via JSON parser with thread
i am stuck in one problem regarding JSON parser.actually i am fetching data through JSON parser and it works successfully but i want to display that data as it come one by one and so that i need to work with Thread so anybody can help me out?how to use multiple thread while fetching data</p>

答:
Have a look at NSOperation. It is the easiest way to perform Network operations in separate threads. The documentation can be found at http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html.

HTH,

Akshay

Title: Fetch data via JSON parser with thread


问:
Copying LookupId into all rows in SSIS
I have two tables, one is LookUpTable where I have an id for AttendanceType = Remote. And I have another table where there is a column called AttendanceType.

I want to fetch the id from LookupTable and copy in all rows of another table into the column AttendanceType in SSIS package?

答: You can use merge join in ssis to join both the sources based on attendence type field and fetch required fields from both the tables.</p>

Title: Copying LookupId into all rows in SSIS


问:
Replace other values with np.nan
I have a pandas data frame:

```<code>import pandas as pd

X = pd.DataFrame({'col1': [1,2],
                  'col2': [4,5]})
</code>```

I have a replacement dictionary:

```<code>dict_replace = {
    'col1': {1:'a', 2:'b'},
    'col2': {4:'c', 5:'d'}
}
</code>```

I can easily replace the values in X using:

```<code>X = X.replace(dict_replace)
</code>```

Resulting in:

```<code>X = pd.DataFrame({'col1': ['a','b'],
                  'col2': ['c','d']})
</code>```

However, if a new value appears in X which is not in dict_replace (for the respective column) I want it replaced with np.nan.

For example, a data frame:

```<code>X = pd.DataFrame({'col1': [1,2,3],
                  'col2': [4,5,7]})
</code>```

Should look like:

```<code>X = pd.DataFrame({'col1': ['a','b',np.nan],
                  'col2': ['c','d',np.nan]})
</code>```

What are some ways I can do this without having to iterate?

答:
Try with mask

```<code>out = X.replace(dict_replace).mask(lambda x : x==X)
Out[215]:
  col1 col2
0    a    c
1    b    d
2  NaN  NaN
</code>```

Title: Replace other values with np.nan

Body:
I have a pandas data frame:

import pandas as pd

X = pd.DataFrame({'col1': [1,2],
                  'col2': [4,5]})

I have a replacement dictionary:

dict_replace = {
    'col1': {1:'a', 2:'b'},
    'col2': {4:'c', 5:'d'}
}

I can easily replace the values in X using:

X = X.replace(dict_replace)

Resulting in:

X = pd.DataFrame({'col1': ['a','b'],
                  'col2': ['c','d']})

However, if a new value appears in X which is not in dict_replace (for the respective column) I want it replaced with np.nan.

For example, a data frame:

X = pd.DataFrame({'col1': [1,2,3],
                  'col2': [4,5,7]})

Should look like:

X = pd.DataFrame({'col1': ['a','b',np.nan],
                  'col2': ['c','d',np.nan]})

What are some ways I can do this without having to iterate?

Body:
Try with mask

out = X.replace(dict_replace).mask(lambda x : x==X)
Out[215]:
  col1 col2
0    a    c
1    b    d
2  NaN  NaN


问:
Bottom-left screen positioning CSS
I am trying to make the Card as i call it attached to the screen so when it is resized, the card will go along with it.

Css code:

```<code>    #wrapper {
    position: relative;
    max-width: 1920px;
    max-width: 100%;
    padding-right: 10px;
    padding-left: 10px;
}
#introduction-container {
    position: relative;
}
#introduction-textposition {
    position: absolute;
    bottom: 100%;
    left: 10%;
}
#introduction-paragraph {
    width: 500px;
    height: 150px;
    background-color: rgba(18, 18, 18, 0.7);
    padding: 40px 25px;
    margin-top: 0;
}
</code>```

html code

```<code> <div id="wrapper">
    <div id="introduction-container">
        <div id="introduction-textposition">
      <div id="introduction-paragraph">
        <h3>RTX 2080Ti Available Now!</h3>
        <h1>RAY-TRACE</h1>
        <p><span style="color: rgb(118, 185, 0);">NVIDIA RTX</span> is the most advanced platform for ray tracing and AI technologies that are revolutionizing the ways we play and create</p>
        <div>
            <a href="#" class="introduction-button hover-color">SHOP NOW!</a>
        </div>
      </div>
    </div>
    </div>
</code>```

ps: the introduction-textposition percentaged is me playing around with it, wont work tho.
problem is, when i used the relative position on #introduction-container it the properties wont show here;
html image

What it should look like: illustration

答:
Try this (Open it in "full page" mode)

* {
    box-sizing: border-box;
}
body {
    margin: 0;
}
#wrapper {
    position: relative;
    max-width: 1920px;
    max-width: 100%;
    padding-right: 10px;
    padding-left: 10px;
    min-height: 100vh;
}
#introduction-paragraph {
    width: 400px;
    background-color: rgba(18, 18, 18, 0.7);
    padding: 40px 25px;
    margin-top: 0;
    position: absolute;
    bottom: 10%;
    left: 10%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
    <div id="introduction-paragraph">
        <h3>RTX 2080Ti Available Now!</h3>
        <h1>RAY-TRACE</h1>
        <p><span style="color: rgb(118, 185, 0);">NVIDIA RTX</span> is the most advanced platform for ray tracing and AI technologies that are revolutionizing the ways we play and create</p>
        <div>
            SHOP NOW!
        </div>
    </div>
</div></code>```

Title: Bottom-left screen positioning CSS

Body:
I am trying to make the Card as i call it attached to the screen so when it is resized, the card will go along with it.

Css code:

    #wrapper {
    position: relative;
    max-width: 1920px;
    max-width: 100%;
    padding-right: 10px;
    padding-left: 10px;
}
#introduction-container {
    position: relative;
}
#introduction-textposition {
    position: absolute;
    bottom: 100%;
    left: 10%;
}
#introduction-paragraph {
    width: 500px;
    height: 150px;
    background-color: rgba(18, 18, 18, 0.7);
    padding: 40px 25px;
    margin-top: 0;
}

html code

RTX 2080Ti Available Now!

RAY-TRACE

NVIDIA RTX is the most advanced platform for ray tracing and AI technologies that are revolutionizing the ways we play and create

            SHOP NOW!

ps: the introduction-textposition percentaged is me playing around with it, wont work tho.
problem is, when i used the relative position on #introduction-container it the properties wont show here;
html image

What it should look like: illustration

Body:
Try this (Open it in "full page" mode)

* {
    box-sizing: border-box;
}
body {
    margin: 0;
}
#wrapper {
    position: relative;
    max-width: 1920px;
    max-width: 100%;
    padding-right: 10px;
    padding-left: 10px;
    min-height: 100vh;
}
#introduction-paragraph {
    width: 400px;
    background-color: rgba(18, 18, 18, 0.7);
    padding: 40px 25px;
    margin-top: 0;
    position: absolute;
    bottom: 10%;
    left: 10%;
}

<div id="wrapper">
    <div id="introduction-paragraph">
        <h3>RTX 2080Ti Available Now!</h3>
        <h1>RAY-TRACE</h1>
        <p><span style="color: rgb(118, 185, 0);">NVIDIA RTX</span> is the most advanced platform for ray tracing and AI technologies that are revolutionizing the ways we play and create</p>
        <div>
            <a href="#" class="introduction-button hover-color">SHOP NOW!</a>
        </div>
    </div>
</div>


问:
Filter multiple Array Objects and match key values with multiple values form another array in Javascript
Been racking my head for a few nights now and Im hoping a kind soul can help solve this wall I have hit.

I have an Array of Objects.

As a user I should be able to filter feature name(s) by multiple or singular filters.
A single filter should return all events with a matching name
A multiple filter should match all events with more than one feature name, not less than 2 or the length of the filters array.

The code I have eventually been stuck with or as far as I can go is this.

let obj1 = [{
  "results": [{
      "id": "1",
      "name": "Event 1",
      "feature": [{
          "id": {
            "target": "78"
          },
          "name": "Bronze"
        },
        {
          "id": {
            "target": "27"
          },
          "name": "Straw"
        },
        {
          "id": {
            "target": "45"
          },
          "name": "Gold"
        }
      ]
    },
    {
      "id": "2",
      "name": "Event 2",
      "feature": [{
        "id": {
          "target": "20"
        },
        "name": "Straw"
      }]
    },
    {
      "id": "3",
      "name": "Event 3",
      "feature": [{
          "id": {
            "target": "20"
          },
          "name": "Gold"
        },
        {
          "id": {
            "target": "20"
          },
          "name": "Straw"
        }
      ]
    },
    {
      "id": "4",
      "name": "Event 4",
      "feature": [{
          "id": {
            "target": "97"
          },
          "name": "Coal"
        },
        {
          "id": {
            "target": "39"
          },
          "name": "Wood"
        }
      ]
    }
  ]
}]

let filterQuery = ['Straw', 'Gold'];

obj1 = obj1[0].results.filter(r => {
  return r.feature.every(f => {
    return filterQuery.includes(f.name)
  })
})

console.log(obj1);```
</div>
</div>
</p>
<p>It filters anything with <code>Straw</code> or <code>Gold</code>, and everything with Straw and Gold</p>
<p>Im trying to get the filter to filter Straw && Gold</p>
<p>So returning an event(s) with example</p>
<p><code> {name: 'Straw', name: 'Gold', name: 'Diamond', name: Copper}</code></p>
<p>would be a correct match, so a user could add another filter to the array to filter the results further.</p>
<p><code>{ name: Straw, name: Diamond }</code></p>
<p>Would not be a correct match.</p>
<p>Any help, suggestions would be greatly appreciated :)</p>
<p>===========================================================</p>
<p>Updated, solved solution. I needed it to be agnostic as possible so it works if key names change. Used in a Vuejs project with Drupal.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    export default class FilterData {

      constructor(name, data, filter_query) {
        this.name = name;
        this.data = data;
        this.filter_query = filter_query;
      }

      filterData(){
        let temp = this.data

// filter out any undefined arrays
        temp = temp.filter((item) => item[this.name] !== undefined);
        temp = temp.filter((item) =>
          [this.filter_query].every((filter) =>
            item[this.name].some(({ name }) => name === filter)
          )
        );
        return temp
      }

    }</code>```

And use it like so

/* use a temp copy of the returned data from the api
so we can keep refiltering from multiple drop downs, radio, checkboxes changes each time a filter keyname is un-selected.
*/

let apiResults = this.apiData.results;

      let filtered = new FilterData(
        `${keyname}`,
        apiResults,
        this.filterQuery[`${keyname}`]
      );
```

Thank you so much @pilchard your answer helped this greatly.

答:
You need to switch your every() call to the filterQuery array. So test if every() string in the filter array has a match in the feature array, here testing with some().

let obj1 = [{ "results": [{ "id": "1", "name": "Event 1", "feature": [{ "id": { "target": "78" }, "name": "Bronze" }, { "id": { "target": "27" }, "name": "Straw" }, { "id": { "target": "45" }, "name": "Gold" }] }, { "id": "2", "name": "Event 2", "feature": [{ "id": { "target": "20" }, "name": "Straw" }] }, { "id": "3", "name": "Event 3", "feature": [{ "id": { "target": "20" }, "name": "Gold" }, { "id": { "target": "20" }, "name": "Straw" }] }, { "id": "4", "name": "Event 4", "feature": [{ "id": { "target": "97" }, "name": "Coal" }, { "id": { "target": "39" }, "name": "Wood" }] }] }]

let filterQuery = ['Straw', 'Gold'];

const filteredObj = obj1[0].results.filter(({ feature }) =>
  filterQuery.every(filter =>
    feature.some(({ name }) => name === filter)))

console.log(filteredObj);```

Body:
Been racking my head for a few nights now and Im hoping a kind soul can help solve this wall I have hit.

I have an Array of Objects.

As a user I should be able to filter feature name(s) by multiple or singular filters.
A single filter should return all events with a matching name
A multiple filter should match all events with more than one feature name, not less than 2 or the length of the filters array.

The code I have eventually been stuck with or as far as I can go is this.

let obj1 = [{
  "results": [{
      "id": "1",
      "name": "Event 1",
      "feature": [{
          "id": {
            "target": "78"
          },
          "name": "Bronze"
        },
        {
          "id": {
            "target": "27"
          },
          "name": "Straw"
        },
        {
          "id": {
            "target": "45"
          },
          "name": "Gold"
        }
      ]
    },
    {
      "id": "2",
      "name": "Event 2",
      "feature": [{
        "id": {
          "target": "20"
        },
        "name": "Straw"
      }]
    },
    {
      "id": "3",
      "name": "Event 3",
      "feature": [{
          "id": {
            "target": "20"
          },
          "name": "Gold"
        },
        {
          "id": {
            "target": "20"
          },
          "name": "Straw"
        }
      ]
    },
    {
      "id": "4",
      "name": "Event 4",
      "feature": [{
          "id": {
            "target": "97"
          },
          "name": "Coal"
        },
        {
          "id": {
            "target": "39"
          },
          "name": "Wood"
        }
      ]
    }
  ]
}]

let filterQuery = ['Straw', 'Gold'];

obj1 = obj1[0].results.filter(r => {
  return r.feature.every(f => {
    return filterQuery.includes(f.name)
  })
})

console.log(obj1);

It filters anything with Straw or Gold, and everything with Straw and Gold

Im trying to get the filter to filter Straw && Gold

So returning an event(s) with example

 {name: 'Straw', name: 'Gold', name: 'Diamond', name: Copper}

would be a correct match, so a user could add another filter to the array to filter the results further.

{ name: Straw, name: Diamond }

Would not be a correct match.

Any help, suggestions would be greatly appreciated :)

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

Updated, solved solution. I needed it to be agnostic as possible so it works if key names change. Used in a Vuejs project with Drupal.

    export default class FilterData {

      constructor(name, data, filter_query) {
        this.name = name;
        this.data = data;
        this.filter_query = filter_query;
      }

      filterData(){
        let temp = this.data

// filter out any undefined arrays
        temp = temp.filter((item) => item[this.name] !== undefined);
        temp = temp.filter((item) =>
          [this.filter_query].every((filter) =>
            item[this.name].some(({ name }) => name === filter)
          )
        );
        return temp
      }

    }

And use it like so

/* use a temp copy of the returned data from the api
so we can keep refiltering from multiple drop downs, radio, checkboxes changes each time a filter keyname is un-selected.
*/

let apiResults = this.apiData.results;

      let filtered = new FilterData(
        `${keyname}`,
        apiResults,
        this.filterQuery[`${keyname}`]
      );

Thank you so much @pilchard your answer helped this greatly.


问:
Getting System.Web.Mvc.SelectListItem as options of DropDownList
I have a ViewBag.CategoryList which contains ViewBag.CategoryList = new SelectList(Category.GetCategories());

My View:

```
@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList), "Select Category", htmlAttributes: new {@class = "form-control"})
```

What I'm getting is <option>System.Web.Mvc.SelectListItem</option> instead of my strings. Debugger shows that the ViewBag does have a list of strings.

Edit:
Fixed it by replacing the view with:

```
@Html.DropDownListFor(model => model.Category, (IEnumerable)(ViewBag.CategoryList), "Select Category", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
```

答:
try this

```<code>var list=Category.GetCategories();
ViewBag.CategoryList = list.Select(i => new SelectListItem
            {
                Value = i.Id.ToString(),
                Text = i.Name
            })
</code>```

and view

```<code>@Html.DropDownListFor(model => model.Category, @ViewBag.CategoryList,"Select Category", htmlAttributes: new { @class = "form-control" })
</code>```

Body:
I have a ViewBag.CategoryList which contains ViewBag.CategoryList = new SelectList(Category.GetCategories());

My View:

@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList), "Select Category", htmlAttributes: new {@class = "form-control"})

What I'm getting is <option>System.Web.Mvc.SelectListItem</option> instead of my strings. Debugger shows that the ViewBag does have a list of strings.

Edit:
Fixed it by replacing the view with:

@Html.DropDownListFor(model => model.Category, (IEnumerable)(ViewBag.CategoryList), "Select Category", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })

Body:
try this

var list=Category.GetCategories();
ViewBag.CategoryList = list.Select(i => new SelectListItem
            {
                Value = i.Id.ToString(),
                Text = i.Name
            })

and view

@Html.DropDownListFor(model => model.Category, @ViewBag.CategoryList,"Select Category", htmlAttributes: new { @class = "form-control" })


问:
Powershell: Can Register-ObjectEvent watch for clipboard events?
(On Windows 10 and 11)

I have successfully used Register-ObjectEvent to watch for file system events.

Can it also be used to watch for clipboard events?

In other words, how is Register-ObjectEvent used to hook Clipboard.ContentChanged Event ?  (Or an equivalent event)

If so, is there an example somewhere? (I looked around but did not spot)

If not, what would the method be to monitor the clipboard?

I've been digging through the MS documentation, and can't find the way to do this (via Register-ObjectEvent or any other method).

Specifically, I want to be notified when a new text object appears on the clipboard. (I would then read the text, and parse it to see if it contained an element of interest, and if so, do some processing.)

答:
OK, there appears to be no direct way to do this.

What I had hoped was that there was the right kind of object surfaced to Register-ObjectEvent that would make this a direct implementation. Something like IO.ClipBoardWatcher version of FileSystemWatcher. But it appears there is no such animal.

The solution on mnaoumov.NET was proposed. It looked right, but on Win11 it does not run as is. (It is 7+ years old at this point.)

I made a few tweaks to it, and have it running on Win11 (and I expect it will also run fine on Win10). This mod can be found here.

The overall approach is that a piece of C# is injected to hook the ClipboardTextChanged event from the .NET/Win32 world. That is then monitored by the Powershell Register-ObjectEvent engine.

If there is a more direct, more Powershell-native way to do this, would love to see it!


问:
Function not working as intended when changing fragment / activity
The app is for Attendance with barcode.

The scan function work fine until i change to other fragment / activity and back to it. If that happen then the camera will scan but it will not return anything and on back press it wont show any toast (even thought it should).
If i close the app then reopen it, open this fragment and scan, it back to normal again until i change to other fragment / activity.

There isnt any error message. So i dont know where the error is.

This is parts of my code that i believe have something to do with this bug:

onCreateView:

```<code>@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_attendance, container, false);

    fetch();

    return v;
}
</code>```

fetch:

```<code>private void fetch() {

FirebaseRecyclerOptions <ModelEvent> options = new FirebaseRecyclerOptions.Builder<ModelEvent>()
.setQuery(query, snapshot -> new ModelEvent(
    Objects.requireNonNull(snapshot.child("eventID").getValue()).toString(),
    Objects.requireNonNull(snapshot.child("eventStatus").getValue()).toString()))
.build();

adapter = new FirebaseRecyclerAdapter<ModelEvent, ViewHolderEvent>(options) {
    @NonNull
    @Override
    public ViewHolderEvent onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_attendance, parent, false);

        return new ViewHolderEvent(view);
    }

    //Set data on each list
    @Override
    protected void onBindViewHolder(@NonNull ViewHolderEvent viewHolderEvent, int i, @NonNull ModelEvent modelEvent) {
            viewHolderEvent.setStringStatus(modelEvent.getEventStatus());

            viewHolderEvent.buttonScan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    stringEventID = modelEvent.getEventID();

                    ScanOptions options = new ScanOptions();
                    options.setDesiredBarcodeFormats(ScanOptions.ALL_CODE_TYPES);
                    options.setPrompt("Scan something");
                    options.setOrientationLocked(true);
                    options.setBeepEnabled(true);
                    fragmentLauncher.launch(options);
                }
            });
        }
    };
    recyclerViewAttendance.setAdapter(adapter);
}
</code>```

for scanner:

```<code>private final ActivityResultLauncher<ScanOptions> fragmentLauncher = registerForActivityResult(new ScanContract(),
    result -> {
        //On Backpress
        if(result.getContents() == null) {
            Toast.makeText(getContext(), "Cancelled", Toast.LENGTH_LONG).show();
        }
        else {
            //Get data from QRCode
            stringQR = result.getContents();

            getUserData();
            setUserAttendance();

            //Notification
            Toast.makeText(getContext(), "Name: " + stringName, Toast.LENGTH_LONG).show();
         }
    });
</code>```

onStart:

```<code>@Override
public void onStart() {
    super.onStart();
    adapter.startListening();
}
</code>```

This is the full code: https://pastebin.com/e7XZN08i

答:
So i just do many thing and ended up find what i should do.

```<code> switch (item.getItemId()) {

    case R.id.nav_event:
        fragmentEvent = new FragmentEvent(); //i just need to add this on all case for some reason, the tutorial i use dont do this
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragmentEvent).commit();
        return true;
</code>```

I also ask this on github:https://github.com/journeyapps/zxing-android-embedded/issues/695

Body:
The app is for Attendance with barcode.

The scan function work fine until i change to other fragment / activity and back to it. If that happen then the camera will scan but it will not return anything and on back press it wont show any toast (even thought it should).
If i close the app then reopen it, open this fragment and scan, it back to normal again until i change to other fragment / activity.

There isnt any error message. So i dont know where the error is.

This is parts of my code that i believe have something to do with this bug:

onCreateView:

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_attendance, container, false);

    fetch();

    return v;
}

fetch:

private void fetch() {

FirebaseRecyclerOptions <ModelEvent> options = new FirebaseRecyclerOptions.Builder<ModelEvent>()
.setQuery(query, snapshot -> new ModelEvent(
    Objects.requireNonNull(snapshot.child("eventID").getValue()).toString(),
    Objects.requireNonNull(snapshot.child("eventStatus").getValue()).toString()))
.build();

adapter = new FirebaseRecyclerAdapter<ModelEvent, ViewHolderEvent>(options) {
    @NonNull
    @Override
    public ViewHolderEvent onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_attendance, parent, false);

        return new ViewHolderEvent(view);
    }

    //Set data on each list
    @Override
    protected void onBindViewHolder(@NonNull ViewHolderEvent viewHolderEvent, int i, @NonNull ModelEvent modelEvent) {
            viewHolderEvent.setStringStatus(modelEvent.getEventStatus());

            viewHolderEvent.buttonScan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    stringEventID = modelEvent.getEventID();

                    ScanOptions options = new ScanOptions();
                    options.setDesiredBarcodeFormats(ScanOptions.ALL_CODE_TYPES);
                    options.setPrompt("Scan something");
                    options.setOrientationLocked(true);
                    options.setBeepEnabled(true);
                    fragmentLauncher.launch(options);
                }
            });
        }
    };
    recyclerViewAttendance.setAdapter(adapter);
}

for scanner:

private final ActivityResultLauncher<ScanOptions> fragmentLauncher = registerForActivityResult(new ScanContract(),
    result -> {
        //On Backpress
        if(result.getContents() == null) {
            Toast.makeText(getContext(), "Cancelled", Toast.LENGTH_LONG).show();
        }
        else {
            //Get data from QRCode
            stringQR = result.getContents();

            getUserData();
            setUserAttendance();

            //Notification
            Toast.makeText(getContext(), "Name: " + stringName, Toast.LENGTH_LONG).show();
         }
    });

onStart:

@Override
public void onStart() {
    super.onStart();
    adapter.startListening();
}

This is the full code: https://pastebin.com/e7XZN08i

Body:
So i just do many thing and ended up find what i should do.

 switch (item.getItemId()) {

    case R.id.nav_event:
        fragmentEvent = new FragmentEvent(); //i just need to add this on all case for some reason, the tutorial i use dont do this
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragmentEvent).commit();
        return true;

I also ask this on github:https://github.com/journeyapps/zxing-android-embedded/issues/695


问:
problem with the if statement
i m parsing a json file.the logic goes like this, if there is no data in the variable named boy.it got to enter the if loop and if there is data it got to enter the else part.but the problem is even if the variable boy is empty(which shows  empty in the console) the loop still enters the else part..cud u guys help me out..below is the code..

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
NSDictionary *boy=[url objectAtIndex:indexPath.row];
NSLog(@"the boy value:%@",boy);
if (boy == NULL)
{
Secondetailview *detailViewController1 = [[Secondetailview alloc] initWithItem:boy];
[self.navigationController pushViewController:detailViewController1 animated:YES];
[detailViewController1 release];
}else
{
    FirstViewDetail *detailViewController = [[FirstViewDetail alloc] initWithItem:boy];

    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}
</code>```

}

答:
Replace

```<code>if (boy == NULL)
</code>```

with

```<code>if ([boy count] == 0)
</code>```

Title: problem with the if statement

Body:
i m parsing a json file.the logic goes like this, if there is no data in the variable named boy.it got to enter the if loop and if there is data it got to enter the else part.but the problem is even if the variable boy is empty(which shows  empty in the console) the loop still enters the else part..cud u guys help me out..below is the code..

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
NSDictionary *boy=[url objectAtIndex:indexPath.row];
NSLog(@"the boy value:%@",boy);
if (boy == NULL)
{
Secondetailview *detailViewController1 = [[Secondetailview alloc] initWithItem:boy];
[self.navigationController pushViewController:detailViewController1 animated:YES];
[detailViewController1 release];
}else
{
    FirstViewDetail *detailViewController = [[FirstViewDetail alloc] initWithItem:boy];

    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

}

Body:
Replace

if (boy == NULL)

with

if ([boy count] == 0)


问:
R programming - error : non-numeric argument to binary operator?
I am running this code (below) to add error bars onto my bar chart, i am trying to to work out the standard deviation (sd) of shannons diversity index
The code works up until the second/third last line

```<code>geom_errorbar(aes(ymin=shannon-sd, ymax=shannon+sd), width=0.2,
position=position_dodge(0.9))
</code>```

This error code keeps coming up

```<code>"Error in shannon - sd : non-numeric argument to binary operator"
</code>```

but this is my data...

```<code>Exposure  | genus      | shannon  | sd
----------------------------------------------
Exposed   | Crustacean | 0.000000 | 0.00000000
Exposed   | Mollusc    | 1.199625 | 0.13291129
Exposed   | Seaweed    | 1.513125 | 0.42093822
Sheltered | Crustacean | 0.025500 | 0.07212489
Sheltered | Mollusc    | 1.156750 | 0.26763341
Sheltered | Seaweed    | 1.848125 | 0.27264128
</code>```

anyone know where im going wrong?

```<code>library(ggplot2)
#+++++++++++++++++++++++++
# Function to calculate the mean and the standard deviation
# for each group
#+++++++++++++++++++++++++
# data : a data frame
# varname : the name of a column containing the variable
#to be summariezed
# groupnames : vector of column names to be used as
# grouping variables
data_summary <- function(data, varname, groupnames){
require(plyr)
summary_func <- function(x, col){
c(mean = mean(x[[col]], na.rm=TRUE),
sd = sd(x[[col]], na.rm=TRUE))
}
data_sum<-ddply(data, groupnames, .fun=summary_func,
varname)
data_sum <- rename(data_sum, c("mean" = varname))
return(data_sum)
}
df3 <- data_summary(diversity, varname="shannon",
groupnames=c("Exposure", "genus"))
# Convert dose to a factor variable
df3$genus=as.factor(df3$genus)
head(df3)
p <- ggplot(diversity, aes(x=genus, y=shannon, fill = location)) +
geom_bar(stat="identity", width = 0.5, position=position_dodge()) + theme_minimal() +
geom_errorbar(aes(ymin=shannon-sd, ymax=shannon+sd), width=0.2,
position=position_dodge(0.9))
p + scale_fill_brewer(palette="Paired") + theme_minimal()
</code>```

答:
You've shared a bunch of code but it's not totally clear what you're trying to accomplish with it all because most of it doesn't seem to make into the actual plot.

One thing I see that's generally not a good idea is that you define one function (data_summary()) inside another (summary_fun()).

Also your plotting code calls fill = location but it's not clear where location is coming from in your data.

So here's my best guess of what you were going for but please clarify if that's not it:

library(tidyverse)

d <- structure(list(Exposure = c("Exposed", "Exposed", "Exposed", "Sheltered", "Sheltered", "Sheltered"), genus = c("Crustacean", "Mollusc", "Seaweed", "Crustacean", "Mollusc", "Seaweed"), shannon = c(0, 1.199625, 1.513125, 0.0255, 1.15675, 1.848125), sd = c(0, 0.13291129, 0.42093822, 0.07212489, 0.26763341, 0.27264128)), row.names = c(NA, -6L), class = "data.frame")

d %>%
  ggplot(aes(x = genus, y = shannon, fill = Exposure)) +
  geom_col(width = 0.5,
           position = position_dodge(0.5)) +
  geom_errorbar(aes(ymin = shannon - sd, ymax = shannon + sd),
                width = 0.2,
                position = position_dodge(0.5)) +
  scale_fill_brewer(palette = "Paired") +
  theme_minimal()
```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
I am running this code (below) to add error bars onto my bar chart, i am trying to to work out the standard deviation (sd) of shannons diversity index
The code works up until the second/third last line

geom_errorbar(aes(ymin=shannon-sd, ymax=shannon+sd), width=0.2,
position=position_dodge(0.9))

This error code keeps coming up

"Error in shannon - sd : non-numeric argument to binary operator"

but this is my data...

Exposure  | genus      | shannon  | sd
----------------------------------------------
Exposed   | Crustacean | 0.000000 | 0.00000000
Exposed   | Mollusc    | 1.199625 | 0.13291129
Exposed   | Seaweed    | 1.513125 | 0.42093822
Sheltered | Crustacean | 0.025500 | 0.07212489
Sheltered | Mollusc    | 1.156750 | 0.26763341
Sheltered | Seaweed    | 1.848125 | 0.27264128

anyone know where im going wrong?

library(ggplot2)
#+++++++++++++++++++++++++
# Function to calculate the mean and the standard deviation
# for each group
#+++++++++++++++++++++++++
# data : a data frame
# varname : the name of a column containing the variable
#to be summariezed
# groupnames : vector of column names to be used as
# grouping variables
data_summary <- function(data, varname, groupnames){
require(plyr)
summary_func <- function(x, col){
c(mean = mean(x[[col]], na.rm=TRUE),
sd = sd(x[[col]], na.rm=TRUE))
}
data_sum<-ddply(data, groupnames, .fun=summary_func,
varname)
data_sum <- rename(data_sum, c("mean" = varname))
return(data_sum)
}
df3 <- data_summary(diversity, varname="shannon",
groupnames=c("Exposure", "genus"))
# Convert dose to a factor variable
df3$genus=as.factor(df3$genus)
head(df3)
p <- ggplot(diversity, aes(x=genus, y=shannon, fill = location)) +
geom_bar(stat="identity", width = 0.5, position=position_dodge()) + theme_minimal() +
geom_errorbar(aes(ymin=shannon-sd, ymax=shannon+sd), width=0.2,
position=position_dodge(0.9))
p + scale_fill_brewer(palette="Paired") + theme_minimal()

Body:
You've shared a bunch of code but it's not totally clear what you're trying to accomplish with it all because most of it doesn't seem to make into the actual plot.

One thing I see that's generally not a good idea is that you define one function (data_summary()) inside another (summary_fun()).

Also your plotting code calls fill = location but it's not clear where location is coming from in your data.

So here's my best guess of what you were going for but please clarify if that's not it:

library(tidyverse)

d <- structure(list(Exposure = c("Exposed", "Exposed", "Exposed", "Sheltered", "Sheltered", "Sheltered"), genus = c("Crustacean", "Mollusc", "Seaweed", "Crustacean", "Mollusc", "Seaweed"), shannon = c(0, 1.199625, 1.513125, 0.0255, 1.15675, 1.848125), sd = c(0, 0.13291129, 0.42093822, 0.07212489, 0.26763341, 0.27264128)), row.names = c(NA, -6L), class = "data.frame")

d %>%
  ggplot(aes(x = genus, y = shannon, fill = Exposure)) +
  geom_col(width = 0.5,
           position = position_dodge(0.5)) +
  geom_errorbar(aes(ymin = shannon - sd, ymax = shannon + sd),
                width = 0.2,
                position = position_dodge(0.5)) +
  scale_fill_brewer(palette = "Paired") +
  theme_minimal()

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
How can I change the labels of the Continue/Cancel buttons in flutter stepper?
Is there any way to change the text labels of the Continue and Cancel Buttons of the stepper in flutter? Stepper seems to be the perfect choice for what I want to do (long form with several "stages") and before I go try to build one from scratch just to get other labels for the buttons I thought I may ask..

Anybody knows if/how thats possible?

答:
I m late for the discussion.
But i have just done it and think it is good to share.
The code is able to control the Text for each step as the code below.
Each step will have difference text, manage to do for 3 steps. If more than that, the code will be quite messy.
Hope it helps someone who is looking for it.</p>
```<code>controlsBuilder: (BuildContext context,
              {VoidCallback onStepContinue, VoidCallback onStepCancel}) {
            return Row(
              children: <Widget>[
                _activeCurrentStep == 0
                    ? TextButton(
                        onPressed: onStepContinue,
                        child: const Text('NEXT'),
                      )
                    : _activeCurrentStep == 1
                        ? Container(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                TextButton(
                                  onPressed: onStepContinue,
                                  child: const Text('NEXT'),
                                ),
                                TextButton(
                                  onPressed: onStepCancel,
                                  child: const Text('BACK'),
                                ),
                              ],
                            ),
                          )
                        : _activeCurrentStep >= 2
                            ? Container(
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    TextButton(
                                      onPressed: onStepContinue,
                                      child: const Text('SAVE'),
                                    ),
                                    TextButton(
                                      onPressed: onStepCancel,
                                      child: const Text('BACK'),
                                    ),
                                  ],
                                ),
                              )
                            : TextButton(
                                onPressed: onStepCancel,
                                child: const Text('BACK'),
                              ),
              ],
            );
          },
</code>```

Body:
I m late for the discussion.
But i have just done it and think it is good to share.
The code is able to control the Text for each step as the code below.
Each step will have difference text, manage to do for 3 steps. If more than that, the code will be quite messy.
Hope it helps someone who is looking for it.

controlsBuilder: (BuildContext context,
              {VoidCallback onStepContinue, VoidCallback onStepCancel}) {
            return Row(
              children: <Widget>[
                _activeCurrentStep == 0
                    ? TextButton(
                        onPressed: onStepContinue,
                        child: const Text('NEXT'),
                      )
                    : _activeCurrentStep == 1
                        ? Container(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                TextButton(
                                  onPressed: onStepContinue,
                                  child: const Text('NEXT'),
                                ),
                                TextButton(
                                  onPressed: onStepCancel,
                                  child: const Text('BACK'),
                                ),
                              ],
                            ),
                          )
                        : _activeCurrentStep >= 2
                            ? Container(
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    TextButton(
                                      onPressed: onStepContinue,
                                      child: const Text('SAVE'),
                                    ),
                                    TextButton(
                                      onPressed: onStepCancel,
                                      child: const Text('BACK'),
                                    ),
                                  ],
                                ),
                              )
                            : TextButton(
                                onPressed: onStepCancel,
                                child: const Text('BACK'),
                              ),
              ],
            );
          },


问:
Windows font issue and how to debug for customer
Recently had a customer send in a ticket complaining that their font has changed (within the week or so).  The font on the site has not changed in probably a decade.  What I suspect is that perhaps a recent windows up that times in line with the change is effecting the font he sees, or, more likely, a setting changed on his end.

the font we use

```<code>font-family: "Helvetica Neue",Helvetica,Arial,sans-serif
</code>```

It is my understanding that Helvetica Neue will likely get replaced by something else on windows since, just from googling, I find that font is not included in windows.

My question is, is there any way I can help debug this on his end to figure out exactly what is going on?  It does make the site difficult to read for this user and I would like to fix it, and also know for sure what I am talking about. I usually try very hard not to just reply with, "looks good on my machine".  Inspecting it shows the same font family as what I posted above.

None of the font options in that css appear to be what is showing.

The one distinguishing trait I can see in the font is the letters de overlap or touch.

This is for web content, the browsers mentioned where most recent Chrome, which I also tested on (verified exact same version numbers) and did not have the issue, and Edge which I do not have.

答:
How to debug: Check whether the specific computer have the Helvetica font installed. You can do this by going to the Fonts settings of windows. To open Font Settings just open windows search and type Font:

Font Settings will show you Available Fonts that are installed in your computer. Type Helvetica in the search bar and see if Helvetica font is installed:

If it's not, you can go and download and install the font on that computer and the problem would be solved.

CSS solution: To avoid this problem from happening in the future, you can include the font's .ttf file in your project and use @font-face to set it as a font on your project.

@font-face {
  font-family: "digital-7";
  font-style: normal;
  src: url("~/assets/fonts/digital-7.ttf");
}
```
<p>You can use it like so:</p>
<pre class="lang-css prettyprint-override"><code>.container{
  font-family: "digital-7";
  font-size: 4em;
  color: black;
}
</code>```

Body:
Recently had a customer send in a ticket complaining that their font has changed (within the week or so).  The font on the site has not changed in probably a decade.  What I suspect is that perhaps a recent windows up that times in line with the change is effecting the font he sees, or, more likely, a setting changed on his end.

the font we use

font-family: "Helvetica Neue",Helvetica,Arial,sans-serif

It is my understanding that Helvetica Neue will likely get replaced by something else on windows since, just from googling, I find that font is not included in windows.

My question is, is there any way I can help debug this on his end to figure out exactly what is going on?  It does make the site difficult to read for this user and I would like to fix it, and also know for sure what I am talking about. I usually try very hard not to just reply with, "looks good on my machine".  Inspecting it shows the same font family as what I posted above.

None of the font options in that css appear to be what is showing.

The one distinguishing trait I can see in the font is the letters de overlap or touch.

This is for web content, the browsers mentioned where most recent Chrome, which I also tested on (verified exact same version numbers) and did not have the issue, and Edge which I do not have.

Body:
How to debug: Check whether the specific computer have the Helvetica font installed. You can do this by going to the Fonts settings of windows. To open Font Settings just open windows search and type Font:

Font Settings will show you Available Fonts that are installed in your computer. Type Helvetica in the search bar and see if Helvetica font is installed:

If it's not, you can go and download and install the font on that computer and the problem would be solved.

CSS solution: To avoid this problem from happening in the future, you can include the font's .ttf file in your project and use @font-face to set it as a font on your project.

@font-face {
  font-family: "digital-7";
  font-style: normal;
  src: url("~/assets/fonts/digital-7.ttf");
}

You can use it like so:

.container{
  font-family: "digital-7";
  font-size: 4em;
  color: black;
}


问:
Reference to an option versus option of a reference
I'm wondering if there's any difference (in terms of optimization) between a function that takes as argument:

fn thing(a: &Option<T>)
```
<p>versus a function that takes as argument:</p>
<pre class="lang-rust prettyprint-override"><code>fn thing(a: Option<&T>)
</code>```

答:
Use Option<&T>

As noted in the comments, Option<&T> is the same size as &T, so there's no real difference between them in terms of calling convention. The &Option<T> has a slight cost that you're forced to follow an indirection before being able to match on the value, but I wouldn't seriously consider a reason for one vs the other except in the most dire of circumstances.

However, the biggest difference is that &Option<T> has an ergonomics problem. Consider the case that I have a T that I want to pass to this function:

```<code>let t: T = ...;
thing(&Some(T));
</code>```

This isn't so bad, but what if I wanted to use my t afterwards? I can't with the above code since it was moved in order to make the Option<T>. I would be forced to do something like this:

```<code>let t: T = ...;
let opt_t = Some(t);
thing(&opt_t );
let t = opt_t.unwrap();
</code>```

Which isn't very nice. Moving the variable itself may also have a non-negligible cost even if I didn't want to use it afterwards. An Option<&T> argument would not have these problems.

Body:
I'm wondering if there's any difference (in terms of optimization) between a function that takes as argument:

fn thing(a: &Option<T>)

versus a function that takes as argument:

fn thing(a: Option<&T>)

Body:
Use Option<&T>

As noted in the comments, Option<&T> is the same size as &T, so there's no real difference between them in terms of calling convention. The &Option<T> has a slight cost that you're forced to follow an indirection before being able to match on the value, but I wouldn't seriously consider a reason for one vs the other except in the most dire of circumstances.

However, the biggest difference is that &Option<T> has an ergonomics problem. Consider the case that I have a T that I want to pass to this function:

let t: T = ...;
thing(&Some(T));

This isn't so bad, but what if I wanted to use my t afterwards? I can't with the above code since it was moved in order to make the Option<T>. I would be forced to do something like this:

let t: T = ...;
let opt_t = Some(t);
thing(&opt_t );
let t = opt_t.unwrap();

Which isn't very nice. Moving the variable itself may also have a non-negligible cost even if I didn't want to use it afterwards. An Option<&T> argument would not have these problems.


问:
Parse String to Jason C# - can't access due to protection level -JObject
Hey i want to parse a String to a Jason Object in C#.

I have found this code but i alltimes get the problem that it means for JObject:
"can't access due to protection level c#"
Its because JObject is Internal in this Framework i think. But i found online so much solution and they tell all to make it like below. I dont know what i make wrong.

```<code>        string APIUrlRandomNameGenerator = "https://api.parser.name/api";
        var json = new WebClient().DownloadString(APIUrlRandomNameGenerator);

        var jobj = new JObject();
        dynamic data = JObject.Parse(json);
        Console.WriteLine(data.id);
        Console.WriteLine(data.first_name);
        Console.WriteLine(data.last_name);
        Console.WriteLine(data.gender);
</code>```

答:
I found the solution.

I was only using the using Newtonsoft.Json.Linq; and i was able to look for the definitions but i it was needed to install the Newtonsoft Paket.

Body:
Hey i want to parse a String to a Jason Object in C#.

I have found this code but i alltimes get the problem that it means for JObject:
"can't access due to protection level c#"
Its because JObject is Internal in this Framework i think. But i found online so much solution and they tell all to make it like below. I dont know what i make wrong.

        string APIUrlRandomNameGenerator = "https://api.parser.name/api";
        var json = new WebClient().DownloadString(APIUrlRandomNameGenerator);

        var jobj = new JObject();
        dynamic data = JObject.Parse(json);
        Console.WriteLine(data.id);
        Console.WriteLine(data.first_name);
        Console.WriteLine(data.last_name);
        Console.WriteLine(data.gender);