问:
ExcelJS can't write to workbook
I am attempting to fetch data from database and create an excel sheet for each user's data. The sheets get created but the data doesn't get written for some reason.

I know NodeJS being async, sometimes you end up sending the file before finishing writing the data to it. However, I console.log each action and they seem to execute in the correct order.

Here is my code and its output. Why does the resulting Excel workbook have empty sheets?

```<code>const createWorkbook = () => {
  return new Promise(resolve => {
    resolve(new excel.Workbook());
  });
}

const getAssemblers = () => {
  return new Promise(async resolve => {
    resolve(await db.models.assembler.findAll())
  });
}

const createWorksheet = (workbook, name) => {
  return new Promise(resolve => {
    resolve(workbook.addWorksheet(name));
  });
};

const getAssemblerData = (id) => {
  return new Promise(async resolve => {
    const assemblyTimes = await db.models.assemblyTime.findAll({
      where: {
        assemblerID: id,
      },
      include: [
        db.models.assembler,
        db.models.item,
      ],
    });

    let assemblyData = [];

    assemblyTimes.forEach((assembly) => {
      assemblyData.push({
        assembler: assembly.assembler.name,
        item: assembly.item.name,
        start: assembly.start,
        end: assembly.end,
        duration: assembly.duration
      });
    });

    resolve(assemblyData);
  })
}

const writeDataToSheet = (worksheet, data) => {
  return new Promise(async resolve => {
    worksheet.columns = [
      { header: 'Assembler', key: 'assembler', width: 30 },
      { header: 'Item', key: 'item', width: 30 },
      { header: 'Start', key: 'start', width: 10 },
      { header: 'End', key: 'end', width: 20 },
      { header: 'Duration', key: 'duration', width: 20 },
    ];
    worksheet.addRows(data)
    resolve();
  });
};

app.get('/download', async (req, res) => {
  try {
    const workbook = await createWorkbook();
    console.log('Created workbook');
    const assemblers = await getAssemblers();
    console.log('Fetched Assemblers');
    console.log(assemblers);

    assemblers.forEach(async (assembler) => {
      const worksheet = await createWorksheet(workbook, assembler.name);
      console.log("Created assembler's worksheet");
      const assemblyData = await getAssemblerData(assembler.id);
      console.log("Fetched assembler's data");
      console.log(assemblyData)
      await writeDataToSheet(worksheet, assemblyData);
      console.log('Written!')
    });

    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      'attachment; filename=assemblyData.xlsx',
    );

    return workbook.xlsx.write(res).then(() => {
      res.status(200).end();
      console.log('Sent!')
    });

  } catch (err) {
    console.error(err);
    res.sendStatus(500);
  }
});
</code>```

Console output:

```<code>Created workbook
Fetched Assemblers
[
  assembler {
    dataValues: { id: 2, name: 'User 1' },
    _previousDataValues: { id: 2, name: 'User 1' },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  assembler {
    dataValues: { id: 3, name: 'User 2' },
    _previousDataValues: { id: 3, name: 'User 2' },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  }
]
Created assembler's worksheet
Created assembler's worksheet
Fetched assembler's data
[
  {
    assembler: 'User 1',
    item: 'Chair',
    start: 2022-02-10T19:18:12.000Z,
    end: 2022-02-10T19:18:14.000Z,
    duration: 2
  },
  {
    assembler: 'User 1',
    item: 'Down Time',
    start: 2022-02-10T19:18:14.000Z,
    end: 2022-02-10T19:18:16.000Z,
    duration: 2
  },
  {
    assembler: 'User 1',
    item: 'Chair',
    start: 2022-02-10T19:18:16.000Z,
    end: 2022-02-10T19:18:20.000Z,
    duration: 4
  },
  {
    assembler: 'User 1',
    item: 'Down Time',
    start: 2022-02-10T19:18:20.000Z,
    end: 2022-02-10T19:18:24.000Z,
    duration: 4
  },
  {
    assembler: 'User 1',
    item: 'Chair',
    start: 2022-02-10T19:18:24.000Z,
    end: 2022-02-10T19:18:29.000Z,
    duration: 5
  }
]
Written!
Fetched assembler's data
[
  {
    assembler: 'User 2',
    item: 'Down Time',
    start: 2022-02-10T19:18:29.000Z,
    end: 2022-02-10T19:18:31.000Z,
    duration: 2
  },
  {
    assembler: 'User 2',
    item: 'Chair',
    start: 2022-02-10T19:18:31.000Z,
    end: 2022-02-10T19:18:35.000Z,
    duration: 4
  },
  {
    assembler: 'User 2',
    item: 'Down Time',
    start: 2022-02-10T19:18:36.000Z,
    end: 2022-02-10T19:18:39.000Z,
    duration: 3
  },
  {
    assembler: 'User 2',
    item: 'Chair',
    start: 2022-02-10T19:18:39.000Z,
    end: 2022-02-10T19:18:46.000Z,
    duration: 7
  },
  {
    assembler: 'User 2',
    item: 'Down Time',
    start: 2022-02-10T19:18:46.000Z,
    end: 2022-02-10T19:18:53.000Z,
    duration: 7
  },
  {
    assembler: 'User 2',
    item: 'Chair',
    start: 2022-02-10T19:18:53.000Z,
    end: 2022-02-10T19:18:58.000Z,
    duration: 5
  }
]
Written!
Sent!
</code>```

答:
try using for..of instead of .forEach:

```<code>for (const assembler of assemblers) {
    const worksheet = await createWorksheet(workbook, assembler.name);
    console.log("Created assembler's worksheet");
    const assemblyData = await getAssemblerData(assembler.id);
    console.log("Fetched assembler's data");
    console.log(assemblyData)
    await writeDataToSheet(worksheet, assemblyData);
    console.log('Written!')
}
</code>```

See more here: Using async/await with a forEach loop

Title: ExcelJS can't write to workbook

Body:
I am attempting to fetch data from database and create an excel sheet for each user's data. The sheets get created but the data doesn't get written for some reason.

I know NodeJS being async, sometimes you end up sending the file before finishing writing the data to it. However, I console.log each action and they seem to execute in the correct order.

Here is my code and its output. Why does the resulting Excel workbook have empty sheets?

const createWorkbook = () => {
  return new Promise(resolve => {
    resolve(new excel.Workbook());
  });
}

const getAssemblers = () => {
  return new Promise(async resolve => {
    resolve(await db.models.assembler.findAll())
  });
}

const createWorksheet = (workbook, name) => {
  return new Promise(resolve => {
    resolve(workbook.addWorksheet(name));
  });
};

const getAssemblerData = (id) => {
  return new Promise(async resolve => {
    const assemblyTimes = await db.models.assemblyTime.findAll({
      where: {
        assemblerID: id,
      },
      include: [
        db.models.assembler,
        db.models.item,
      ],
    });

    let assemblyData = [];

    assemblyTimes.forEach((assembly) => {
      assemblyData.push({
        assembler: assembly.assembler.name,
        item: assembly.item.name,
        start: assembly.start,
        end: assembly.end,
        duration: assembly.duration
      });
    });

    resolve(assemblyData);
  })
}

const writeDataToSheet = (worksheet, data) => {
  return new Promise(async resolve => {
    worksheet.columns = [
      { header: 'Assembler', key: 'assembler', width: 30 },
      { header: 'Item', key: 'item', width: 30 },
      { header: 'Start', key: 'start', width: 10 },
      { header: 'End', key: 'end', width: 20 },
      { header: 'Duration', key: 'duration', width: 20 },
    ];
    worksheet.addRows(data)
    resolve();
  });
};

app.get('/download', async (req, res) => {
  try {
    const workbook = await createWorkbook();
    console.log('Created workbook');
    const assemblers = await getAssemblers();
    console.log('Fetched Assemblers');
    console.log(assemblers);

    assemblers.forEach(async (assembler) => {
      const worksheet = await createWorksheet(workbook, assembler.name);
      console.log("Created assembler's worksheet");
      const assemblyData = await getAssemblerData(assembler.id);
      console.log("Fetched assembler's data");
      console.log(assemblyData)
      await writeDataToSheet(worksheet, assemblyData);
      console.log('Written!')
    });

    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      'attachment; filename=assemblyData.xlsx',
    );

    return workbook.xlsx.write(res).then(() => {
      res.status(200).end();
      console.log('Sent!')
    });

  } catch (err) {
    console.error(err);
    res.sendStatus(500);
  }
});

Console output:

Created workbook
Fetched Assemblers
[
  assembler {
    dataValues: { id: 2, name: 'User 1' },
    _previousDataValues: { id: 2, name: 'User 1' },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  assembler {
    dataValues: { id: 3, name: 'User 2' },
    _previousDataValues: { id: 3, name: 'User 2' },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  }
]
Created assembler's worksheet
Created assembler's worksheet
Fetched assembler's data
[
  {
    assembler: 'User 1',
    item: 'Chair',
    start: 2022-02-10T19:18:12.000Z,
    end: 2022-02-10T19:18:14.000Z,
    duration: 2
  },
  {
    assembler: 'User 1',
    item: 'Down Time',
    start: 2022-02-10T19:18:14.000Z,
    end: 2022-02-10T19:18:16.000Z,
    duration: 2
  },
  {
    assembler: 'User 1',
    item: 'Chair',
    start: 2022-02-10T19:18:16.000Z,
    end: 2022-02-10T19:18:20.000Z,
    duration: 4
  },
  {
    assembler: 'User 1',
    item: 'Down Time',
    start: 2022-02-10T19:18:20.000Z,
    end: 2022-02-10T19:18:24.000Z,
    duration: 4
  },
  {
    assembler: 'User 1',
    item: 'Chair',
    start: 2022-02-10T19:18:24.000Z,
    end: 2022-02-10T19:18:29.000Z,
    duration: 5
  }
]
Written!
Fetched assembler's data
[
  {
    assembler: 'User 2',
    item: 'Down Time',
    start: 2022-02-10T19:18:29.000Z,
    end: 2022-02-10T19:18:31.000Z,
    duration: 2
  },
  {
    assembler: 'User 2',
    item: 'Chair',
    start: 2022-02-10T19:18:31.000Z,
    end: 2022-02-10T19:18:35.000Z,
    duration: 4
  },
  {
    assembler: 'User 2',
    item: 'Down Time',
    start: 2022-02-10T19:18:36.000Z,
    end: 2022-02-10T19:18:39.000Z,
    duration: 3
  },
  {
    assembler: 'User 2',
    item: 'Chair',
    start: 2022-02-10T19:18:39.000Z,
    end: 2022-02-10T19:18:46.000Z,
    duration: 7
  },
  {
    assembler: 'User 2',
    item: 'Down Time',
    start: 2022-02-10T19:18:46.000Z,
    end: 2022-02-10T19:18:53.000Z,
    duration: 7
  },
  {
    assembler: 'User 2',
    item: 'Chair',
    start: 2022-02-10T19:18:53.000Z,
    end: 2022-02-10T19:18:58.000Z,
    duration: 5
  }
]
Written!
Sent!

Body:
try using for..of instead of .forEach:

for (const assembler of assemblers) {
    const worksheet = await createWorksheet(workbook, assembler.name);
    console.log("Created assembler's worksheet");
    const assemblyData = await getAssemblerData(assembler.id);
    console.log("Fetched assembler's data");
    console.log(assemblyData)
    await writeDataToSheet(worksheet, assemblyData);
    console.log('Written!')
}

See more here: Using async/await with a forEach loop


来源: stackexchange

问:
Exclude array data from foreach loop
I have a payment function that emails me whenever a transaction occurs, the issue is it emails me too much data, and not all of it is relevant. The payment itself is processed by Authorize API (which is also whats returning this data).

```<code>function sent_mail($data = array()) {
    $out = "";
    foreach ($data as $k => $value) {
        if (is_array($value)) {
            foreach ($value as $key => $v) {
                $out .= ucwords($key) . ' Name : ' . $v . "<br/>";
            }
        } else {
            $out .= ucwords($k) . ' : ' . $value . "<br/>";
        }
    }
    $msg = "<h2><strong>Receipt Of Payment</strong></h2>" . "<br/><br/>";
    $msg .= "$out";

    $to = 'myemail@mycompany.com';
    $subject = 'New Payment';
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=iso-8859-1\n";
    @mail($to, $subject, $msg, $headers);
}
</code>```

The email I get, includes these fields:

DataValue, DataDescriptor, InvoiceID, Amount, Item_name, Item_Desc, FirstName, LastName, Email, Website, Country, Zip, Terms, TransID, Card_Holder

Where as, the only data I need is

InvoiceID, Amount, Item_name, FirstName, LastName, Email, Website

I've not sure how to limit this, create a skip?

答:
In a loop you can use the continue statement to immediately go to the next iteration of that loop. That means you can create a condition to skip over the loop that adds data to your email if the key does not match one of the keys you want to include.

if (!in_array($k, ['InvoiceID', 'Amount', 'Item_name', 'FirstName', 'LastName', 'Email', 'Website'])) {
  continue;
}
```

ContentLicense: CC BY-SA 4.0

Title: Exclude array data from foreach loop

Body:
I have a payment function that emails me whenever a transaction occurs, the issue is it emails me too much data, and not all of it is relevant. The payment itself is processed by Authorize API (which is also whats returning this data).

function sent_mail($data = array()) {
    $out = "";
    foreach ($data as $k => $value) {
        if (is_array($value)) {
            foreach ($value as $key => $v) {
                $out .= ucwords($key) . ' Name : ' . $v . "
";
            }
        } else {
            $out .= ucwords($k) . ' : ' . $value . "
";
        }
    }
    $msg = "
Receipt Of Payment
" . "

";
    $msg .= "$out";

    $to = 'myemail@mycompany.com';
    $subject = 'New Payment';
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=iso-8859-1\n";
    @mail($to, $subject, $msg, $headers);
}

The email I get, includes these fields:

DataValue, DataDescriptor, InvoiceID, Amount, Item_name, Item_Desc, FirstName, LastName, Email, Website, Country, Zip, Terms, TransID, Card_Holder

Where as, the only data I need is

InvoiceID, Amount, Item_name, FirstName, LastName, Email, Website

I've not sure how to limit this, create a skip?


问:
'No type was found that matches the controller named' error
I have an Asp.Net Web Forms app that I am trying to add a webapi controller to. When I call the URI for the controller, I get the 'No type was found that matches the controller named' error. I have read through all the threads here and on other sites but no resolution as yet.

My controller class has the following:

```<code>`public class RelationalController : ApiController{

    [System.Web.Http.ActionName("InitializeClient")]
    [System.Web.Http.HttpPost]
    public Dictionary<string, object>
InitializeClient(Dictionary<string, object> jsonResult)
    {
        this.BindData();
        return pivotClient.GetJsonData(jsonResult["action"].ToString(),
ProductSales.GetSalesData(), jsonResult["clientParams"].ToString());
    }
}`
</code>```

I have the following setup in Global.asax.cs:

`

```<code>protected void Application_Start(Object sender, EventArgs e)
        {
            RegisterRoutes();
        }

        protected static void RegisterRoutes()
        {
            RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
            RouteTable.Routes.MapHttpRoute(
                name: "Relational",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { controller = "Relational", id =
    System.Web.Http.RouteParameter.Optional }
            );
        }`
</code>```

When I test the call in Postman I get the following:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:57802/api/Relational/InitializeClient/'.","MessageDetail":"No type was found that matches the controller named 'Relational'."}

I've verified I only have one controller named RelationalController. It's the only controller defined in the app. It's in a folder call api at the root of my app.

Does anyone know what might be the issue, or can you suggest some ways to troubleshoot further?

答:
you can try attribute routing. Add  MapMvcAttributeRoutes()

```<code>public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: “Default”,
        url: “api/{controller}/{action}/{id}”,
        defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
    );
}
</code>```

and change the action

```<code>[HttpPost("~/api/Relational/InitializeClient")]
public Dictionary<string, object> InitializeClient(Dictionary<string, object> jsonResult)
</code>```

Body:
I have an Asp.Net Web Forms app that I am trying to add a webapi controller to. When I call the URI for the controller, I get the 'No type was found that matches the controller named' error. I have read through all the threads here and on other sites but no resolution as yet.

My controller class has the following:

`public class RelationalController : ApiController{

    [System.Web.Http.ActionName("InitializeClient")]
    [System.Web.Http.HttpPost]
    public Dictionary<string, object>
InitializeClient(Dictionary<string, object> jsonResult)
    {
        this.BindData();
        return pivotClient.GetJsonData(jsonResult["action"].ToString(),
ProductSales.GetSalesData(), jsonResult["clientParams"].ToString());
    }
}`

I have the following setup in Global.asax.cs:

`

protected void Application_Start(Object sender, EventArgs e)
        {
            RegisterRoutes();
        }

        protected static void RegisterRoutes()
        {
            RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
            RouteTable.Routes.MapHttpRoute(
                name: "Relational",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { controller = "Relational", id =
    System.Web.Http.RouteParameter.Optional }
            );
        }`

When I test the call in Postman I get the following:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:57802/api/Relational/InitializeClient/'.","MessageDetail":"No type was found that matches the controller named 'Relational'."}

I've verified I only have one controller named RelationalController. It's the only controller defined in the app. It's in a folder call api at the root of my app.

Does anyone know what might be the issue, or can you suggest some ways to troubleshoot further?

Body:
you can try attribute routing. Add  MapMvcAttributeRoutes()

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: “Default”,
        url: “api/{controller}/{action}/{id}”,
        defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
    );
}

and change the action

[HttpPost("~/api/Relational/InitializeClient")]
public Dictionary<string, object> InitializeClient(Dictionary<string, object> jsonResult)


问:
"Git Bash here" isn't working when right clicking
I don't know, how that happened but before today I could right click on any folder and there would be and an option Git Bash here. But today I dont have that option. Anyone knows how to get that back?

答: Had the same issue , realized that previously right clicking anywhere or inside the folder the Option would show but now I had to select or highlight the folder and then right_click for the option to show.</p>


问:
Create ID over an abnormal sequence
I have the following code that samples 1 row 5 times, 2 rows 5 times, 3 rows 5 times and so on..
After running the lapply and converting it to a dataframe to make comparisons I need a way to alter the ID variable to act as my groups. So rows 1:5 of "want" would be "group 1", rows 6:15 would be "group 2", 16:30 would be "group 3" and so on...
These are the groupings because group one only has one replicate of each number in the ID column, group 2 has two replicates, group 3 has 3 replicates and so on.

Code

```<code>iris<- iris

select_rows <- 1:4
n_times <- 5
inds <- nrow(iris)

result <- lapply(select_rows, function(x)
  replicate(n_times, iris[sample(inds, x), ], simplify = FALSE))

want<- bind_rows(result, .id = 'source')
View(want)
</code>```

Thinking about running an ANOVA on each column for example, the ID column would not provide sufficient groupings of observations.
I suppose I could use a combo of ifelse and mutate to manually go through and assign the rows to certain groups, but I hope to avoid this as I will need to do this for several varying dataframes.
I also tried the following code to assign groups over a sequence, but realized it wouldn't work because the numbers of observations in each group are not the same:

```<code>final<- want %>% mutate(Group = rep(seq(1,ceiling(nrow(want)/5)),each = 5))
</code>```

Any help would be appreciated.

答:
Use the times argument to rep to get five 1's, ten 2's, fifteen 3's, etc.

```<code>dat$id <- rep(1:3, times=1:3*5)
</code>```

Title: Create ID over an abnormal sequence

Body:
I have the following code that samples 1 row 5 times, 2 rows 5 times, 3 rows 5 times and so on..
After running the lapply and converting it to a dataframe to make comparisons I need a way to alter the ID variable to act as my groups. So rows 1:5 of "want" would be "group 1", rows 6:15 would be "group 2", 16:30 would be "group 3" and so on...
These are the groupings because group one only has one replicate of each number in the ID column, group 2 has two replicates, group 3 has 3 replicates and so on.

Code

iris<- iris

select_rows <- 1:4
n_times <- 5
inds <- nrow(iris)

result <- lapply(select_rows, function(x)
  replicate(n_times, iris[sample(inds, x), ], simplify = FALSE))

want<- bind_rows(result, .id = 'source')
View(want)

Thinking about running an ANOVA on each column for example, the ID column would not provide sufficient groupings of observations.
I suppose I could use a combo of ifelse and mutate to manually go through and assign the rows to certain groups, but I hope to avoid this as I will need to do this for several varying dataframes.
I also tried the following code to assign groups over a sequence, but realized it wouldn't work because the numbers of observations in each group are not the same:

final<- want %>% mutate(Group = rep(seq(1,ceiling(nrow(want)/5)),each = 5))

Any help would be appreciated.

Body:
Use the times argument to rep to get five 1's, ten 2's, fifteen 3's, etc.

dat$id <- rep(1:3, times=1:3*5)


问:
Is if(A | B) always faster than if(A || B)?
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

```<code>void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}
</code>```

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

答:
So the question is why don't we always use | instead of || in branches?

In my little mind three reasons, but that might be only me.

First and most: all code tends to be read multiple times more often than it is written. So, in the example you have an array of ints with value either zero or 1. What the code really is meant to do is hidden to the reader. It might be clear to the original writer exactly what is supposed to be done, but years later, and after adding lots and lots of code lines it is probably anyones guess. In my world use what shows the intended comparison, it either is a bit comparison or a logical one. It should not be both.

Secondly: does the performance gain really matter? The example basically does nothing and could be coded a lot more efficient. Not? Well don't create the array in the first place, what the code does now is simply to check the quality of the rand function. The optimization is an example where a better analysis of the problem probably would give a much larger gain.

Third: a different compiler or a different processor will probably change the relative speeds. Now, what you are doing here is applying your knowledge of the internals of the current compiler and current processor. Next version of compiler and processor might turn the question around totally. You really cannot know. And we all know that the only way to know if an optimization actually will be quicker is by testing, which this very specific example has done.

So, if, for some reason, getting the very last bit of efficiency out of the code is worth it I would mark the choice as a "hack". I would probably include a macro with something like "DO_PERFORMANCE_HACKS" and have two versions of the code, one with | and one with  || and commenting what the intention is. By changing the macro it will be possible for next readers to see what and where the hack is, and in the future may elect to not compile them.

Body:
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?


问:
Converting a int to a BCD byte array
I want to convert an int to a byte[2] array using BCD.

The int in question will come from DateTime representing the Year and must be converted to two bytes.

Is there any pre-made function that does this or can you give me a simple way of doing this?

example:

```<code>int year = 2010
</code>```

would output:

```<code>byte[2]{0x20, 0x10};
</code>```

答:
maybe a simple parse function containing this loop</p>

```<code>i=0;
while (id>0)
{
    twodigits=id%100; //need 2 digits per byte
    arr[i]=twodigits%10 + twodigits/10*16;  //first digit on first 4 bits second digit shifted with 4 bits
    id/=100;

    i++;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Converting a int to a BCD byte array

Body:
I want to convert an int to a byte[2] array using BCD.

The int in question will come from DateTime representing the Year and must be converted to two bytes.

Is there any pre-made function that does this or can you give me a simple way of doing this?

example:

int year = 2010

would output:

byte[2]{0x20, 0x10};

Body:
maybe a simple parse function containing this loop

i=0;
while (id>0)
{
    twodigits=id%100; //need 2 digits per byte
    arr[i]=twodigits%10 + twodigits/10*16;  //first digit on first 4 bits second digit shifted with 4 bits
    id/=100;

    i++;
}

ContentLicense: CC BY-SA 3.0


问:
PHP is not update page from formdata
My goal is to get the value of a selector on 1 page. I want to
have a user select a year and update the page when selected a year.
Without the $_GET function.

I will demonstrate it with steps, to understand it a bit more.

Step 1: This is the select element that the user is going to press on a year The
selector

Step 2: There should be an echo what the user has selected. For example; I choose 2019 > there should be a echo somewhere which prints 2019.

This is getData.php

```<code><?php
echo file_get_contents('php://input');

echo json_decode($_POST["year"]);

echo $_POST["year"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/chartSelector.js" defer></script>
</head>
<body>
<div>
  <select name="jaarKiezer" id="jaarKiezer" onchange="changeData()">
    <option selected disabled>Choose a year</option>
    <option value="2019">2019</option>
    <option value="2020">2020</option>
    <option value="2021">2021</option>
  </select>
</div>
</body>
</html>
</code>```

This is chartSelector.js

```<code>console.log("connected with js");
function changeData() {
    let yearJS = document.getElementById("jaarKiezer").value;
    console.log("changed to " + yearJS);
    getData(yearJS);
}

function getData(yearJS) {
    let formData = new FormData();
    formData.append("year", yearJS);
    fetch("../getData.php", {
        "body": formData,
        "method": "POST"
    }).catch(error => console.error(error));
}

</code>```

In the
network tab on preview you see its working. The problem comes when I want to post the form data into php, on the 'live' page
nothing happens. Only 2 errors from getData.php: Undefined array key "year".

Some images to understand it a bit more:

The network tab itself: Network tab

The payload: Payload

The preview: Preview

I've tried:

AJAX

Using the JSON.stringify(formData) function.

Using Headers (Like: header(Content-Type: application/json)).

Note: I'm using php server from the vscode extensions

答:
You have two distinct problems here.

A fundamental misunderstanding of how Ajax works

The browser makes an HTTP request. It gets an HTML document and renders it in the viewport.

The page contains some JavaScript which tells it to make a new HTTP request. The response is returned to JavaScript for further processing.

You don't do any further processing so the only effect you see is in the Network tab of the browser's developer tools.

The request does not travel back in time, replace the previous request for the page to display, and change the page displayed.

If you want to replace the entire page with a new one: Use a regular form submission. Do not use Ajax.

If you want to do something with the response to the Ajax request, then you need to write JavaScript that does that something.

```<code>async function getData(yearJS) {
    let formData = new FormData();
    formData.append("year", yearJS);
    try {
        const response = await fetch("../getData.php", {
            "body": formData,
            "method": "POST"
        });
        const html = await response.text();
        console.log(html); // Do something with the HTML more useful than logging it.
    } catch (error) {
        console.log(error);
    }
}
</code>```

You aren't dealing with JSON

FormData objects are converted into multipart form data request bodies, not JSON.

Remove:

```<code>echo file_get_contents('php://input');

echo json_decode($_POST["year"]);
</code>```

PHP will parse multipart form data request bodies and populate $_POST and $_FILES with the contents automatically.

Title: PHP is not update page from formdata

Body:
My goal is to get the value of a selector on 1 page. I want to
have a user select a year and update the page when selected a year.
Without the $_GET function.

I will demonstrate it with steps, to understand it a bit more.

Step 1: This is the select element that the user is going to press on a year The
selector

Step 2: There should be an echo what the user has selected. For example; I choose 2019 > there should be a echo somewhere which prints 2019.

This is getData.php

<?php
echo file_get_contents('php://input');

echo json_decode($_POST["year"]);

echo $_POST["year"];
?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

  <select name="jaarKiezer" id="jaarKiezer" onchange="changeData()">
    <option selected disabled>Choose a year</option>
    <option value="2019">2019</option>
    <option value="2020">2020</option>
    <option value="2021">2021</option>
  </select>

This is chartSelector.js

console.log("connected with js");
function changeData() {
    let yearJS = document.getElementById("jaarKiezer").value;
    console.log("changed to " + yearJS);
    getData(yearJS);
}

function getData(yearJS) {
    let formData = new FormData();
    formData.append("year", yearJS);
    fetch("../getData.php", {
        "body": formData,
        "method": "POST"
    }).catch(error => console.error(error));
}

In the
network tab on preview you see its working. The problem comes when I want to post the form data into php, on the 'live' page
nothing happens. Only 2 errors from getData.php: Undefined array key "year".

Some images to understand it a bit more:

The network tab itself: Network tab

The payload: Payload

The preview: Preview

I've tried:

AJAX

Using the JSON.stringify(formData) function.

Using Headers (Like: header(Content-Type: application/json)).

Note: I'm using php server from the vscode extensions

Body:
You have two distinct problems here.

A fundamental misunderstanding of how Ajax works

The browser makes an HTTP request. It gets an HTML document and renders it in the viewport.

The page contains some JavaScript which tells it to make a new HTTP request. The response is returned to JavaScript for further processing.

You don't do any further processing so the only effect you see is in the Network tab of the browser's developer tools.

The request does not travel back in time, replace the previous request for the page to display, and change the page displayed.

If you want to replace the entire page with a new one: Use a regular form submission. Do not use Ajax.

If you want to do something with the response to the Ajax request, then you need to write JavaScript that does that something.

async function getData(yearJS) {
    let formData = new FormData();
    formData.append("year", yearJS);
    try {
        const response = await fetch("../getData.php", {
            "body": formData,
            "method": "POST"
        });
        const html = await response.text();
        console.log(html); // Do something with the HTML more useful than logging it.
    } catch (error) {
        console.log(error);
    }
}

You aren't dealing with JSON

FormData objects are converted into multipart form data request bodies, not JSON.

Remove:

echo file_get_contents('php://input');

echo json_decode($_POST["year"]);

PHP will parse multipart form data request bodies and populate $_POST and $_FILES with the contents automatically.


问:
How to use condition for lambda environment variables
I am writing a CloudFormation template. My use case is to pass different values for AWS lambda environment.

```<code>   Environment:
    Variables:
      databaseName: lambda-dev
      databaseUser: admin-dev
      databaseName: lambda-prod
      databaseUser: admin-prod
</code>```

I want to keep a condition in environment variables like if(env==dev) then use these values, if (env==prod) then use last two.

答:
The way to do this is with a mapping, not with conditions. Something like this:

```<code>Parameters:
  Environment:
    Type: String
    Default: dev
    AllowedValues:
      - dev
      - prod
    Description: Enter environment (dev or prod)

Mappings:
  DatabaseMap:
    dev:
      name: "lambda-dev"
      user: "admin-dev"
    prod:
      name: "lambda-prod"
      user: "admin-prod"
</code>```

And later, to use the mapping to retrieve the database name associated with the given environment:

```<code>!FindInMap
  - DatabaseMap
  - !Ref Environment
  - name
</code>```

Body:
I am writing a CloudFormation template. My use case is to pass different values for AWS lambda environment.

   Environment:
    Variables:
      databaseName: lambda-dev
      databaseUser: admin-dev
      databaseName: lambda-prod
      databaseUser: admin-prod

I want to keep a condition in environment variables like if(env==dev) then use these values, if (env==prod) then use last two.

Body:
The way to do this is with a mapping, not with conditions. Something like this:

Parameters:
  Environment:
    Type: String
    Default: dev
    AllowedValues:
      - dev
      - prod
    Description: Enter environment (dev or prod)

Mappings:
  DatabaseMap:
    dev:
      name: "lambda-dev"
      user: "admin-dev"
    prod:
      name: "lambda-prod"
      user: "admin-prod"

And later, to use the mapping to retrieve the database name associated with the given environment:

!FindInMap
  - DatabaseMap
  - !Ref Environment
  - name


问:
What's the point of Raku's 'mod' operator?
I previously incorrectly thought that the % operator returned the remainder and the mod operator returned the modulus (the remainder and modulus are the same when the operands are both positive or both negative but differ when one operand is positive and the other is negative.  Compare Raket's remainder and modulo functions).

However, that's not correct at all – both % and mod return the modulus; neither return the remainder.  In fact, it looks like mod will always return exactly the same value as % would have, if called with the same arguments.  As far as I can tell, the only difference is that % can be called with non-integer arguments, whereas mod throws an exception if called with anything other than Int:D or int.

So, what's the point of mod?  Is there some performance gain from using it (maybe by saving the optimizer some specialization work?) or is there some other difference I'm missing?

答:
TL;DR My takeaway from a quick skim of sources is that % is (supposed to be) the rational or generic modulus op, whereas mod is a dedicated integer modulus op. For some inputs they yield the same result.

The rest of this answer just references the sources I looked at.

Doc

mod:

Integer modulo operator. Returns the remainder of an integer modulo operation.

%:

Modulo operator. Coerces to Numeric first.

Generally the following identity holds:

```<code>my ($x, $y) = 1,2;
$x % $y == $x - floor($x / $y) * $y
</code>```

roast

Search of roast for modulus lists just S03-operators/arith.t. Leads to:

infix:<%> should return Rat when it can.

"TimToady thinks modmap (or whatever we decide to call it) would be a useful addition to the language". (Off topic but interesting.)

S03

infix:<%>, modulo

coerces ... then calculates the remainder ... defined as:

$x % $y == $x - floor($x / $y) * $y

If both operands are of integer or rational type, the operator returns the corresponding Rat value (except when the result does not fit into a Rat, as detailed in S02).

infix:<mod>, integer modulo

Dispatches to the infix:<mod> multi most appropriate to the operand types, returning a value of the same type. Not coercive, so fails on differing types.

This should preserve the identity:

$x mod $y == $x - ($x div $y) * $y

IRC

Search of #perl6 for mod integer.

Rakudo source code

infix:<%>

infix:<mod>

Body:
TL;DR My takeaway from a quick skim of sources is that % is (supposed to be) the rational or generic modulus op, whereas mod is a dedicated integer modulus op. For some inputs they yield the same result.

The rest of this answer just references the sources I looked at.

Doc

mod:

Integer modulo operator. Returns the remainder of an integer modulo operation.

%:

Modulo operator. Coerces to Numeric first.

Generally the following identity holds:

my ($x, $y) = 1,2;
$x % $y == $x - floor($x / $y) * $y

roast

Search of roast for modulus lists just S03-operators/arith.t. Leads to:

infix:<%> should return Rat when it can.

"TimToady thinks modmap (or whatever we decide to call it) would be a useful addition to the language". (Off topic but interesting.)

S03

infix:<%>, modulo

coerces ... then calculates the remainder ... defined as:

$x % $y == $x - floor($x / $y) * $y

If both operands are of integer or rational type, the operator returns the corresponding Rat value (except when the result does not fit into a Rat, as detailed in S02).

infix:<mod>, integer modulo

Dispatches to the infix:<mod> multi most appropriate to the operand types, returning a value of the same type. Not coercive, so fails on differing types.

This should preserve the identity:

$x mod $y == $x - ($x div $y) * $y

IRC

Search of #perl6 for mod integer.

Rakudo source code

infix:<%>

infix:<mod>


问:
What is easiest way to send message to API from Camunda?
I would like to use easiest way to send API message from Camunda. What is the easiest way? I can't find useful source.</p>

答: Use client rest to send the payload (below)


问:
How to validate and exclude data at ingestion time for Azure Data Explorer
I am sending data from web client to event hub and then ingest into Azure Data Explorer.
The event generated by web client has a timestamp field, and when event hub receives the event, it will add a EventEnqueuedUtcTime field. Both are UTC timestamp.

Is there a way to compare the the two timestamps at Data Explorer ingestion, and exclude the data if the time difference is more than a certain vaule?

for example, if EventEnqueuedUtcTime - timestamp > x minutes, then we don't ingest this event into Data Explorer?

答:
Example how ingestion time works!

Let’s say you have event table with field
.create table events (source: string)

And orders table with fields
.create table orders (source: string, LastModifiedDate: datetime)

Now you are copying events table source to orders table but, you want to generate your last modified date on orders table as ingestion time.

Steps:

Create events table - .create table events (source: string)

Create orders table - .create table orders (source: string,    LastModifiedDate: datetime)

Create function to extend lastmodified in events table
.create function eventRecordsExpand() { events | extends LastModifiedDate = ingestiontime()}

Alter your orders table to update policy
.alter table orders policy update @‘[{“source”: “events”, “query”: “eventRecordsExpand()“, “isEnabled”: “True”}]’

This will ingest records from events table to orders table with LastModifiedDate from orders table as ingestion time.


问:
How to display HTML content from API response on HTML page?
I sent a fetch request to an API which responded with:

<Game Gameid="12345">
    <name primary="true">Apple</name>
    <year>2011</year>
</Game>```
</div>
</div>
</p>
<p>Just wondering how I would display this data on my HTML page. I'm assuming I would need to process this with javascript or something.</p>
<p>Here is my current javascript:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>fetch(url)
  .then((response) => {

      return response.json();
  })
  .then(data => {
    console.log(data);
  })</code>```

Just want the name and year displayed in a Div or something

答:
Here is a small script demonstrating how to extract data from an XML string:

const xml=`<Game Gameid="12345">
    <name primary="true">Apple</name>
    <year>2011</year>
</Game>`;

const dom=(new DOMParser()).parseFromString(xml,"text/xml");
const game=dom.querySelector("*");
// console.log(game.tagName,game.getAttribute("Gameid"));
const data = [...game.children].reduce((a,t)=>(a[t.tagName]=t.textContent,a), {});

document.querySelector("div").textContent=`The name is ${data.name} and the year is ${data.year}.`;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Body:
I sent a fetch request to an API which responded with:

<Game Gameid="12345">
    <name primary="true">Apple</name>
    <year>2011</year>
</Game>

Just wondering how I would display this data on my HTML page. I'm assuming I would need to process this with javascript or something.

Here is my current javascript:

fetch(url)
  .then((response) => {

      return response.json();
  })
  .then(data => {
    console.log(data);
  })

Just want the name and year displayed in a Div or something

Body:
Here is a small script demonstrating how to extract data from an XML string:

const xml=`<Game Gameid="12345">
    <name primary="true">Apple</name>
    <year>2011</year>
</Game>`;

const dom=(new DOMParser()).parseFromString(xml,"text/xml");
const game=dom.querySelector("*");
// console.log(game.tagName,game.getAttribute("Gameid"));
const data = [...game.children].reduce((a,t)=>(a[t.tagName]=t.textContent,a), {});

document.querySelector("div").textContent=`The name is ${data.name} and the year is ${data.year}.`;

<div></div>


问:
How do physics engines model angular velocity and angular acceleration (in 3D)
I have been looking around for answers to this question and I can't find a straight answer.
It seems the word online is that angular velocity is stored as a vector, where the direction is the axis of rotation and the length is the rate of rotation.
That makes some sense but it completely neglects how you actually work with it.
So there are 2 critical operations that need to be done.

Apply angular acceleration (how do you add a angular acceleration (presumably in the same data type) to your angular velocity?)

Calculate the velocity of a point on the rigidbody taking into account both angular and linear velocity.

I have looked at how physics engines like bullet handle it but the math is very confusing and some of the operator overloads seem to hide what is actually going on.

Answers are preferred in C++ or C but as long as the math is clear anything works.

答:
I'd suggest reading the paper An Introduction to Physically Based Modeling: Rigid Body Simulation I—Unconstrained Rigid Body Dynamics by David Baraff.

In the paper you have the model of the angular momentum L of the rigid body and the angular velocity ω. But it does not use the angular acceleration, since the angular momentum depends on the torque being applied to it. You'll also need to define your own Inertia tensor I(t) that "describes how the mass in a body is distributed relative to the body’s center of mass." In the paper there's also an implementation of the whole model (mass, forces, torque, angular momentum) in C language.

This repo also has an implementation (in C) of the paper: RiBOEngine

Source: https://www.cs.cmu.edu/~baraff/sigcourse/notesd1.pdf

In the bullet3 physics engine, the implementation is very similar to the paper describe above. If you look in the btRigidBody::integrateVelocities() method, you'll find out that in order to calculate the angular velocity you need the tensor and the torque to compute it.


Title: Content from a string into a array

Body:
I have a string that needs to be put sorted(not in the high to low way), the string is set to separate each number with a comma and after every third number a space:

26,2496,1492252306 1049,99,68353132 860,99,59587920 4717,99,43863427 807,99,67243688 1382,99,37865117 1088,99,14810482 95,99,67711274 5,99,200000000 3310,99,25639438 75,99,157217334 1923,99,29678736 48,99,118806349 133,99,35055345 563,99,21098356 3410,99,17805574 47,99,62821143 2504,99,14821240 5,99,200000000 3076,99,19425499 474,99,31321799 3983,99,16825678 17826,99,13768252 1129,99,17249030 5393,99,14082021 338,120,137201472 2850,1944 -1,-1 -1,-1 -1,-1 -1,-1 4509,3988 3863,3987 2632,4148 5790,4105 -1,-1 -1,-1

i need to create some sort of association for each of the 3 numbers. kinda like a something along the lines of 2d array and a dictionary. any suggestion?

Body:
Assuming your string is saved in a variable named "myNumbers", do this:

NSString *myNumbers = @"26,2496,1492252306 1049,99,68353132 860,99,59587920 4717,99,43863427 807,99,67243688 1382,99,37865117 1088,99,14810482 95,99,67711274 5,99,200000000 3310,99,25639438 75,99,157217334 1923,99,29678736 48,99,118806349 133,99,35055345 563,99,21098356 3410,99,17805574 47,99,62821143 2504,99,14821240 5,99,200000000 3076,99,19425499 474,99,31321799 3983,99,16825678 17826,99,13768252 1129,99,17249030 5393,99,14082021 338,120,137201472 2850,1944 -1,-1 -1,-1 -1,-1 -1,-1 4509,3988 3863,3987 2632,4148 5790,4105 -1,-1 -1,-1";

NSArray *triples = [myNumbers componentsSeparatedByString:@" "];

NSMutableArray *matrix = [[NSMutableArray alloc] init];

for (NSString *triple in triples) {
    [matrix addObject:[triple componentsSeparatedByString:@","]];
}

NSLog(@"matrix: %@", matrix);
[matrix release];


问:
How would paginate a json response in my GET request without the use of models/databases?
I'd like to know how I can paginate multiples of 10 with the given response in my GET request when it's not using databases/models.

I've searched around but I'm mostly seeing examples of database/model paginations and not json response paginations.

Below's what I've tried (along with so many other ways but I've ran out of options and hit a wall) but to no avail.

I know there's a way to do this simply but I just can't seem to wrap my head around it.  Any feedback would be appreciated :).

```<code>$response = Http::get(env('endpoint'), $queryParams);

$results = $response->json()['results'];

$numResults = $response->json()['num_results'];

$results->paginate(10); // multiples of ten.  I know this is the Model way of doing it but I can't find any other way to achieve this.
</code>```

答:
May be you can use de chunk method of collection</p>
```<code>$results = collect($result);
$outputs = $results->chunck(20)[$request->input('page')];
</code>```

Body:
I'd like to know how I can paginate multiples of 10 with the given response in my GET request when it's not using databases/models.

I've searched around but I'm mostly seeing examples of database/model paginations and not json response paginations.

Below's what I've tried (along with so many other ways but I've ran out of options and hit a wall) but to no avail.

I know there's a way to do this simply but I just can't seem to wrap my head around it.  Any feedback would be appreciated :).

$response = Http::get(env('endpoint'), $queryParams);

$results = $response->json()['results'];

$numResults = $response->json()['num_results'];

$results->paginate(10); // multiples of ten.  I know this is the Model way of doing it but I can't find any other way to achieve this.

Body:
May be you can use de chunk method of collection

$results = collect($result);
$outputs = $results->chunck(20)[$request->input('page')];


问:
averaging all rows from Matrix where column 1 has the same value (Matlab)
I have a matrix and would like to average all columns where column 1 has the same value. For example
A [1 2 3; 1 2 5; 3 2 5]
The column 1 has two times the number 1, so I would like to all columns where column 1 has number 1, so that the outcome will be
A_new [1 2 4; 3 2 5]

What is the easiest way to do so?

Additionally, I would like in this matrix that every number between 1 and in this example 3, is present in column 1, and that it should fill the corresponding other columns with NaNs.

So the outcome should be
A_new2 [1 2 4; 2 NaN NaN; 3 2 5]

答:
This is a job for splitapply, together with findgroups (or unique):

```<code>A = [1 2 3; 1 2 5; 3 2 5];
[g, h] = findgroups(A(:,1)); % or [~, h, g] = unique(10*A(:,1));
result = [h splitapply(@(x)mean(x,1), A(:, 2:end), findgroups(A(:,1)))];
</code>```

Body:
This is a job for splitapply, together with findgroups (or unique):

A = [1 2 3; 1 2 5; 3 2 5];
[g, h] = findgroups(A(:,1)); % or [~, h, g] = unique(10*A(:,1));
result = [h splitapply(@(x)mean(x,1), A(:, 2:end), findgroups(A(:,1)))];


问:
Escape double ampersand in powershell script when using Invoke-Expression
I am trying to build a command using different strings that are created conditionally.
This command is for adding a key to vault.

Thing is, either in key description or value double ampersands can occur.

I managed to escape single ampersand, but not the two or more.

Current code, excluding parameter passing etc for brevity:

```<code>[string]$params = "az keyvault secret set --name `'$name`' --vault-name `'$destinationVault`' "

    if($description -ne '')
    {
        # Escaping ampersand so that it can be used in Invoke-Expression
        $params += "--description `'$($description -replace '&', '"&"')`' "
    }

    $params += "--disabled $(if($enabled) { "false" } else { "true" }) "

    if($expires -ne '')
    {
        $params += "--expires `'$(([DateTime]($expires)).ToUniversalTime().ToString($dateFormat))`' "
    }

    if($notBefore -ne '')
    {
        $params += "--not-before `'$(([DateTime]($notBefore)).ToUniversalTime().ToString($dateFormat))`' "
    }

    if($tags -ne '')
    {
        $params += "--tags `'$tags`' "
    }
    else
    {
        $params += "--tags `"`" "
    }

    $params += "--value `'$($value -replace '&', '"&"')`'"

    return $params
</code>```

Returned params is used by parent script - $result = Invoke-Expression (Build-SetSecretCommand $secret $destinationKeyVault)

Result of this code ran on example data with single & in secret value in console looks like that:

```<code>az keyvault secret set --name 'secret_name' --vault-name 'vault_name' --disabled false --tags 'file-encoding=utf-8' --value 'super_secret://+_with_symbols"&"ampersand!'
</code>```

and translates to super_secret://+_with_symbols&ampersand! in created secret value.

As mentioned, code works with single &, but if there are more than one symbols like that, I am getting errors like

```<code>Invoke-Expression : At line:1 char:23
+ Write-Host asdasdasd a&&&&&asdASsdad asd a    ada   &7
The token '&&' is not a valid statement separator in this version.
</code>```

答:
First, the obligatory warning:

Invoke-Expression  (iex) should generally be avoided and used only as a last resort, due to its inherent security risks. Superior alternatives are usually available. If there truly is no alternative, only ever use it on input you either provided yourself or fully trust - see this answer.

In the case at hand, since you're calling an external program (az), the best approach is to create to collect the programmatically constructed arguments in an array, as the following simplified example demonstrates:

# Programmatically construct the arguments to pass to az below.
$azArgs = & {

  if ($description)
  {
      '--description'
      # Enclose (runs of) ampersands (&) in arguments with *no spaces* in "..."
      # THIS MUST BE DONE FOR ALL ARGUMENTS THAT POTENTIALLY CONTAIN &
      # such as the --value argument.
      # IF AN ARGUMENT (ALREADY) HAS EMBEDDED " CHARACTERS, MORE WORK IS NEEDED,
      # EVEN IF IT CONTAINS SPACES - see notes below.
      if ($description -match '&' -and $description -notmatch ' ') {
        $description -replace '&+', '"$&"'
        # NOTE: $& is a placeholder for whatever the regex matched
        #       That this placeholder also includes '&' is coincidental.
      } else {
        $description
      }
  }

  '--disabled'
  if ($enabled) { 'false' } else { 'true' }

  # ...
}

# Invoke az with the array of arguments constructed above.
az keyvault secret set --name $name --vault-name $destinationVault $azArgs
```
<p>Note:</p>
<ul>
<li><p>The script block (<code>{ ... }</code>) outputs individual strings, which PowerShell automatically collects in an array (assuming two or more outputs).</p>
</li>
<li><p><strong><code>&</code> chars. embedded in arguments (potentially along with other <code>cmd.exe</code> metacharacters such as <code>|</code>) only cause problems <em>if the argument contains no spaces</em></strong>; this unfortunate problem is a confluence of two behaviors:</p>
<ul>
<li><p>PowerShell - justifiably - passes space-less arguments <em>unquoted</em> on the command line <em>it rebuilds behind the scenes</em> - irrespective of the original quoting; e.g., <code>'a&b'</code> is placed as <em>unquoted</em> <code>a&b</code> on the command line ultimately used for invocation.</p>
</li>
<li><p><strong><code>az</code> - due to being implemented <em>as a batch file</em> (<code>az.cmd</code>) - regrettably parses its command line <em>as if it had been invoked from inside a <code>cmd.exe</code> session</em></strong>, so that an <em>unquoted</em> argument such as <code>a&b</code> <em>breaks</em> the call, because <code>&</code> is a <code>cmd.exe</code> <em>metacharacter</em>. (The problem does <em>not</em> arise if the argument happens to contain <em>spaces</em>, because PowerShell then places it <em>double-quoted</em> on the behind-the-scenes command line.)</p>
</li>
<li><p>While <code>cmd.exe</code> is ultimately at fault, PowerShell <em>could</em> - and arguably should - compensate for this automatically, as proposed in GitHub issue #15143. Sadly, it appears that this proposal won't be implemented.</p>
</li>
</ul>
</li>
<li><p>Applying embedded double-quoting to (runs of) <code>&</code> chars. in space-less arguments is <em>not</em> enough <strong>if arguments already have embedded double quotes (<code>"</code>)</strong>, e.g. <code>a"b</code>; in fact, preexisting embedded <code>"</code> are a problem even in arguments <em>with</em> spaces. <strong>They require explicit escaping as <code>""</code></strong>, which - in contrast with the <code>&</code> issue - <em>is</em> PowerShell's fault: <strong>passing arguments with embedded <code>"</code> has always been broken and still is as of PowerShell 7.2.1</strong> - a possibly <em>opt-in</em> fix may come in v7.3 at the earliest - see this answer</p>
</li>
</ul>
<p>A <strong>backward- and forward-compatible helper function that obviates the need for manual quoting and escaping</strong> is the <strong><code>ie</code> function</strong> from the <code>Native</code> module (<code>Install-Module Native</code>)</p>
<p>With the <code>ie</code> function installed, you can output the argument values <em>as-is</em> from the script block (e.g., <code>if ($description) { '--description'; $description }</code>) and simply prepend <code>ie </code> to the invocation:</p>
<pre class="lang-sh prettyprint-override"><code># Call via helper function "ie" from the "Native" module
# - no manual quoting / escaping needed.
ie az keyvault secret set --name $name --vault-name $destinationVault $azArgs
</code>```

Body:
I am trying to build a command using different strings that are created conditionally.
This command is for adding a key to vault.

Thing is, either in key description or value double ampersands can occur.

I managed to escape single ampersand, but not the two or more.

Current code, excluding parameter passing etc for brevity:

[string]$params = "az keyvault secret set --name `'$name`' --vault-name `'$destinationVault`' "

    if($description -ne '')
    {
        # Escaping ampersand so that it can be used in Invoke-Expression
        $params += "--description `'$($description -replace '&', '"&"')`' "
    }

    $params += "--disabled $(if($enabled) { "false" } else { "true" }) "

    if($expires -ne '')
    {
        $params += "--expires `'$(([DateTime]($expires)).ToUniversalTime().ToString($dateFormat))`' "
    }

    if($notBefore -ne '')
    {
        $params += "--not-before `'$(([DateTime]($notBefore)).ToUniversalTime().ToString($dateFormat))`' "
    }

    if($tags -ne '')
    {
        $params += "--tags `'$tags`' "
    }
    else
    {
        $params += "--tags `"`" "
    }

    $params += "--value `'$($value -replace '&', '"&"')`'"

    return $params

Returned params is used by parent script - $result = Invoke-Expression (Build-SetSecretCommand $secret $destinationKeyVault)

Result of this code ran on example data with single & in secret value in console looks like that:

az keyvault secret set --name 'secret_name' --vault-name 'vault_name' --disabled false --tags 'file-encoding=utf-8' --value 'super_secret://+_with_symbols"&"ampersand!'

and translates to super_secret://+_with_symbols&ampersand! in created secret value.

As mentioned, code works with single &, but if there are more than one symbols like that, I am getting errors like

Invoke-Expression : At line:1 char:23
+ Write-Host asdasdasd a&&&&&asdASsdad asd a    ada   &7
The token '&&' is not a valid statement separator in this version.

Body:
First, the obligatory warning:

Invoke-Expression  (iex) should generally be avoided and used only as a last resort, due to its inherent security risks. Superior alternatives are usually available. If there truly is no alternative, only ever use it on input you either provided yourself or fully trust - see this answer.

In the case at hand, since you're calling an external program (az), the best approach is to create to collect the programmatically constructed arguments in an array, as the following simplified example demonstrates:

# Programmatically construct the arguments to pass to az below.
$azArgs = & {

  if ($description)
  {
      '--description'
      # Enclose (runs of) ampersands (&) in arguments with *no spaces* in "..."
      # THIS MUST BE DONE FOR ALL ARGUMENTS THAT POTENTIALLY CONTAIN &
      # such as the --value argument.
      # IF AN ARGUMENT (ALREADY) HAS EMBEDDED " CHARACTERS, MORE WORK IS NEEDED,
      # EVEN IF IT CONTAINS SPACES - see notes below.
      if ($description -match '&' -and $description -notmatch ' ') {
        $description -replace '&+', '"$&"'
        # NOTE: $& is a placeholder for whatever the regex matched
        #       That this placeholder also includes '&' is coincidental.
      } else {
        $description
      }
  }

  '--disabled'
  if ($enabled) { 'false' } else { 'true' }

  # ...
}

# Invoke az with the array of arguments constructed above.
az keyvault secret set --name $name --vault-name $destinationVault $azArgs

Note:

The script block ({ ... }) outputs individual strings, which PowerShell automatically collects in an array (assuming two or more outputs).

& chars. embedded in arguments (potentially along with other cmd.exe metacharacters such as |) only cause problems if the argument contains no spaces; this unfortunate problem is a confluence of two behaviors:

PowerShell - justifiably - passes space-less arguments unquoted on the command line it rebuilds behind the scenes - irrespective of the original quoting; e.g., 'a&b' is placed as unquoted a&b on the command line ultimately used for invocation.

az - due to being implemented as a batch file (az.cmd) - regrettably parses its command line as if it had been invoked from inside a cmd.exe session, so that an unquoted argument such as a&b breaks the call, because & is a cmd.exe metacharacter. (The problem does not arise if the argument happens to contain spaces, because PowerShell then places it double-quoted on the behind-the-scenes command line.)

While cmd.exe is ultimately at fault, PowerShell could - and arguably should - compensate for this automatically, as proposed in GitHub issue #15143. Sadly, it appears that this proposal won't be implemented.

Applying embedded double-quoting to (runs of) & chars. in space-less arguments is not enough if arguments already have embedded double quotes ("), e.g. a"b; in fact, preexisting embedded " are a problem even in arguments with spaces. They require explicit escaping as "", which - in contrast with the & issue - is PowerShell's fault: passing arguments with embedded " has always been broken and still is as of PowerShell 7.2.1 - a possibly opt-in fix may come in v7.3 at the earliest - see this answer

A backward- and forward-compatible helper function that obviates the need for manual quoting and escaping is the ie function from the Native module (Install-Module Native)

With the ie function installed, you can output the argument values as-is from the script block (e.g., if ($description) { '--description'; $description }) and simply prepend ie  to the invocation:

# Call via helper function "ie" from the "Native" module
# - no manual quoting / escaping needed.
ie az keyvault secret set --name $name --vault-name $destinationVault $azArgs


问:
Cargo build broke after using VS code
For a while I have been editing my Rust program with Pycharm Professional. However, I was curious and experimented with VS Code. At first my project was compiling and running. However, it suddenly started throwing a pretty wild error on cargo build and cargo run (while cargo check is fine), even in cmd outside of VS Code:

```<code>error: linking with `link.exe` failed: exit code: 1104
= note: "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.30.30705\\bin\\HostX64\\x64\\link.exe" "/NOLOGO" "C:\\rust\\book\\target\\debug\\deps\\book.1apvyby1qhuehv3.rcgu.o" "C:\\rust\\book\\target\\debug\\deps\\book.1cw7xmk0cjjg5uln.rcgu.o" "C:\\rust\\book\\target\\debug\\deps\\book.1e8ho0j4rykowhcr.rcgu.o" "C:\\rust\\book\\target\\debug\\deps\\book.1g2fbveo2gp7bxds.rcgu.o"
..............
..............
= note: LINK : fatal error LNK1104: cannot open file 'C:\rust\book\target\debug\deps\book.exe'
</code>```

book is the name of my project.
I am on Windows 10, System Type: x64-based PC.
VS Code version 1.63.2

答: Had to remove the directory, and redownload the whole project(used Git).</p>

Title: Cargo build broke after using VS code

Body:
For a while I have been editing my Rust program with Pycharm Professional. However, I was curious and experimented with VS Code. At first my project was compiling and running. However, it suddenly started throwing a pretty wild error on cargo build and cargo run (while cargo check is fine), even in cmd outside of VS Code:

error: linking with `link.exe` failed: exit code: 1104
= note: "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.30.30705\\bin\\HostX64\\x64\\link.exe" "/NOLOGO" "C:\\rust\\book\\target\\debug\\deps\\book.1apvyby1qhuehv3.rcgu.o" "C:\\rust\\book\\target\\debug\\deps\\book.1cw7xmk0cjjg5uln.rcgu.o" "C:\\rust\\book\\target\\debug\\deps\\book.1e8ho0j4rykowhcr.rcgu.o" "C:\\rust\\book\\target\\debug\\deps\\book.1g2fbveo2gp7bxds.rcgu.o"
..............
..............
= note: LINK : fatal error LNK1104: cannot open file 'C:\rust\book\target\debug\deps\book.exe'

book is the name of my project.
I am on Windows 10, System Type: x64-based PC.
VS Code version 1.63.2


问:
Visual hitches in SwiftUI when dragging an element in a view with lots of Buttons
I'm developing a macOS application in SwiftUI for image annotation (keypoints). Basically, the user can add keypoints (circles) by clicking the displayed image and it can move them around by dragging them if they are misplaced. I noticed huge slowdowns and hitches when dragging keypoints.

I wasn't able to find the issue using the debugger so I tried to narrow down the problem by removing code until the issue disappears. I found a minimal example which reproduces the issue:

import SwiftUI

struct Keypoint: Identifiable {
    var x, y: Double
    let id = UUID()
}

struct KeypointView: View {
    @Binding var keypoint: Keypoint

    var body: some View {
        Circle()
            .frame(width: 20, height: 20)
            .offset(x: keypoint.x - 10, y: keypoint.y - 10)
            .gesture(move)
    }

    var move: some Gesture {
        DragGesture().onChanged { value in
            let pos = value.location
            keypoint.x = pos.x
            keypoint.y = pos.y
        }
    }
}

struct KeypointsView: View {
    @Binding var keypoints: [Keypoint]

    var body: some View {
        ZStack(alignment: .topLeading) {
            ForEach($keypoints) { $keypoint in
                KeypointView(keypoint: $keypoint)
            }
        }
        .frame(width: 600, height: 400, alignment: .topLeading)
    }
}

struct ButtonsView: View {
    var body: some View {
        HStack {
            ForEach(0..<10) { i in
                Button("\(i)") { }
            }
        }
        .padding()
    }
}

struct ContentView: View {
    @State private var keypoints = (0..<10).map { _ in
        Keypoint(x: .random(in: 0...600), y: .random(in: 0...400))
    }

    var body: some View {
        HStack {
            VStack {
                KeypointsView(keypoints: $keypoints)
                ButtonsView()
            }
            Text("")
        }
    }
}
```
<p>This represents a view with some keypoints (circles) in the main area, controls at the bottom (buttons) and some text on the view side. Dragging any keypoint results in lots of visual hitches, the movement is not smooth. By commenting the <code>ButtonsView()</code> and the <code>Text()</code> in <code>ContentView()</code>, the issue disappears and the movement is smooth.</p>
<p>I tried to identify the issue using the SwiftUI and the Hitches debuggers and I found that there are many critical commits during dragging. However, this is not very informative and I cannot understand what causes the issue.</p>
<p>By experimenting, I noticed that the more buttons they are, the most hitches they are. Also, commenting only the <code>Text()</code> view results in a less critical slowdown. Replacing the buttons by other views (<code>Text</code>, <code>Rectangle</code>, ...) also removes the issue.</p>
<p><strong>Any idea on what is causing the issue or a workaround?</strong></p>
<hr />
<h3>Update</h3>
<p>I found a workaround that works for this particular example, but not for my original application. It consists in wrapping the <code>KeypointsView</code>'s <code>ZStack</code> in a <code>GeometryReader</code>:</p>
<pre class="lang-swift prettyprint-override"><code>struct KeypointsView: View {
    @Binding var keypoints: [Keypoint]

    var body: some View {
        GeometryReader { _ in
            ZStack(alignment: .topLeading) {
                ForEach($keypoints) { $keypoint in
                    KeypointView(keypoint: $keypoint)
                }
            }
        }
        .frame(width: 600, height: 400, alignment: .topLeading)
    }
}
</code>```

This brings back a very smooth visual experience. Does anybody knows how this works?

答:
If you skip the text and VStack – and give the buttons a fixed frame then it works. Don't ask me why...

```<code>var body: some View {
//  HStack {
        VStack {
            KeypointsView(keypoints: $keypoints)
            ButtonsView()
                .frame(width: 600, height: 100)
        }
//      Text("Hello")
//  }
}
</code>```

Body:
I'm developing a macOS application in SwiftUI for image annotation (keypoints). Basically, the user can add keypoints (circles) by clicking the displayed image and it can move them around by dragging them if they are misplaced. I noticed huge slowdowns and hitches when dragging keypoints.

I wasn't able to find the issue using the debugger so I tried to narrow down the problem by removing code until the issue disappears. I found a minimal example which reproduces the issue:

import SwiftUI

struct Keypoint: Identifiable {
    var x, y: Double
    let id = UUID()
}

struct KeypointView: View {
    @Binding var keypoint: Keypoint

    var body: some View {
        Circle()
            .frame(width: 20, height: 20)
            .offset(x: keypoint.x - 10, y: keypoint.y - 10)
            .gesture(move)
    }

    var move: some Gesture {
        DragGesture().onChanged { value in
            let pos = value.location
            keypoint.x = pos.x
            keypoint.y = pos.y
        }
    }
}

struct KeypointsView: View {
    @Binding var keypoints: [Keypoint]

    var body: some View {
        ZStack(alignment: .topLeading) {
            ForEach($keypoints) { $keypoint in
                KeypointView(keypoint: $keypoint)
            }
        }
        .frame(width: 600, height: 400, alignment: .topLeading)
    }
}

struct ButtonsView: View {
    var body: some View {
        HStack {
            ForEach(0..<10) { i in
                Button("\(i)") { }
            }
        }
        .padding()
    }
}

struct ContentView: View {
    @State private var keypoints = (0..<10).map { _ in
        Keypoint(x: .random(in: 0...600), y: .random(in: 0...400))
    }

    var body: some View {
        HStack {
            VStack {
                KeypointsView(keypoints: $keypoints)
                ButtonsView()
            }
            Text("")
        }
    }
}

This represents a view with some keypoints (circles) in the main area, controls at the bottom (buttons) and some text on the view side. Dragging any keypoint results in lots of visual hitches, the movement is not smooth. By commenting the ButtonsView() and the Text() in ContentView(), the issue disappears and the movement is smooth.

I tried to identify the issue using the SwiftUI and the Hitches debuggers and I found that there are many critical commits during dragging. However, this is not very informative and I cannot understand what causes the issue.

By experimenting, I noticed that the more buttons they are, the most hitches they are. Also, commenting only the Text() view results in a less critical slowdown. Replacing the buttons by other views (Text, Rectangle, ...) also removes the issue.

Any idea on what is causing the issue or a workaround?

Update

I found a workaround that works for this particular example, but not for my original application. It consists in wrapping the KeypointsView's ZStack in a GeometryReader:

struct KeypointsView: View {
    @Binding var keypoints: [Keypoint]

    var body: some View {
        GeometryReader { _ in
            ZStack(alignment: .topLeading) {
                ForEach($keypoints) { $keypoint in
                    KeypointView(keypoint: $keypoint)
                }
            }
        }
        .frame(width: 600, height: 400, alignment: .topLeading)
    }
}

This brings back a very smooth visual experience. Does anybody knows how this works?

Body:
If you skip the text and VStack – and give the buttons a fixed frame then it works. Don't ask me why...

var body: some View {
//  HStack {
        VStack {
            KeypointsView(keypoints: $keypoints)
            ButtonsView()
                .frame(width: 600, height: 100)
        }
//      Text("Hello")
//  }
}


问:
How to run unitest from specific file?
In my project I have a task to add few Unittests to APIs.
We have many django apps and I need to do work only with one:

```<code>apps\data\tests.py
</code>```

But when I'm trying to specify exactly this file/folder to start those exact Tests:

```<code>python3 manage.py test data.tests
</code>```

or

```<code>python3 manage.py test data.tests.py
</code>```

its still running ALL tests between ALL apps.
I did make 1 hour search online but Everyone suggesting to use:

```<code> python3 manage.py test  + "path to the folder/file".
</code>```

But its still running everything. Maybe i'm missing some General test configuration in settings.py?

Thank you,

答:
You need to start from your app name. To run tests only from file tests.py in app apps run:

```<code>python3 manage.py test apps.data.tests
</code>```

To run specific TestCase, run:

```<code>python3 manage.py test apps.data.tests.MyTestCase
</code>```

or even only single test:

```<code>python3 manage.py test apps.data.tests.MyTestCase.my_first_test
</code>```

Title: How to run unitest from specific file?

Body:
In my project I have a task to add few Unittests to APIs.
We have many django apps and I need to do work only with one:

apps\data\tests.py

But when I'm trying to specify exactly this file/folder to start those exact Tests:

python3 manage.py test data.tests

or

python3 manage.py test data.tests.py

its still running ALL tests between ALL apps.
I did make 1 hour search online but Everyone suggesting to use:

 python3 manage.py test  + "path to the folder/file".

But its still running everything. Maybe i'm missing some General test configuration in settings.py?

Thank you,

Body:
You need to start from your app name. To run tests only from file tests.py in app apps run:

python3 manage.py test apps.data.tests

To run specific TestCase, run:

python3 manage.py test apps.data.tests.MyTestCase

or even only single test:

python3 manage.py test apps.data.tests.MyTestCase.my_first_test


问:
Which component lifecycle method is best suited for performing side effects?
Which component lifecycle method is best suited for performing side effects?</p>
```<code>componentWillMount()
shouldComponentUpdate()
componentDidUnmount()
componentDidMount()
</code>```

答:
If talking class component lifecycle methods, componentDidMount, componentDidUpdate, and componentWillUnmount are the three lifecycle methods you should use for issuing side-effects.

componentDidMount

componentDidUpdate

componentWillUnmount

If talking function components, then useEffect with an appropriate dependency array is what you would use for issuing side-effects.

An useEffect hook with an empty dependency array is roughly equivalent to componentDidMount.

An useEffect hook with a populated dependency array is roughly equivalent to componentDidMount and componentDidUpdate.

An useEffect hook with a populated dependency array and returned cleanup function is roughly equivalent to componentDidMount, componentDidUpdate, and componentWillUnmount.

See useEffect for more documentation

Body:
Which component lifecycle method is best suited for performing side effects?

componentWillMount()
shouldComponentUpdate()
componentDidUnmount()
componentDidMount()


问:
Outlook Add-in REST API deprecation
We are retrieving the email and attachments using the oAuth token from getCallbackTokenAsync in office.js JavaScript library and sending the token to the web application to retrieve them from EWS (~/EWS/Exchange.asmx) using SOAP request similar to the approach shown in https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/get-attachments-of-an-outlook-item

Could anyone please confirm that the deprecation of Outlook Rest API 2.0 will not affect the existing functionality. I am new to the Outlook add-in development and the documentation seems vast to digest.

https://devblogs.microsoft.com/microsoft365dev/outlook-rest-api-v2-0-deprecation-notice/

Do we need to register the add-in anywhere OR provide any permissions to the add-in specifically for getCallbackTokenAsync method to retrieve the token OR making the SOAP request to download attachments.

答:
EWS remains unchanged for Outlook web add-ins. Make sure that you don't use the isRest option for the getCallbackTokenAsync call.

Take a look at the recent Office add-ins community call where this question was discussed in depth. Here is a screenshot for others:

Title: Outlook Add-in REST API deprecation


问:
C# Generic Methods Problem ,TargetException , Object does not match target type
iv'e been using the following reflection methods in order to create a Generic MethodInfo object of a certain type

```<code>// this is the example that does work , i call the invoked generic method
// from the same class it resides in
// all i'm doing here is casting type on T in order to create an object<t> of
// some sort witch i can't know the T till run-time
class SomeClass
{
    public IIndexable CreateIndex(string column)
    {
       Type type = GetType(column);
       MethodInfo index_generator = GetGenericMethod(type,"GenerateIndex");
       Iindexable index = (Iindaxable)index_genraotr.Invoke(this,null);
    }

     public MethodInfo GetGenericMethod(Type type, string method_name)
     {
        return GetType()
              .GetMethods(BindingFlags.Public |  BindingFlags.InstanceBindingFlags.NonPublic)
              .Single(methodInfo => methodInfo.Name == method_name && methodInfo.IsGenericMethodDefinition)
              .MakeGenericMethod(type);
     }
     public Iindexable GenerateIndex<T>()
     {
         return new Sindex<T>();
     }
 } // end SomeClass
</code>```

now since these are methods that i use Frequently i decided to encapsulate them in a factory class

```<code>class Factory
{// same deal as above just that now i got a class called factory encapsulating
 // all the functionality involved
       public MethodInfo GetGenericMethod(Type type, string method_name)

       public IIndexable GenerateIndex<T>(string[] columns)
       {// SIndex : IIndexable
            SIndex<T> index = new SIndex<T>(record, column, seecondary_columns);
            return index;
       }
       public Type GetType(string column)
}
</code>```

now when i try to invoke the same method from somewhere outside the factory class i get a TargetException witch states,
Object does not match target type.

```<code>// some event , or some place to call the factory's functionality from
btn_index ClickEvent(.......)
{
    Factory f = new Factory();
    Type type = f.GetType(column);
    MethodInfo index_generator = f.GetGenericMethod(type,"GenerateIndex");
    Iindexable index = (Iindexable)index_genrator.Inovke(this,null);
}
</code>```

is the target type the type of the place witch i call the invoke from ?
and if so why should it matter the Method is found in the factory
when i call GetType() inside GetGenericMethod i get the type of the factory
and from there i extract the wanted method using a lambda expression .

i would really appreciate if some one could shed some light on the matter  since i seem to be missing some know how on the matter

thanks in advance eran.

答:
Try using </p>

```<code>index_genrator.Invoke(f,null);
</code>```

Body:
iv'e been using the following reflection methods in order to create a Generic MethodInfo object of a certain type

// this is the example that does work , i call the invoked generic method
// from the same class it resides in
// all i'm doing here is casting type on T in order to create an object<t> of
// some sort witch i can't know the T till run-time
class SomeClass
{
    public IIndexable CreateIndex(string column)
    {
       Type type = GetType(column);
       MethodInfo index_generator = GetGenericMethod(type,"GenerateIndex");
       Iindexable index = (Iindaxable)index_genraotr.Invoke(this,null);
    }

     public MethodInfo GetGenericMethod(Type type, string method_name)
     {
        return GetType()
              .GetMethods(BindingFlags.Public |  BindingFlags.InstanceBindingFlags.NonPublic)
              .Single(methodInfo => methodInfo.Name == method_name && methodInfo.IsGenericMethodDefinition)
              .MakeGenericMethod(type);
     }
     public Iindexable GenerateIndex<T>()
     {
         return new Sindex<T>();
     }
 } // end SomeClass

now since these are methods that i use Frequently i decided to encapsulate them in a factory class

class Factory
{// same deal as above just that now i got a class called factory encapsulating
 // all the functionality involved
       public MethodInfo GetGenericMethod(Type type, string method_name)

       public IIndexable GenerateIndex<T>(string[] columns)
       {// SIndex : IIndexable
            SIndex<T> index = new SIndex<T>(record, column, seecondary_columns);
            return index;
       }
       public Type GetType(string column)
}

now when i try to invoke the same method from somewhere outside the factory class i get a TargetException witch states,
Object does not match target type.

// some event , or some place to call the factory's functionality from
btn_index ClickEvent(.......)
{
    Factory f = new Factory();
    Type type = f.GetType(column);
    MethodInfo index_generator = f.GetGenericMethod(type,"GenerateIndex");
    Iindexable index = (Iindexable)index_genrator.Inovke(this,null);
}

is the target type the type of the place witch i call the invoke from ?
and if so why should it matter the Method is found in the factory
when i call GetType() inside GetGenericMethod i get the type of the factory
and from there i extract the wanted method using a lambda expression .

i would really appreciate if some one could shed some light on the matter  since i seem to be missing some know how on the matter

thanks in advance eran.

Body:
Try using

index_genrator.Invoke(f,null);


问:
Does google adwords de-dupe conversions?
I'm using AdWords to track conversions on an ajax site. It works well for single conversions that have a unique label and value.

The Problem:

On the site I have a use case where a user can fire multiple very similar looking conversions in short succession. Sometimes these conversions are unique, sometimes they could match one or more of the other conversion values and labels.

When I submit these conversions, it tracks some of them, and not others.

At first, I was adding the conversion snippet to the page, so I figured it was including conversions.js only once, and not firing the others. So, to fix that, I moved the conversion snippet to an iFrame and put that on the page. That had the same problem, but was definitely including conversions.js. I was worried that the problem may have to do with the fact that they're fired in quick succession, so I made them wait before firing the next. I tried intervals of 1,2, and 4 seconds, none of which solved the issue.

In an attempt to figure out what was going wrong, I beautified conversions.js, and found a debug option. I turned it on, and it was warning on all conversions about a missing conversion_id - I tried adding google_conversion_id, and just set it to a timestamp, so it would always be unique. This didn't solve the problem either.

I finally tried just ditching the iFrames, and adding the tracking pixel to the page. The tracking pixel still fires the conversions just fine, and seems to add an iFrame to the page, then delete it. Unfortunately, the conversions still are missing.

The Question:

In light of this not working in any of many different ways, I'm wondering if google is de-duping my similar conversions. The docs have no information that shed light on this, but they also don't document the google_conversion_id, so there's plenty going on that isn't documented.

If they are, why wouldn't google_conversion_id fix this? It seems that should unique each lead. I can't append to the label or value, and I'm making all my requests with a cachebuster appended to the end to make sure it's not on the browser end. I can verify that it's working, as either conversions.js gets included or the iFrame shows up.

Any ideas? Anyone know where I can ask a googler about this? It's driving me CRAZY.

答:
The variable google_conversion_id is your account number. Do not change it, or things just won't work.

As far as I can tell there is no way to pass a unique transaction ID, nor to sign the conversion parameters to prevent duplicates and request forgeries.

Google has no way to differentiate the following scenarios, because they result in exactly the same set of calls to the current Google adWords conversion script:

A customer buying two widgets at $50 in quick succession

A customer buying one widget at $50 and refreshing or returning to your receipt page

An evil adSense user triggering your conversion pixel to log himself two $50 sales

This was merely annoying when they only supported CPC, but with CPA it has become a vulnerability in the Google adWords system.


问:
Create ID over an abnormal sequence
I have the following code that samples 1 row 5 times, 2 rows 5 times, 3 rows 5 times and so on..
After running the lapply and converting it to a dataframe to make comparisons I need a way to alter the ID variable to act as my groups. So rows 1:5 of "want" would be "group 1", rows 6:15 would be "group 2", 16:30 would be "group 3" and so on...
These are the groupings because group one only has one replicate of each number in the ID column, group 2 has two replicates, group 3 has 3 replicates and so on.

Code

```<code>iris<- iris

select_rows <- 1:4
n_times <- 5
inds <- nrow(iris)

result <- lapply(select_rows, function(x)
  replicate(n_times, iris[sample(inds, x), ], simplify = FALSE))

want<- bind_rows(result, .id = 'source')
View(want)
</code>```

Thinking about running an ANOVA on each column for example, the ID column would not provide sufficient groupings of observations.
I suppose I could use a combo of ifelse and mutate to manually go through and assign the rows to certain groups, but I hope to avoid this as I will need to do this for several varying dataframes.
I also tried the following code to assign groups over a sequence, but realized it wouldn't work because the numbers of observations in each group are not the same:

```<code>final<- want %>% mutate(Group = rep(seq(1,ceiling(nrow(want)/5)),each = 5))
</code>```

Any help would be appreciated.

Title: Create ID over an abnormal sequence

Body:
I have the following code that samples 1 row 5 times, 2 rows 5 times, 3 rows 5 times and so on..
After running the lapply and converting it to a dataframe to make comparisons I need a way to alter the ID variable to act as my groups. So rows 1:5 of "want" would be "group 1", rows 6:15 would be "group 2", 16:30 would be "group 3" and so on...
These are the groupings because group one only has one replicate of each number in the ID column, group 2 has two replicates, group 3 has 3 replicates and so on.

Code

iris<- iris

select_rows <- 1:4
n_times <- 5
inds <- nrow(iris)

result <- lapply(select_rows, function(x)
  replicate(n_times, iris[sample(inds, x), ], simplify = FALSE))

want<- bind_rows(result, .id = 'source')
View(want)

Thinking about running an ANOVA on each column for example, the ID column would not provide sufficient groupings of observations.
I suppose I could use a combo of ifelse and mutate to manually go through and assign the rows to certain groups, but I hope to avoid this as I will need to do this for several varying dataframes.
I also tried the following code to assign groups over a sequence, but realized it wouldn't work because the numbers of observations in each group are not the same:

final<- want %>% mutate(Group = rep(seq(1,ceiling(nrow(want)/5)),each = 5))

Any help would be appreciated.

Body:
Here's another option using findInterval and cumsum:

want$grp <- c(findInterval(seq(1:nrow(want)), cumsum(c(n_times * select_rows))+1))

Output

   source Sepal.Length Sepal.Width Petal.Length Petal.Width    Species grp
1       1          5.4         3.7          1.5         0.2     setosa   0
2       2          4.8         3.1          1.6         0.2     setosa   0
3       3          6.1         2.8          4.7         1.2 versicolor   0
4       4          6.7         3.3          5.7         2.5  virginica   0
5       5          5.4         3.4          1.7         0.2     setosa   0
6       6          5.5         2.4          3.8         1.1 versicolor   1
7       6          6.0         2.2          5.0         1.5  virginica   1
8       7          5.0         3.5          1.6         0.6     setosa   1
9       7          5.6         2.5          3.9         1.1 versicolor   1
10      8          5.2         3.4          1.4         0.2     setosa   1
11      8          6.2         3.4          5.4         2.3  virginica   1
12      9          6.7         3.1          4.7         1.5 versicolor   1
13      9          5.1         3.3          1.7         0.5     setosa   1
14     10          7.7         3.8          6.7         2.2  virginica   1
15     10          6.0         3.4          4.5         1.6 versicolor   1
16     11          5.0         3.3          1.4         0.2     setosa   2
17     11          6.6         3.0          4.4         1.4 versicolor   2
18     11          5.6         2.5          3.9         1.1 versicolor   2
19     12          4.4         3.2          1.3         0.2     setosa   2
20     12          6.7         3.3          5.7         2.5  virginica   2
21     12          5.9         3.0          5.1         1.8  virginica   2
22     13          5.8         2.7          4.1         1.0 versicolor   2
23     13          5.4         3.4          1.5         0.4     setosa   2
24     13          5.5         2.4          3.8         1.1 versicolor   2
25     14          5.6         2.5          3.9         1.1 versicolor   2
26     14          6.0         2.2          5.0         1.5  virginica   2
27     14          5.7         3.8          1.7         0.3     setosa   2
28     15          6.2         3.4          5.4         2.3  virginica   2
29     15          6.5         3.2          5.1         2.0  virginica   2
30     15          5.8         2.7          4.1         1.0 versicolor   2
31     16          5.1         3.5          1.4         0.2     setosa   3
32     16          5.8         2.7          5.1         1.9  virginica   3
33     16          4.3         3.0          1.1         0.1     setosa   3
34     16          4.6         3.2          1.4         0.2     setosa   3
35     17          4.9         3.0          1.4         0.2     setosa   3
36     17          5.4         3.0          4.5         1.5 versicolor   3
37     17          6.7         3.1          4.7         1.5 versicolor   3
38     17          6.3         2.3          4.4         1.3 versicolor   3
39     18          4.7         3.2          1.3         0.2     setosa   3
40     18          6.5         2.8          4.6         1.5 versicolor   3
41     18          4.9         3.1          1.5         0.1     setosa   3
42     18          6.4         2.7          5.3         1.9  virginica   3
43     19          6.1         3.0          4.9         1.8  virginica   3
44     19          6.2         2.8          4.8         1.8  virginica   3
45     19          4.8         3.1          1.6         0.2     setosa   3
46     19          5.9         3.0          5.1         1.8  virginica   3
47     20          5.4         3.9          1.7         0.4     setosa   3
48     20          6.2         2.9          4.3         1.3 versicolor   3
49     20          6.4         2.7          5.3         1.9  virginica   3
50     20          6.3         3.4          5.6         2.4  virginica   3


问:
react render Logical && vs Ternary operator
In the react render() when the value of x equals 1 both the logical && and ternary operator will display Hello and both are syntactically correct. I always used the && when I don't want to show the else part of my condition, but I have come across one code base where most of the places they used ternary operator with null instead of &&. Is there any performance gain or any other advantage of using one method over the other?

```<code>return (
    <div>
        <div>{x === 1 && <div>Hello</div>}</div>
        <div>{x === 1 ? <div>Hello</div> : null}</div>
    </div>
);
</code>```

答:
It is advised to use ternary operator instead of logical &&, ||. There is a major difference if you do not take it into account. You can read the details in the below article.

Kent Blog About this

Body:
In the react render() when the value of x equals 1 both the logical && and ternary operator will display Hello and both are syntactically correct. I always used the && when I don't want to show the else part of my condition, but I have come across one code base where most of the places they used ternary operator with null instead of &&. Is there any performance gain or any other advantage of using one method over the other?

return (

{x === 1 &&
Hello
}

{x === 1 ?
Hello
 : null}

);