问:
How to write unit test case for my cron job Scheduler
I've updated my cron job scheduler function. Now i need to update the unit test case for this function. For scheduleJob passing date and function as params. In my test case, I need to check whether the function toHaveBeenCalled.

```<code>/**
 * @file Scheduler Service.
 */

// Import External Modules
import { CronCommand, CronJob } from 'cron';

// ************* Scheduler Configuration ***************
const TIMEZONE = 'Asia/Kolkata';
// *****************************************************

export class Scheduler {
  static scheduleJob = (scheduleDate: Date, scheduleFunction: CronCommand) => {
    const date = new Date(scheduleDate);
    const scheduleJob = new CronJob(
      `0 0 0 ${date.getDate()} ${date.getMonth()} 0-6`,
      scheduleFunction,
      undefined,
      true,
      TIMEZONE,
    );
    scheduleJob.start();
  };
}
</code>```

答:
You can use jest.mock(moduleName, factory, options) mock the CronJob constructor and its instance for cron module.

E.g.

index.ts:

import { CronCommand, CronJob } from 'cron';

// ************* Scheduler Configuration ***************
const TIMEZONE = 'Asia/Kolkata';
// *****************************************************

export class Scheduler {
  static scheduleJob = (scheduleDate: Date, scheduleFunction: CronCommand) => {
    const date = new Date(scheduleDate);
    const scheduleJob = new CronJob(
      `0 0 0 ${date.getDate()} ${date.getMonth()} 0-6`,
      scheduleFunction,
      undefined,
      true,
      TIMEZONE,
    );
    scheduleJob.start();
  };
}
```

<p><code>index.test.ts</code>:</p>

<pre class="lang-js prettyprint-override"><code>import { Scheduler } from '.';
import { CronJob } from 'cron';

jest.mock('cron', () => {
  const mScheduleJob = { start: jest.fn() };
  const mCronJob = jest.fn(() => mScheduleJob);
  return { CronJob: mCronJob };
});

describe('62078071', () => {
  it('should pass', () => {
    const mScheduleJob = new CronJob();
    const mDate = new Date(1995, 11, 17);
    const mScheduleFunction = jest.fn();
    Scheduler.scheduleJob(mDate, mScheduleFunction);
    expect(CronJob).toBeCalledWith(`0 0 0 17 11 0-6`, mScheduleFunction, undefined, true, 'Asia/Kolkata');
    expect(mScheduleJob.start).toBeCalledTimes(1);
  });
});
</code>```

The outcome for the test:

 PASS  stackoverflow/62078071/index.test.ts (14.62s)
  62078071
    ✓ should pass (8ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 index.ts |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        16.582s
```

Body:
I've updated my cron job scheduler function. Now i need to update the unit test case for this function. For scheduleJob passing date and function as params. In my test case, I need to check whether the function toHaveBeenCalled.

/**
 * @file Scheduler Service.
 */

// Import External Modules
import { CronCommand, CronJob } from 'cron';

// ************* Scheduler Configuration ***************
const TIMEZONE = 'Asia/Kolkata';
// *****************************************************

export class Scheduler {
  static scheduleJob = (scheduleDate: Date, scheduleFunction: CronCommand) => {
    const date = new Date(scheduleDate);
    const scheduleJob = new CronJob(
      `0 0 0 ${date.getDate()} ${date.getMonth()} 0-6`,
      scheduleFunction,
      undefined,
      true,
      TIMEZONE,
    );
    scheduleJob.start();
  };
}

Body:
You can use jest.mock(moduleName, factory, options) mock the CronJob constructor and its instance for cron module.

E.g.

index.ts:

import { CronCommand, CronJob } from 'cron';

// ************* Scheduler Configuration ***************
const TIMEZONE = 'Asia/Kolkata';
// *****************************************************

export class Scheduler {
  static scheduleJob = (scheduleDate: Date, scheduleFunction: CronCommand) => {
    const date = new Date(scheduleDate);
    const scheduleJob = new CronJob(
      `0 0 0 ${date.getDate()} ${date.getMonth()} 0-6`,
      scheduleFunction,
      undefined,
      true,
      TIMEZONE,
    );
    scheduleJob.start();
  };
}

index.test.ts:

import { Scheduler } from '.';
import { CronJob } from 'cron';

jest.mock('cron', () => {
  const mScheduleJob = { start: jest.fn() };
  const mCronJob = jest.fn(() => mScheduleJob);
  return { CronJob: mCronJob };
});

describe('62078071', () => {
  it('should pass', () => {
    const mScheduleJob = new CronJob();
    const mDate = new Date(1995, 11, 17);
    const mScheduleFunction = jest.fn();
    Scheduler.scheduleJob(mDate, mScheduleFunction);
    expect(CronJob).toBeCalledWith(`0 0 0 17 11 0-6`, mScheduleFunction, undefined, true, 'Asia/Kolkata');
    expect(mScheduleJob.start).toBeCalledTimes(1);
  });
});

The outcome for the test:

 PASS  stackoverflow/62078071/index.test.ts (14.62s)
  62078071
    ✓ should pass (8ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 index.ts |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        16.582s


来源: stackexchange

问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答: Define a high level language?  When C was created it was considered a high level language because it could be compiled on multiple architectures </p>

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?

OwnerDisplayName: Bob The Janitor


问:
C# application with SQL Server stored procedure
My C# Windows form has a combobox and textbox. The combobox has 2 records which are 'Novel' & 'Poem'.

I need to write code that if I select 'Poem', it should be auto generate 'PO-00001' and if I select 'Novel', it should be auto generate 'NV-00001'.

So then I wrote a stored procedure to do that and it looks like this:

```<code>ALTER PROCEDURE [dbo].[Proc_New_LoadTest]
AS
BEGIN
    DECLARE @MaxNo int, @No Varchar(50);

    SELECT @MaxNo = ISNULL(MAX(CAST(RIGHT(ISBN, 5) AS int)), 0) + 1
    FROM bookstock
    WHERE category = @No

    SELECT RIGHT('00000' + CAST(@MaxNo AS varchar(50)), 5);
    RETURN @MaxNo
END
</code>```

This is my C# code:

```<code>void loadisbn()
{
    Connection con = new Connection();

    SqlCommand cmd = new SqlCommand("[Proc_New_LoadTest]", con.ActiveCon());
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@No", SqlDbType.VarChar).Value = cmbcategory.Text.Trim();

    cmd.ExecuteNonQuery();
}
</code>```

I tried to do here as if select 'Novel' by combobox, so it should find maximum isbn number from isbn column and if it is 'Poem' so related maximum isbn to it (these 2 records are contained in a one column).

But my code throws an error:

Procedure  Proc_New_LoadTest has no parameters and arguments were supplied.

Please help me to debug this error (my SQL Server version is SQL Server 2005 Express)

答:
If you want the @no to be a parameter for the stored procedure, you need to define it like this:

```<code>ALTER PROCEDURE [dbo].[Proc_New_LoadTest]
    @No Varchar(50);
AS
BEGIN
    DECLARE @MaxNo int;

    SELECT @MaxNo = ISNULL(MAX(CAST(RIGHT(ISBN, 5) AS int)), 0) + 1
    FROM bookstock
    WHERE category = @No

    SELECT RIGHT('00000' + CAST(@MaxNo AS varchar(50)), 5);

    RETURN @MaxNo
END
</code>```

and in your C# code, you have a funny way of combining two approaches to providing a value - the best practice would be to use this line of code:

```<code>cmd.Parameters.Add("@No", SqlDbType.VarChar, 50).Value = cmbcategory.Text.Trim();
</code>```

Use the .Add() method (not .AddWithValue()), and explicitly define the length of your varchar parameter.

ContentLicense: CC BY-SA 4.0

Body:
My C# Windows form has a combobox and textbox. The combobox has 2 records which are 'Novel' & 'Poem'.

I need to write code that if I select 'Poem', it should be auto generate 'PO-00001' and if I select 'Novel', it should be auto generate 'NV-00001'.

So then I wrote a stored procedure to do that and it looks like this:

ALTER PROCEDURE [dbo].[Proc_New_LoadTest]
AS
BEGIN
    DECLARE @MaxNo int, @No Varchar(50);

    SELECT @MaxNo = ISNULL(MAX(CAST(RIGHT(ISBN, 5) AS int)), 0) + 1
    FROM bookstock
    WHERE category = @No

    SELECT RIGHT('00000' + CAST(@MaxNo AS varchar(50)), 5);
    RETURN @MaxNo
END

This is my C# code:

void loadisbn()
{
    Connection con = new Connection();

    SqlCommand cmd = new SqlCommand("[Proc_New_LoadTest]", con.ActiveCon());
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@No", SqlDbType.VarChar).Value = cmbcategory.Text.Trim();

    cmd.ExecuteNonQuery();
}

I tried to do here as if select 'Novel' by combobox, so it should find maximum isbn number from isbn column and if it is 'Poem' so related maximum isbn to it (these 2 records are contained in a one column).

But my code throws an error:

Procedure  Proc_New_LoadTest has no parameters and arguments were supplied.

Please help me to debug this error (my SQL Server version is SQL Server 2005 Express)

Body:
If you want the @no to be a parameter for the stored procedure, you need to define it like this:

ALTER PROCEDURE [dbo].[Proc_New_LoadTest]
    @No Varchar(50);
AS
BEGIN
    DECLARE @MaxNo int;

    SELECT @MaxNo = ISNULL(MAX(CAST(RIGHT(ISBN, 5) AS int)), 0) + 1
    FROM bookstock
    WHERE category = @No

    SELECT RIGHT('00000' + CAST(@MaxNo AS varchar(50)), 5);

    RETURN @MaxNo
END

and in your C# code, you have a funny way of combining two approaches to providing a value - the best practice would be to use this line of code:

cmd.Parameters.Add("@No", SqlDbType.VarChar, 50).Value = cmbcategory.Text.Trim();

Use the .Add() method (not .AddWithValue()), and explicitly define the length of your varchar parameter.


问:
What is the different between <class> with <class> and <class> with <mixin>
What is the different between <class> with <class> and <class> with <mixin> ?

I have a example:

```<code>class Run {
  void run(String name) {
    print('$name run');
  }
}

class People with Run {}

class Dog with Run {}

void main() {
  final people = People();
  final dog = Dog();
  people.run('${people.runtimeType}');
  dog.run('${dog.runtimeType}');
}
</code>```

I cannot seen different after i had changed class Run to mixin Run

答:
mixin is used to specify that the class is only to be used as a mixin.

You can mixin plain classes or abstract classes, but they can be subclassed and the former can be instanced. If you want to prevent that you should use a mixin. I believe it should be more common to define mixins purposefully.

mixin rules are different from mixing in other classes.

Read more about here.

Body:
What is the different between <class> with <class> and <class> with <mixin> ?

I have a example:

class Run {
  void run(String name) {
    print('$name run');
  }
}

class People with Run {}

class Dog with Run {}

void main() {
  final people = People();
  final dog = Dog();
  people.run('${people.runtimeType}');
  dog.run('${dog.runtimeType}');
}

I cannot seen different after i had changed class Run to mixin Run


问:
Logarithmic axis with modified ticks
I'm trying to re-create the below graph but am not able to get rid of the 'half-step' increments for x > 3. Is there a better way of doing this? I'm using ggplot2 for now - to get it right and then plan on switching to plotly for interactive plots.

Code

Only showing 3 traces for PoC:

```<code>set.seed(69)
library(data.table)
library(ggplot2)

k <- lapply(1:10, function(z){
  ret <- sample(x = (5*z):100,
                size = 20,
                replace = T)
  dat <- data.table(V1 =  ret[order(ret)] )
  colnames(dat) <- paste('trace', z, sep = '')
  return(dat)
  })

dat <- do.call(cbind, k)
dat$size <- c(seq(0.1, 1, 0.1), 2:11)

ggplot(dat[size >= 0.2, ], aes(x = size)) +
  geom_line(size = 1.5, aes(y = trace1), color = '#003366') +
  geom_line(size = 1.5, aes(y = trace2),
            color = rgb(red = 0, green = 103, blue = 62, maxColorValue = 255)) +
  geom_line(size = 1.5, aes(y = trace3), color = '#b20000') +
  scale_x_log10(breaks = c(seq(0.1, 1, 0.1), 2:11))
</code>```

Output

Desired Plot

答:
Minor grid lines can be removed via the theme, by setting panel.grid.minor = element_blank().

set.seed(69)
library(data.table)
library(ggplot2)

k <- lapply(1:10, function(z){
  ret <- sample(x = (5*z):100,
                size = 20,
                replace = T)
  dat <- data.table(V1 =  ret[order(ret)] )
  colnames(dat) <- paste('trace', z, sep = '')
  return(dat)
})

dat <- do.call(cbind, k)
dat$size <- c(seq(0.1, 1, 0.1), 2:11)

ggplot(dat[size >= 0.2, ], aes(x = size)) +
  geom_line(size = 1.5, aes(y = trace1), color = '#003366') +
  geom_line(size = 1.5, aes(y = trace2),
            color = rgb(red = 0, green = 103, blue = 62, maxColorValue = 255)) +
  geom_line(size = 1.5, aes(y = trace3), color = '#b20000') +
  scale_x_log10(breaks = c(seq(0.1, 1, 0.1), 2:11)) +
  theme(panel.grid.minor = element_blank())
```

Created on 2020-05-28 by the reprex package (v0.3.0)

Title: Logarithmic axis with modified ticks

Body:
I'm trying to re-create the below graph but am not able to get rid of the 'half-step' increments for x > 3. Is there a better way of doing this? I'm using ggplot2 for now - to get it right and then plan on switching to plotly for interactive plots.

Code

Only showing 3 traces for PoC:

set.seed(69)
library(data.table)
library(ggplot2)

k <- lapply(1:10, function(z){
  ret <- sample(x = (5*z):100,
                size = 20,
                replace = T)
  dat <- data.table(V1 =  ret[order(ret)] )
  colnames(dat) <- paste('trace', z, sep = '')
  return(dat)
  })

dat <- do.call(cbind, k)
dat$size <- c(seq(0.1, 1, 0.1), 2:11)

ggplot(dat[size >= 0.2, ], aes(x = size)) +
  geom_line(size = 1.5, aes(y = trace1), color = '#003366') +
  geom_line(size = 1.5, aes(y = trace2),
            color = rgb(red = 0, green = 103, blue = 62, maxColorValue = 255)) +
  geom_line(size = 1.5, aes(y = trace3), color = '#b20000') +
  scale_x_log10(breaks = c(seq(0.1, 1, 0.1), 2:11))

Output

Desired Plot

Body:
Minor grid lines can be removed via the theme, by setting panel.grid.minor = element_blank().

set.seed(69)
library(data.table)
library(ggplot2)

k <- lapply(1:10, function(z){
  ret <- sample(x = (5*z):100,
                size = 20,
                replace = T)
  dat <- data.table(V1 =  ret[order(ret)] )
  colnames(dat) <- paste('trace', z, sep = '')
  return(dat)
})

dat <- do.call(cbind, k)
dat$size <- c(seq(0.1, 1, 0.1), 2:11)

ggplot(dat[size >= 0.2, ], aes(x = size)) +
  geom_line(size = 1.5, aes(y = trace1), color = '#003366') +
  geom_line(size = 1.5, aes(y = trace2),
            color = rgb(red = 0, green = 103, blue = 62, maxColorValue = 255)) +
  geom_line(size = 1.5, aes(y = trace3), color = '#b20000') +
  scale_x_log10(breaks = c(seq(0.1, 1, 0.1), 2:11)) +
  theme(panel.grid.minor = element_blank())

Created on 2020-05-28 by the reprex package (v0.3.0)


问:
How do I solve this inheritance problem in rust?
first of all the obligatory "I am new to Rust": I am.

So I have the following problem:

I have two(or more) structs of data, that all implement some common behaviour in addition their own behaviour. I have a list of these structs (or rather: of the 'supertype'), I need to access some of their shared behaviour and some of their individual behaviour.
My Question is: how do I do that in Rust.

To further illustrate my question I have come up with a code comparision between Kotlin and Rust. Kotlin works as I want it to, Rust does not (yet).

In Kotlin the code may look like this(using the plain, old inheritance abstraction):

```<code>interface Animal {
    fun eat()
    fun sleep()
}
class Cat(val name: String) : Animal {
    fun meow()              { println("meow") }

    override fun eat()      { println("cat $name is eating fish(or lasagne)") }
    override fun sleep()    { println("cat $name sleeps inside") }
}
class Lion(val tag_id: Int) : Animal {
    fun roar()              { println("roar") }

    override fun eat()      { println("lion(tag=${tag_id} is eating gazelle") }
    override fun sleep()    { println("lion(tag=${tag_id} sleeps outside") }
}

var animals: MutableList<Animal> = ArrayList()
fun main() {
    animals.add(Cat("Garfield"))
    animals.add(Lion(12))
    //later:
    for (animal in animals) {
        animal.sleep()
        if (animal is Lion)
            animal.roar()
    }
}
</code>```

In Rust I came up with the following code (which does not allow an 'instance_of' type function):

```<code>trait Animal {
    fn eat(&self);
    fn sleep(&self);
}

struct Cat {
    name: String
}
impl Cat {
    fn meow(&self)      { println!("meow") }
}
impl Animal for Cat {
    fn eat(&self)       { println!("cat {} is eating fish(or lasagne)", self.name) }
    fn sleep(&self)     { println!("cat {} sleeps inside", self.name) }
}

struct Lion {
    tag_id: usize
}
impl Lion {
    fn roar(&self)      { println!("roar") }
}
impl Animal for Lion {
    fn eat(&self)       { println!("lion(tag={}) is eating fish(or lasagne)", self.tag_id) }
    fn sleep(&self)     { println!("lion(tag={}) sleeps inside", self.tag_id) }
}

fn main() {
    let animals:Vec<Box<dyn Animal>> = vec![
                Box::new(Cat {name: "Garfield".to_string()}),
                Box::new(Lion {tag_id: 12})
    ];
    //later:
    for animal in animals {
        animal.sleep()
        //HOW DO I ACCESS THE CONCRETE STRUCT HERE?
    }
}
</code>```

Playground

I realize this may be a stupid question, or show how I am 'still trapped in the non-Rust thinking', but I am at kind of an Impass here and need just a little bit of assistence.

答:
You can try something like this

use std::any::Any;

trait Animal {
    fn eat(&self);
    fn sleep(&self);
    fn as_any(&self) -> &dyn Any;
}

struct Cat {
    name: String
}
impl Cat {
    fn meow(&self)      { println!("meow") }
}
impl Animal for Cat {
    fn eat(&self)       { println!("cat {} is eating fish(or lasagne)", self.name) }
    fn sleep(&self)     { println!("cat {} sleeps inside", self.name) }
    fn as_any(&self) -> &dyn Any { self }
}

struct Lion {
    tag_id: usize
}
impl Lion {
    fn roar(&self)      { println!("roar") }
}
impl Animal for Lion {
    fn eat(&self)       { println!("lion(tag={}) is eating fish(or lasagne)", self.tag_id) }
    fn sleep(&self)     { println!("lion(tag={}) sleeps inside", self.tag_id) }
    fn as_any(&self) -> &dyn Any { self }
}

fn main() {
    let animals:Vec<Box<dyn Animal>> = vec![
                Box::new(Cat {name: "Garfield".to_string()}),
                Box::new(Lion {tag_id: 12})
    ];
    //later:
    for animal in animals.iter() {
        animal.sleep();
        if let Some(animal) = animal.as_any().downcast_ref::<Lion>() {
            animal.roar();
        }
    }
}

```

Body:
first of all the obligatory "I am new to Rust": I am.

So I have the following problem:

I have two(or more) structs of data, that all implement some common behaviour in addition their own behaviour. I have a list of these structs (or rather: of the 'supertype'), I need to access some of their shared behaviour and some of their individual behaviour.
My Question is: how do I do that in Rust.

To further illustrate my question I have come up with a code comparision between Kotlin and Rust. Kotlin works as I want it to, Rust does not (yet).

In Kotlin the code may look like this(using the plain, old inheritance abstraction):

interface Animal {
    fun eat()
    fun sleep()
}
class Cat(val name: String) : Animal {
    fun meow()              { println("meow") }

    override fun eat()      { println("cat $name is eating fish(or lasagne)") }
    override fun sleep()    { println("cat $name sleeps inside") }
}
class Lion(val tag_id: Int) : Animal {
    fun roar()              { println("roar") }

    override fun eat()      { println("lion(tag=${tag_id} is eating gazelle") }
    override fun sleep()    { println("lion(tag=${tag_id} sleeps outside") }
}

var animals: MutableList<Animal> = ArrayList()
fun main() {
    animals.add(Cat("Garfield"))
    animals.add(Lion(12))
    //later:
    for (animal in animals) {
        animal.sleep()
        if (animal is Lion)
            animal.roar()
    }
}

In Rust I came up with the following code (which does not allow an 'instance_of' type function):

trait Animal {
    fn eat(&self);
    fn sleep(&self);
}

struct Cat {
    name: String
}
impl Cat {
    fn meow(&self)      { println!("meow") }
}
impl Animal for Cat {
    fn eat(&self)       { println!("cat {} is eating fish(or lasagne)", self.name) }
    fn sleep(&self)     { println!("cat {} sleeps inside", self.name) }
}

struct Lion {
    tag_id: usize
}
impl Lion {
    fn roar(&self)      { println!("roar") }
}
impl Animal for Lion {
    fn eat(&self)       { println!("lion(tag={}) is eating fish(or lasagne)", self.tag_id) }
    fn sleep(&self)     { println!("lion(tag={}) sleeps inside", self.tag_id) }
}

fn main() {
    let animals:Vec<Box<dyn Animal>> = vec![
                Box::new(Cat {name: "Garfield".to_string()}),
                Box::new(Lion {tag_id: 12})
    ];
    //later:
    for animal in animals {
        animal.sleep()
        //HOW DO I ACCESS THE CONCRETE STRUCT HERE?
    }
}

Playground

I realize this may be a stupid question, or show how I am 'still trapped in the non-Rust thinking', but I am at kind of an Impass here and need just a little bit of assistence.


问:
How to convert vector<int> to a char array?
Platform is Windows with MSVC.  I'm writing an encryption unpadding function.

I have many vector<int> which are the results of a decryption function.  A vector<int> might contain a UTF-8 string, or it might be garbage if the decryption parameters were wrong.  I need to subtract a number from each position, and then see if it's a valid UTF-8 string.  That's the padding scheme: add a character's position to itself before encrypting.

To display the results, I assume I need to convert the vector<int> to a vector<char>.  I can then use that as a const char[] and print it to the console.

How do I handle the possibility of overflow and underflow when casting to a char?  After all, a char is signed and has a range of -128 to 127 on my platform.

```<code>std::vector<char> unpad(const std::vector<int>& input) {
    std::vector<char> output;
    for (int i{ 0 }; i < input.size(); ++i) {
        if (input[i] < -128 || input[i] > 127) {
            printf("oops overflow\n");
        }
        output.push_back(static_cast<char>(input[i] - i)); // Padding scheme
    }
    output.push_back(static_cast<char>(0)); // Null termination
    return output;
}
</code>```

答:
I think you're looking at this problem wrong. You don't want to cast from int to char since you'll lose information. You want to preserve the information in the int. What you need to realise is that an int is 32 bits and char 8 bits. Therefore you need 4 chars to hold all the information from a single int. To extract the information from a single int you need to use bit operators

```<code>char a = some_int & 0x000000ff;
char b = some_int & 0x0000ff00;
char c = some_int & 0x00ff0000;
char d = some_int & 0xff000000;
</code>```

Now you'll have the 4 bytes (the chars) that map to the parts in a single int. You can work from there to decode utf-8.

Note that on 64 and 32 bit systems ints take 4 bytes.

Body:
Platform is Windows with MSVC.  I'm writing an encryption unpadding function.

I have many vector<int> which are the results of a decryption function.  A vector<int> might contain a UTF-8 string, or it might be garbage if the decryption parameters were wrong.  I need to subtract a number from each position, and then see if it's a valid UTF-8 string.  That's the padding scheme: add a character's position to itself before encrypting.

To display the results, I assume I need to convert the vector<int> to a vector<char>.  I can then use that as a const char[] and print it to the console.

How do I handle the possibility of overflow and underflow when casting to a char?  After all, a char is signed and has a range of -128 to 127 on my platform.

std::vector<char> unpad(const std::vector<int>& input) {
    std::vector<char> output;
    for (int i{ 0 }; i < input.size(); ++i) {
        if (input[i] < -128 || input[i] > 127) {
            printf("oops overflow\n");
        }
        output.push_back(static_cast<char>(input[i] - i)); // Padding scheme
    }
    output.push_back(static_cast<char>(0)); // Null termination
    return output;
}

Body:
I think you're looking at this problem wrong. You don't want to cast from int to char since you'll lose information. You want to preserve the information in the int. What you need to realise is that an int is 32 bits and char 8 bits. Therefore you need 4 chars to hold all the information from a single int. To extract the information from a single int you need to use bit operators

char a = some_int & 0x000000ff;
char b = some_int & 0x0000ff00;
char c = some_int & 0x00ff0000;
char d = some_int & 0xff000000;

Now you'll have the 4 bytes (the chars) that map to the parts in a single int. You can work from there to decode utf-8.

Note that on 64 and 32 bit systems ints take 4 bytes.


问:
Calculating absolute average in dataframe
My dataframe-

```<code>df= pd.DataFrame({'A':[33,-44],'B':[44,-66],'C':[66,21]})
</code>```

I want to find the absolute average per row(ignoring the signs) and the formula for taking the average will be for example-

for the first row-

```<code>(33+ 44/2 + 66/3)/3 = 25.6
</code>```

for second row-

```<code>(44+66/2+21/3)/3=24.3
</code>```

This is not a direct average but according to a specific column the value will be divided by a specific value like for column A its 1 for column B its division by 2 and so on.

output-

```<code>        Average
     0  25.60000
     1  24.300
</code>```

I did -

```<code>df[['average']]= (abs(df[['A']]).values + abs(df[['B']]/2).values +  abs(df[['C']]/3).values )/3
</code>```

but its giving error

答:
Isn't that possible with pd.Series?</p>

```<code>((abs(df['A'])+abs(df['B']/2)+abs(df['C']/3))/3).to_frame()
</code>```

Body:
My dataframe-

df= pd.DataFrame({'A':[33,-44],'B':[44,-66],'C':[66,21]})

I want to find the absolute average per row(ignoring the signs) and the formula for taking the average will be for example-

for the first row-

(33+ 44/2 + 66/3)/3 = 25.6

for second row-

(44+66/2+21/3)/3=24.3

This is not a direct average but according to a specific column the value will be divided by a specific value like for column A its 1 for column B its division by 2 and so on.

output-

        Average
     0  25.60000
     1  24.300

I did -

df[['average']]= (abs(df[['A']]).values + abs(df[['B']]/2).values +  abs(df[['C']]/3).values )/3

but its giving error

Body:
Isn't that possible with pd.Series?

((abs(df['A'])+abs(df['B']/2)+abs(df['C']/3))/3).to_frame()


问:
How to apply masking while creating next row value which is based on previous row's value and another column in Python Pandas?
Here is the data

```<code>import numpy as np
import pandas as pd

data = {
    'cases': [120, 100, np.nan, np.nan, np.nan, np.nan, np.nan],
    'percent_change': [0.03, 0.01, 0.00, -0.001, 0.05, -0.1, 0.003],
    'tag': [7, 6, 5, 4, 3, 2, 1],
}

   cases  percent_change  tag
0  120.0           0.030    7
1  100.0           0.010    6
2    NaN           0.000    5
3    NaN          -0.001    4
4    NaN           0.050    3
5    NaN          -0.100    2
6    NaN           0.003    1
</code>```

I want to create next cases' value as (next value) = (previous value) * (1+current per_change). Specifically, I want it to be done in rows that has a tag value less than 6 (and I must use a mask (i.e., df.loc for this row selection). This should give me:

```<code>   cases  percent_change  tag
0  120.0           0.030    7
1  100.0           0.010    6
2  100.0           0.000    5
3   99.9          -0.001    4
4  104.9           0.050    3
5   94.4          -0.100    2
6   94.7           0.003    1
</code>```

I tried this but it doesn't work:

```<code>df_index = np.where(df['tag'] == 6)
index = df_index[0][0]
df.loc[(df.tag<6), 'cases'] = (df.percent_change.shift(0).fillna(1) + 1).cumprod() * df.at[index, 'cases']

        cases  percent_change  tag
0  120.000000           0.030    7
1  100.000000           0.010    6
2  104.030000           0.000    5
3  103.925970          -0.001    4
4  109.122268           0.050    3
5   98.210042          -0.100    2
6   98.504672           0.003    1
</code>```

答:
I would do:

```<code>s = df.cases.isna()
percents = df.percent_change.where(s,0)+1
df['cases'] = df.cases.ffill()*percents.cumprod()
</code>```

Output:

```<code>        cases  percent_change  tag
0  120.000000           0.030    7
1  100.000000           0.010    6
2  100.000000           0.000    5
3   99.900000          -0.001    4
4  104.895000           0.050    3
5   94.405500          -0.100    2
6   94.688716           0.003    1
</code>```

Update: If you really insist on masking on the Tag==6:

```<code>s = df.tag.eq(6).shift()
s = s.where(s).ffill()

percents = df.percent_change.where(s,0)+1
df['cases'] = df.cases.ffill()*percents.cumprod()
</code>```

Body:
Here is the data

import numpy as np
import pandas as pd

data = {
    'cases': [120, 100, np.nan, np.nan, np.nan, np.nan, np.nan],
    'percent_change': [0.03, 0.01, 0.00, -0.001, 0.05, -0.1, 0.003],
    'tag': [7, 6, 5, 4, 3, 2, 1],
}

   cases  percent_change  tag
0  120.0           0.030    7
1  100.0           0.010    6
2    NaN           0.000    5
3    NaN          -0.001    4
4    NaN           0.050    3
5    NaN          -0.100    2
6    NaN           0.003    1

I want to create next cases' value as (next value) = (previous value) * (1+current per_change). Specifically, I want it to be done in rows that has a tag value less than 6 (and I must use a mask (i.e., df.loc for this row selection). This should give me:

   cases  percent_change  tag
0  120.0           0.030    7
1  100.0           0.010    6
2  100.0           0.000    5
3   99.9          -0.001    4
4  104.9           0.050    3
5   94.4          -0.100    2
6   94.7           0.003    1

I tried this but it doesn't work:

df_index = np.where(df['tag'] == 6)
index = df_index[0][0]
df.loc[(df.tag<6), 'cases'] = (df.percent_change.shift(0).fillna(1) + 1).cumprod() * df.at[index, 'cases']

        cases  percent_change  tag
0  120.000000           0.030    7
1  100.000000           0.010    6
2  104.030000           0.000    5
3  103.925970          -0.001    4
4  109.122268           0.050    3
5   98.210042          -0.100    2
6   98.504672           0.003    1

Body:
I would do:

s = df.cases.isna()
percents = df.percent_change.where(s,0)+1
df['cases'] = df.cases.ffill()*percents.cumprod()

Output:

        cases  percent_change  tag
0  120.000000           0.030    7
1  100.000000           0.010    6
2  100.000000           0.000    5
3   99.900000          -0.001    4
4  104.895000           0.050    3
5   94.405500          -0.100    2
6   94.688716           0.003    1

Update: If you really insist on masking on the Tag==6:

s = df.tag.eq(6).shift()
s = s.where(s).ffill()

percents = df.percent_change.where(s,0)+1
df['cases'] = df.cases.ffill()*percents.cumprod()


问:
Can't change emulated performance of AVD in Android Studio
I can't change the graphics to software as I'm sure this is the fix for my AVD not launching.
The option is greyed out (see screenshot). Has anyone has experience with this? I couldn't find anyone who had the same issue.

I'm running the latest version of Android Studio on Ubuntu 17.04.

答:
I think It's just a bug!

Solved the issue by selecting any virtual device had the option enabled and after finishing the installation I just clicked on edit and reselected the device I wanted and the option was still enabled.

Click on edit button from here.

Then change the device to the one you want.

ContentLicense: CC BY-SA 3.0


问:
Reorder Overlaid Bars in Plot so Longer Bars are in back -R
I have a barplot that I want to overlay. The issue is that longer bars are covering shorter bars. There's a function in excel that allows for longer bars to be pushed to the back, and shorter bars brought to the forefront. How can I do that in R?

My code is below:

```<code>ggplot(df2) +geom_bar(aes(x = id, y = `Feb-20`), position = "identity",stat="identity", fill = 'green') +
  geom_bar(aes(x = id, y = `Mar-20`), position = "identity", stat="identity",fill = 'navy') +
  geom_bar(aes(x = id, y = `Apr-20`), position = "identity", stat="identity", fill = 'red')
</code>```

And produces this chart:

Now, I've seen some solutions to this issue by changing the transparency. Since I have three factors, changing the alpha hasn't been very clear:

How can I change the overlay ordering of the bars, so longer bars are in the back?

答:
I would recommend you switch to geom_col if you are going to be plotting bars, but supplying x= and y= aesthetics.  See here for the documentation explanation.  With that being said, it will work either way.  Basically:

Tidy Data: I cannot confirm, but it seems that your dataset df2 is not organized following Tidy Data Principles, which makes things much easier with ggplot2 and many other methods of data analysis.  Instead of having your y values split among df2$Mar-20 and df2$Apr-20, you should have a column for the category (let's call it df2$date) and a column for the actual value df2$y.  You would then have one call to geom_bar giving aes(x=id, y=y).  You can do this via dplyr::gather() or melt from the reshape2 package.

Arrange Data: Outside of any other influence (such as ordering of the levels of a factor), the plotting function in ggplot2 will plot data according to the arrangement of the actual dataframe for the x= and y= aesthetic.  This means if you order the data beforehand on a particular, non-factor value, this will dictate the order in which ggplot2 will plot.  So, you should order the plot based on descending df2$y prior to plotting to have the largest bars plotted first and smallest last, which means the smallest will be in front.

Here's a complete example with dummy data:

```<code>library(ggplot2)
library(dplyr)

set.seed(1234)
df <- data.frame(
  x=rep(LETTERS[1:10],3),
  y=sample(1:100,30,replace=TRUE),
  id=c(rep('Group1',10),rep('Group2',10),rep('Group3',10))
)

df %>%
arrange(-y) %>%
ggplot(aes(x,y)) + theme_bw() +
  geom_bar(aes(fill=id),stat='identity',position=position_identity())
</code>```

Try that ggplot() function without the arrange() function and you'll see the effect is what you're looking to do.

Body:
I have a barplot that I want to overlay. The issue is that longer bars are covering shorter bars. There's a function in excel that allows for longer bars to be pushed to the back, and shorter bars brought to the forefront. How can I do that in R?

My code is below:

ggplot(df2) +geom_bar(aes(x = id, y = `Feb-20`), position = "identity",stat="identity", fill = 'green') +
  geom_bar(aes(x = id, y = `Mar-20`), position = "identity", stat="identity",fill = 'navy') +
  geom_bar(aes(x = id, y = `Apr-20`), position = "identity", stat="identity", fill = 'red')

And produces this chart:

Now, I've seen some solutions to this issue by changing the transparency. Since I have three factors, changing the alpha hasn't been very clear:

How can I change the overlay ordering of the bars, so longer bars are in the back?

Body:
I would recommend you switch to geom_col if you are going to be plotting bars, but supplying x= and y= aesthetics.  See here for the documentation explanation.  With that being said, it will work either way.  Basically:

Tidy Data: I cannot confirm, but it seems that your dataset df2 is not organized following Tidy Data Principles, which makes things much easier with ggplot2 and many other methods of data analysis.  Instead of having your y values split among df2$Mar-20 and df2$Apr-20, you should have a column for the category (let's call it df2$date) and a column for the actual value df2$y.  You would then have one call to geom_bar giving aes(x=id, y=y).  You can do this via dplyr::gather() or melt from the reshape2 package.

Arrange Data: Outside of any other influence (such as ordering of the levels of a factor), the plotting function in ggplot2 will plot data according to the arrangement of the actual dataframe for the x= and y= aesthetic.  This means if you order the data beforehand on a particular, non-factor value, this will dictate the order in which ggplot2 will plot.  So, you should order the plot based on descending df2$y prior to plotting to have the largest bars plotted first and smallest last, which means the smallest will be in front.

Here's a complete example with dummy data:

library(ggplot2)
library(dplyr)

set.seed(1234)
df <- data.frame(
  x=rep(LETTERS[1:10],3),
  y=sample(1:100,30,replace=TRUE),
  id=c(rep('Group1',10),rep('Group2',10),rep('Group3',10))
)

df %>%
arrange(-y) %>%
ggplot(aes(x,y)) + theme_bw() +
  geom_bar(aes(fill=id),stat='identity',position=position_identity())

Try that ggplot() function without the arrange() function and you'll see the effect is what you're looking to do.


问:
C# Not recognizing resources, .NET to blame?
I am trying to build a C# Program (https://github.com/f1r3fr0st/ajart-studio-edit). First, I load the file but but it gives the error:

The C# project "Art Studio Edit" is targeting ".NETFramework, Version = v4.6.2", which is not installed on this machine. To proceed, select an option below.

Change the Target to .NET Framework 4.6.1.

Download the targeting pack for ".NETFramework, Version = v4.6.2".

When I choose to change the target, then attempt to build the project, I get a multitude of errors which claim that the resources were not able to be found (PcapDotNet, NAudio, AMF3SpecCli, etc.) even though they are all in the project's "Resources" section. Somehow, I have no idea how to replicate it, I was able to get most of the errors to dispensary, with AMF3SpecCli being the only one not to work. After a bit of research, I realized the .NET redirect could be the issue, but it seems like there is no way for me to install hte 4.6.2, which doesn't make sense. I tried downloading and installing 4.6.2, but it says it can't cause a newer version is installed, which doesn't make sense if VS tried to downgrade to 4.6.1... but then I looked and it seems the installed .NET frameworks are 3.5 and 4.8 - so where is the 4.6.1 coming from? And how do I install 4.6.2? Is that even the issue? Please help if possible!

答:
The dependencies (the NuGet packages) work with 4.6.2, not 4.6.1. This leaves you two choices.

Find the versions that work with 4.6.1 and update the references to those versions.

CORRECTION: Install the targeting pack for 4.6.2.

Of the two, the 2nd is easier, but the first will give you some experience cleaning up .NET references (and still may not work if the authors of the github project used something from 4.6.2 that does not work in 4.6.1).

Do you want to fix it or learn?

EDIT: BTW, you can end up with some of the same fun updating to the very latest. Then you have to see if you can get all of the NuGet packages updated. This is actually a useful exercise as senior developers and architects often spend time fixing NuGet messes in code. Going back to the past or forward, either will get you some experience in this.

SECOND EDIT: If you want some real-world experience, update the project for the latest, if possible. I say "if possible" as it may use other projects that are not updated. Then see if you can contribute to the open-source project an updated version. You both help the open-source community and learn a valuable set of skills.


问:
Why reading attributes of an object makes the object undefine?
Below is my code, which gets data from Redux:

```<code>function ProductsDetail(props){
    const dispatch = useDispatch();
    useEffect( () => {
        const fetch = async () => {
            const {data} = await axios.get("/api/products/" + props.match.params.id);
            dispatch(
                {
                type: "product_detail_success",
                payload: data
            })
        }
        fetch();
        return () => {};
    }, [])

    const {product} = useSelector((state) => {
        return state.productDetails
    });

    console.log(product)
    //console.log(product.image)

    return (
        <div>
        </div>
    )
}
</code>```

The console.log(product) line prints out:

However, if I don't comment out the following console.log(product.image) line, an error of Uncaught TypeError: Cannot read property 'image' of undefined will occur.

image is just an attribute of product object , why printing it on the console makes the product object undefine?

Thanks in advence!

答:
In the initial render product is undefined so:

```<code>console.log(product) // will show nothing
//console.log(product.image)
</code>```

when it re-render:

```<code>`console.log(product)` // This show what you see in you log
</code>```

So try the following code:

```<code>console.log(product) // will show nothing
console.log(product?.image) // Add ? to make sure only get image when product defined
</code>```

Body:
Below is my code, which gets data from Redux:

function ProductsDetail(props){
    const dispatch = useDispatch();
    useEffect( () => {
        const fetch = async () => {
            const {data} = await axios.get("/api/products/" + props.match.params.id);
            dispatch(
                {
                type: "product_detail_success",
                payload: data
            })
        }
        fetch();
        return () => {};
    }, [])

    const {product} = useSelector((state) => {
        return state.productDetails
    });

    console.log(product)
    //console.log(product.image)

    return (

    )
}

The console.log(product) line prints out:

However, if I don't comment out the following console.log(product.image) line, an error of Uncaught TypeError: Cannot read property 'image' of undefined will occur.

image is just an attribute of product object , why printing it on the console makes the product object undefine?

Thanks in advence!

Body:
In the initial render product is undefined so:

console.log(product) // will show nothing
//console.log(product.image)

when it re-render:

`console.log(product)` // This show what you see in you log

So try the following code:

console.log(product) // will show nothing
console.log(product?.image) // Add ? to make sure only get image when product defined


问:
AWS Route 53 Routing Policy: Geolocation Vs Latency
AWS implements latency routing policy based on the ip address of resolver or masked ip address of client. It will help to find the region of low latency.

If both geolocation policy and latency policy are based on the IP address of client, it comes to several questions:

what's the difference between them?

What's the purpose of Geolocation routing policy?

Is geolocation policy used for complying the law of different country?  e.g. GDPR, cookie usage.

Europe: GDPR

China: data must be stored in China.

In which case should I use Geolocation routing policy rather than latency policy?

Reference

how does AWS Route 53 achieve latency based routing:

https://youtu.be/PVBC1gb78r8?t=1963

https://youtu.be/PcoQY82SDHw?t=622

How does AWS Route 53 achieve latency based routing?

答:
Amazon maps-out typical latency between IP addresses and AWS regions. Choose Latency-based Routing to have the fastest response.

Geolocation maps the IP addresses to geographic locations. This permits rules like "send all users from Côte d'Ivoire to the website in France", so they see a language-specific version. It can redirect by country, region (eg Oceania) and US state. Geolocation cares more about the location of users rather than the speed of their connection.

Geolocation pre-dates GDPR. It could be used for geo-blocking, but this is typically done in Amazon CloudFront: Restricting the Geographic Distribution of Your Content - Amazon CloudFront


问:
Facing issue with sed command
I have a file with below entries:

```<code> ./test/test1/test2
 ./abc/abc1/abc2
 ./bcd/bcd1/bcd2
</code>```

I want to remove space, ., and / from the starting of each line of the file using sed command. I am using the below sed command for this:

```<code>sed 's/^[ ]\.\//'
</code>```

but is removing only the space and ., but not the /.

I am not able to figure out how to remove / as well. Can someone please help.

Thanks

答:
You're missing a final / in sed's s command:

```<code>sed 's/^[ ]\.\///'
                ^--needed to complete the replacement string.
</code>```

Title: Facing issue with sed command

Body:
I have a file with below entries:

 ./test/test1/test2
 ./abc/abc1/abc2
 ./bcd/bcd1/bcd2

I want to remove space, ., and / from the starting of each line of the file using sed command. I am using the below sed command for this:

sed 's/^[ ]\.\//'

but is removing only the space and ., but not the /.

I am not able to figure out how to remove / as well. Can someone please help.

Thanks

Body:
You're missing a final / in sed's s command:

sed 's/^[ ]\.\///'
                ^--needed to complete the replacement string.


问:
How to set up build and release pipeline for NestJS application to Azure using YAML
I am having trouble understanding and getting the build/release pipelines setup for deploying a NestJS application to Azure DevOps (ADO).

I am deploying to a Linux Web App hosted in Azure.

As far as I understand, if I run the app locally using something like npm run start, it creates a dist folder under my root project directory.

So, when writing the YAML for the build and deployment. My thought process is to:

Run an NPM update.

Run npm run build to build the application and generate the dist folder.

Copy the contents of the application (or just the dist folder?) into the target folder (/home/site/wwwroot)

Run npm run start:prod to start the server.

Here is my YAML so far:

```<code>trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

steps:

- task: UseNode@1
  inputs:
    version: '14.x'
    checkLatest: true

- task: Npm@0
  displayName: Run NPM Update for NestJS
  inputs:
    cwd: '$(Build.SourcesDirectory)/ProjectName'
    command: update

- task: Npm@0
  displayName: Build NestJS
  inputs:
    cwd: '$(Build.SourcesDirectory)/ProjectName'
    command: run
    arguments: "build"

- task: CopyFiles@2
  inputs:
    Contents: 'dist/**'
    TargetFolder: '$(Build.ArtifactStagingDirectory)'
</code>```

The issue is after the build process completes, I do not see a dist folder in /home/site/wwwroot/ProjectName. Can someone help me out with what I am missing?

Also, a side noob-y question about Azure DevOps, what does $(Build.SourcesDirectory) and $(Build.ArtifactStagingDirectory) refer to and how and where are those environment variables set?

答:
To deploy your app to the  hosted in Azure. You need to use Azure App Service Deploy task or Azure Web App task.

Azure devops is the tool to build and deploy your app to your server(eg. the Linux Web App on Azure), it is not for hosting your app.

$(Build.ArtifactStagingDirectory) refer to the folder of the agent machine which runs your pipeline. (When your run your pipeline, it pick up a agent defined in pool to run your pipeline tasks)

The mapping to the folders in the agent machine is showing as below screenshot. Check the predefined variables for more information.

$(Agent.BuildDirectory) is mapped to c:\agent_work\1

$(Build.ArtifactStagingDirectory) is mapped to c:\agent_work\1\a

$(Build.BinariesDirectory) is mapped to c:\agent_work\1\b

$(Build.SourcesDirectory) is mapped to c:\agent_work\1\s

So back to the question how to deploying a NestJS application to Azure?

First you need to create a service connection in Azure devops to connect to your azure subscription. Check here for detailed steps.

Then add Azure App Service Deploy task/Azure Web App task to the end of your pipeline. See below example:

```<code>- task: AzureRmWebAppDeployment@4
  inputs:
    ConnectionType: 'AzureRM'
    azureSubscription: 'SubscriptionServiceConnectionName'
    appType: 'webAppLinux'
    WebAppName: 'MyWebAppName'
    Package: '$(Build.ArtifactStagingDirectory)/dist/'
    StartupCommand: 'npm run start:prod'
</code>```

You can check here for more information.

Body:
I am having trouble understanding and getting the build/release pipelines setup for deploying a NestJS application to Azure DevOps (ADO).

I am deploying to a Linux Web App hosted in Azure.

As far as I understand, if I run the app locally using something like npm run start, it creates a dist folder under my root project directory.

So, when writing the YAML for the build and deployment. My thought process is to:

Run an NPM update.

Run npm run build to build the application and generate the dist folder.

Copy the contents of the application (or just the dist folder?) into the target folder (/home/site/wwwroot)

Run npm run start:prod to start the server.

Here is my YAML so far:

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

steps:

- task: UseNode@1
  inputs:
    version: '14.x'
    checkLatest: true

- task: Npm@0
  displayName: Run NPM Update for NestJS
  inputs:
    cwd: '$(Build.SourcesDirectory)/ProjectName'
    command: update

- task: Npm@0
  displayName: Build NestJS
  inputs:
    cwd: '$(Build.SourcesDirectory)/ProjectName'
    command: run
    arguments: "build"

- task: CopyFiles@2
  inputs:
    Contents: 'dist/**'
    TargetFolder: '$(Build.ArtifactStagingDirectory)'

The issue is after the build process completes, I do not see a dist folder in /home/site/wwwroot/ProjectName. Can someone help me out with what I am missing?

Also, a side noob-y question about Azure DevOps, what does $(Build.SourcesDirectory) and $(Build.ArtifactStagingDirectory) refer to and how and where are those environment variables set?

Body:
To deploy your app to the  hosted in Azure. You need to use Azure App Service Deploy task or Azure Web App task.

Azure devops is the tool to build and deploy your app to your server(eg. the Linux Web App on Azure), it is not for hosting your app.

$(Build.ArtifactStagingDirectory) refer to the folder of the agent machine which runs your pipeline. (When your run your pipeline, it pick up a agent defined in pool to run your pipeline tasks)

The mapping to the folders in the agent machine is showing as below screenshot. Check the predefined variables for more information.

$(Agent.BuildDirectory) is mapped to c:\agent_work\1

$(Build.ArtifactStagingDirectory) is mapped to c:\agent_work\1\a

$(Build.BinariesDirectory) is mapped to c:\agent_work\1\b

$(Build.SourcesDirectory) is mapped to c:\agent_work\1\s

So back to the question how to deploying a NestJS application to Azure?

First you need to create a service connection in Azure devops to connect to your azure subscription. Check here for detailed steps.

Then add Azure App Service Deploy task/Azure Web App task to the end of your pipeline. See below example:

- task: AzureRmWebAppDeployment@4
  inputs:
    ConnectionType: 'AzureRM'
    azureSubscription: 'SubscriptionServiceConnectionName'
    appType: 'webAppLinux'
    WebAppName: 'MyWebAppName'
    Package: '$(Build.ArtifactStagingDirectory)/dist/'
    StartupCommand: 'npm run start:prod'

You can check here for more information.


问:
how to set multiple Font Styles when checked Combobox in c#
I'd like to font style and font size in Combobox. When I selected font size after selected font style then, I select font style in Combobox again it did not work.

How can I solve it?

```<code>private void FontBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(FontBox.Text, RichTextBox.Font.Size);
    }
    catch { }
}

private void font_sizeBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(RichTextBox.Font.FontFamily,
            float.Parse(font_sizeBox.SelectedItem.ToString()));
    }
    catch { }
}
</code>```

答:
To display the fonts in a ComboBox with it's respective styles, we have to set the ComboBox DrawMode property from, Normal to DrawItemFixed. Then we can use the DrawItem event:

```<code>    public Form1()
    {
        InitializeComponent();
        comboBox1.DrawItem += comboBox1_DrawItem;
        comboBox1.DataSource = System.Drawing.FontFamily.Families.ToList();
    }
</code>```

Here, we're creating the Method comboBox1_DrawItem and assigning the DataSource for the ComboBox as the current installed Font-families.

```<code>    private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        var comboBox = (ComboBox)sender;
        var fontFamily = (FontFamily)comboBox.Items[e.Index];
        var font = new Font(fontFamily, comboBox.Font.SizeInPoints);

        e.DrawBackground();
        e.Graphics.DrawString(font.Name, font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
    }
</code>```

Then this should be the DrawItem method. You can also set comboBox1.DrawMode = DrawMode.OwnerDrawFixed; in the public of your form.

Body:
I'd like to font style and font size in Combobox. When I selected font size after selected font style then, I select font style in Combobox again it did not work.

How can I solve it?

private void FontBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(FontBox.Text, RichTextBox.Font.Size);
    }
    catch { }
}

private void font_sizeBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(RichTextBox.Font.FontFamily,
            float.Parse(font_sizeBox.SelectedItem.ToString()));
    }
    catch { }
}

Body:
To display the fonts in a ComboBox with it's respective styles, we have to set the ComboBox DrawMode property from, Normal to DrawItemFixed. Then we can use the DrawItem event:

    public Form1()
    {
        InitializeComponent();
        comboBox1.DrawItem += comboBox1_DrawItem;
        comboBox1.DataSource = System.Drawing.FontFamily.Families.ToList();
    }

Here, we're creating the Method comboBox1_DrawItem and assigning the DataSource for the ComboBox as the current installed Font-families.

    private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        var comboBox = (ComboBox)sender;
        var fontFamily = (FontFamily)comboBox.Items[e.Index];
        var font = new Font(fontFamily, comboBox.Font.SizeInPoints);

        e.DrawBackground();
        e.Graphics.DrawString(font.Name, font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
    }

Then this should be the DrawItem method. You can also set comboBox1.DrawMode = DrawMode.OwnerDrawFixed; in the public of your form.


问:
Copy data in array of a nested array of an object
So guys, I don't how to give a topic to this one. I'm having trouble to copy data from array of Object to another newly created array.

For example, I want to copy and create a new array that contain all category of animals of every person in my database.

```<code> people = [
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]
</code>```

So, I created a new array named animalCategory to hold every category available.

```<code> // declare new array to hold category of animals
 let animalCategory = []
</code>```

This is the logic I came up with:-

```<code>// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            // loop and check existing animal categories in animalCategory array
            animalCategory.forEach(category => {
                // check if MATCH?
                if(category === animal.category) {
                    break // or just continue or will NOT BE SAVE
                }

                // if NOT MATCH, then
                else {
                    // SAVE new category
                    animalCategory.push(animal.category)
                }
            })
        }
    })
})

// see result
console.log(animalCategory.length)
</code>```

But unfortunately I got like a very big array of animalCategory as a result. And a lot of repetative animals category. (like shown below)

UPDATED: the output I want to seek is:-

```<code>animalCategory: [ 'cat', 'dog', 'iguana', 'fish']
</code>```

How should I change my logic then? And is there any other way I can do this?

答:
You could try using a Set. Set are made up of only unique values.

It wont matter if you push the same value it just won't add it to the set.

If you want to then convert the categories back to an array use the Array.from Method and pass in the set.

```<code>let animalCategory = new Set()
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
          animalCategory.add(animal.category)
    })
})
animalCategory = Array.from(animalCategory)
</code>```

Body:
So guys, I don't how to give a topic to this one. I'm having trouble to copy data from array of Object to another newly created array.

For example, I want to copy and create a new array that contain all category of animals of every person in my database.

 people = [
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]

So, I created a new array named animalCategory to hold every category available.

 // declare new array to hold category of animals
 let animalCategory = []

This is the logic I came up with:-

// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            // loop and check existing animal categories in animalCategory array
            animalCategory.forEach(category => {
                // check if MATCH?
                if(category === animal.category) {
                    break // or just continue or will NOT BE SAVE
                }

                // if NOT MATCH, then
                else {
                    // SAVE new category
                    animalCategory.push(animal.category)
                }
            })
        }
    })
})

// see result
console.log(animalCategory.length)

But unfortunately I got like a very big array of animalCategory as a result. And a lot of repetative animals category. (like shown below)

UPDATED: the output I want to seek is:-

animalCategory: [ 'cat', 'dog', 'iguana', 'fish']

How should I change my logic then? And is there any other way I can do this?

Body:
You could try using a Set. Set are made up of only unique values.

It wont matter if you push the same value it just won't add it to the set.

If you want to then convert the categories back to an array use the Array.from Method and pass in the set.

let animalCategory = new Set()
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
          animalCategory.add(animal.category)
    })
})
animalCategory = Array.from(animalCategory)


问:
Merge dataframes with many rownames == NA's in R
I want to merge the following data, data1 and data2.

```<code>> data1
      A       B   C     D    E   F
alpha "Jenna" "1" "50"  "60" "7" "1"
<NA>  NA      NA  "67"  "99" NA  NA
<NA>  NA      NA  "55"  NA   NA  NA
<NA>  NA      NA  "45"  NA   NA  NA
beta  "Jenna" "1" "333" "89" "8" "1"
<NA>  NA      NA  "755" "74" NA  NA
<NA>  NA      NA  "433" NA   NA  NA
<NA>  NA      NA  "300" NA   NA  NA

> data2
      A      B   C     D     E    F
alpha "Lena" "1" "23"  "77"  "7"  "1"
<NA>  NA     NA  "67"  "103" NA   NA
<NA>  NA     NA  "55"  NA    NA   NA  # note here only have 2 rows but 3 above
deta  "Lena" "1" "599" "9"   "76" "1" #note this one is deta not beta
<NA>  NA     NA  "763" "88"  NA   NA
<NA>  NA     NA  "1"   NA    NA   NA
<NA>  NA     NA  "3"   NA    NA   NA
</code>```

into this:

Basically, merge the df according to the rownames. If not exist, fill with NA.
*I don't want to add in the extra rownames (i.e. deta) manually. I've got some idea like finding the larger nrow(df), then ... etc ??

```<code>> dput(data1)
structure(c("Jenna", NA, NA, NA, "Jenna", NA, NA, NA, "1", NA,
NA, NA, "1", NA, NA, NA, "50", "67", "55", "45", "333", "755",
"433", "300", "60", "99", NA, NA, "89", "74", NA, NA, "7", NA,
NA, NA, "8", NA, NA, NA, "1", NA, NA, NA, "1", NA, NA, NA), .Dim = c(8L,
6L), .Dimnames = list(c("alpha", NA, NA, NA, "beta", NA, NA,
NA), c("A", "B", "C", "D", "E", "F")))
> dput(data2)
structure(c("Lena", NA, NA, "Lena", NA, NA, NA, "1", NA, NA,
"1", NA, NA, NA, "23", "67", "55", "599", "763", "1", "3", "77",
"103", NA, "9", "88", NA, NA, "7", NA, NA, "76", NA, NA, NA,
"1", NA, NA, "1", NA, NA, NA), .Dim = 7:6, .Dimnames = list(c("alpha",
NA, NA, "deta", NA, NA, NA), c("A", "B", "C", "D", "E", "F")))
</code>```

答:
We may need to expand the rows based on the occurrence of NA before doing the merge.  Create a numeric index based on the non-NA elements (or use na.locf0 from zoo), split the sequence of rows of data (or get the table of 'v1', 'v2' and take the max of the frequency), expand the rows by padding NA rows based on the 'l1' and then do a merge on the row.names after filling the rownames with the non-NA element (na.locf0), change the row names of the output by replaceing some of the elements to NA

```<code>library(zoo)
v1 <- cumsum(!is.na(row.names(data1)))
v2 <- cumsum(!is.na(row.names(data2)))

lst1 <- split(seq_len(nrow(data1)), v1)
lst2 <- split(seq_len(nrow(data2)), v2)

l1 <- pmax(lengths(lst1), lengths(lst2))

dat1n <- do.call(rbind,  Map(function(x, y) data1[`length<-`(x, y), ], lst1, l1))
dat2n <- do.call(rbind,  Map(function(x, y) data2[`length<-`(x, y), ], lst2, l1))
row.names(dat1n) <- na.locf0(row.names(dat1n))
row.names(dat2n) <- na.locf0(row.names(dat2n))
out <-  merge(dat1n, dat2n, by = 'row.names', all = TRUE)

out1 <- as.matrix(out[-1])
row.names(out1) <- replace(out[,1], grepl("\\.\\d+$", out[,1]), NA)

out1
#      A.x     B.x C.x   D.x  E.x F.x A.y    B.y C.y   D.y   E.y  F.y
#alpha "Jenna" "1" "50"  "60" "7" "1" "Lena" "1" "23"  "77"  "7"  "1"
#<NA>  NA      NA  "67"  "99" NA  NA  NA     NA  "67"  "103" NA   NA
#<NA>  NA      NA  "55"  NA   NA  NA  NA     NA  "55"  NA    NA   NA
#<NA>  NA      NA  "45"  NA   NA  NA  NA     NA  NA    NA    NA   NA
#beta  "Jenna" "1" "333" "89" "8" "1" NA     NA  NA    NA    NA   NA
#<NA>  NA      NA  "755" "74" NA  NA  NA     NA  NA    NA    NA   NA
#<NA>  NA      NA  "433" NA   NA  NA  NA     NA  NA    NA    NA   NA
#<NA>  NA      NA  "300" NA   NA  NA  NA     NA  NA    NA    NA   NA
#deta  NA      NA  NA    NA   NA  NA  "Lena" "1" "599" "9"   "76" "1"
#<NA>  NA      NA  NA    NA   NA  NA  NA     NA  "763" "88"  NA   NA
#<NA>  NA      NA  NA    NA   NA  NA  NA     NA  "1"   NA    NA   NA
#<NA>  NA      NA  NA    NA   NA  NA  NA     NA  "3"   NA    NA   NA
</code>```

Body:
I want to merge the following data, data1 and data2.

> data1
      A       B   C     D    E   F
alpha "Jenna" "1" "50"  "60" "7" "1"
<NA>  NA      NA  "67"  "99" NA  NA
<NA>  NA      NA  "55"  NA   NA  NA
<NA>  NA      NA  "45"  NA   NA  NA
beta  "Jenna" "1" "333" "89" "8" "1"
<NA>  NA      NA  "755" "74" NA  NA
<NA>  NA      NA  "433" NA   NA  NA
<NA>  NA      NA  "300" NA   NA  NA

> data2
      A      B   C     D     E    F
alpha "Lena" "1" "23"  "77"  "7"  "1"
<NA>  NA     NA  "67"  "103" NA   NA
<NA>  NA     NA  "55"  NA    NA   NA  # note here only have 2 rows but 3 above
deta  "Lena" "1" "599" "9"   "76" "1" #note this one is deta not beta
<NA>  NA     NA  "763" "88"  NA   NA
<NA>  NA     NA  "1"   NA    NA   NA
<NA>  NA     NA  "3"   NA    NA   NA

into this:

Basically, merge the df according to the rownames. If not exist, fill with NA.
*I don't want to add in the extra rownames (i.e. deta) manually. I've got some idea like finding the larger nrow(df), then ... etc ??

> dput(data1)
structure(c("Jenna", NA, NA, NA, "Jenna", NA, NA, NA, "1", NA,
NA, NA, "1", NA, NA, NA, "50", "67", "55", "45", "333", "755",
"433", "300", "60", "99", NA, NA, "89", "74", NA, NA, "7", NA,
NA, NA, "8", NA, NA, NA, "1", NA, NA, NA, "1", NA, NA, NA), .Dim = c(8L,
6L), .Dimnames = list(c("alpha", NA, NA, NA, "beta", NA, NA,
NA), c("A", "B", "C", "D", "E", "F")))
> dput(data2)
structure(c("Lena", NA, NA, "Lena", NA, NA, NA, "1", NA, NA,
"1", NA, NA, NA, "23", "67", "55", "599", "763", "1", "3", "77",
"103", NA, "9", "88", NA, NA, "7", NA, NA, "76", NA, NA, NA,
"1", NA, NA, "1", NA, NA, NA), .Dim = 7:6, .Dimnames = list(c("alpha",
NA, NA, "deta", NA, NA, NA), c("A", "B", "C", "D", "E", "F")))

Body:
We may need to expand the rows based on the occurrence of NA before doing the merge.  Create a numeric index based on the non-NA elements (or use na.locf0 from zoo), split the sequence of rows of data (or get the table of 'v1', 'v2' and take the max of the frequency), expand the rows by padding NA rows based on the 'l1' and then do a merge on the row.names after filling the rownames with the non-NA element (na.locf0), change the row names of the output by replaceing some of the elements to NA

library(zoo)
v1 <- cumsum(!is.na(row.names(data1)))
v2 <- cumsum(!is.na(row.names(data2)))

lst1 <- split(seq_len(nrow(data1)), v1)
lst2 <- split(seq_len(nrow(data2)), v2)

l1 <- pmax(lengths(lst1), lengths(lst2))

dat1n <- do.call(rbind,  Map(function(x, y) data1[`length<-`(x, y), ], lst1, l1))
dat2n <- do.call(rbind,  Map(function(x, y) data2[`length<-`(x, y), ], lst2, l1))
row.names(dat1n) <- na.locf0(row.names(dat1n))
row.names(dat2n) <- na.locf0(row.names(dat2n))
out <-  merge(dat1n, dat2n, by = 'row.names', all = TRUE)

out1 <- as.matrix(out[-1])
row.names(out1) <- replace(out[,1], grepl("\\.\\d+$", out[,1]), NA)

out1
#      A.x     B.x C.x   D.x  E.x F.x A.y    B.y C.y   D.y   E.y  F.y
#alpha "Jenna" "1" "50"  "60" "7" "1" "Lena" "1" "23"  "77"  "7"  "1"
#<NA>  NA      NA  "67"  "99" NA  NA  NA     NA  "67"  "103" NA   NA
#<NA>  NA      NA  "55"  NA   NA  NA  NA     NA  "55"  NA    NA   NA
#<NA>  NA      NA  "45"  NA   NA  NA  NA     NA  NA    NA    NA   NA
#beta  "Jenna" "1" "333" "89" "8" "1" NA     NA  NA    NA    NA   NA
#<NA>  NA      NA  "755" "74" NA  NA  NA     NA  NA    NA    NA   NA
#<NA>  NA      NA  "433" NA   NA  NA  NA     NA  NA    NA    NA   NA
#<NA>  NA      NA  "300" NA   NA  NA  NA     NA  NA    NA    NA   NA
#deta  NA      NA  NA    NA   NA  NA  "Lena" "1" "599" "9"   "76" "1"
#<NA>  NA      NA  NA    NA   NA  NA  NA     NA  "763" "88"  NA   NA
#<NA>  NA      NA  NA    NA   NA  NA  NA     NA  "1"   NA    NA   NA
#<NA>  NA      NA  NA    NA   NA  NA  NA     NA  "3"   NA    NA   NA


答:
Your code is has error because:
they mistake that: ['average'] is in the index , ofcouse ['A'], ['B'] ,.... too .

You should try this:

```<code>df['average']= (abs(df['A']).values + abs(df['B']/2).values +  abs(df['C']/3).values )/3
</code>```

Title: Calculating absolute average in dataframe

Body:
My dataframe-

df= pd.DataFrame({'A':[33,-44],'B':[44,-66],'C':[66,21]})

I want to find the absolute average per row(ignoring the signs) and the formula for taking the average will be for example-

for the first row-

(33+ 44/2 + 66/3)/3 = 25.6

for second row-

(44+66/2+21/3)/3=24.3

This is not a direct average but according to a specific column the value will be divided by a specific value like for column A its 1 for column B its division by 2 and so on.

output-

        Average
     0  25.60000
     1  24.300

I did -

df[['average']]= (abs(df[['A']]).values + abs(df[['B']]/2).values +  abs(df[['C']]/3).values )/3

but its giving error

Body:
Your code is has error because:
they mistake that: ['average'] is in the index , ofcouse ['A'], ['B'] ,.... too .

You should try this:

df['average']= (abs(df['A']).values + abs(df['B']/2).values +  abs(df['C']/3).values )/3


问:
Adding multiple OnClickListeners to a RecyclerView using Kotlin
I'm in the process of fiddling my way to a working app using Kotlin and I have hit a roadblock when trying to implement OnClickListeners for my three buttons. I have my RecyclerView populate properly, but despite following the recommendations on this SO post (except in Kotlin) and following the documentation, though I am still having trouble getting the implementation to work.

The code below is my adapter class for the implementation.

```<code>class BrowseHabitsAdapter(private val habits: ArrayList<Habit>) :
    RecyclerView.Adapter<BrowseHabitsAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.habit_card, parent, false)

        return ViewHolder(itemView, object: HabitClickListener {
            override fun onDecrease(position: Int) {
                val streak = itemView.dayCounter.text.toString().toInt()
                itemView.dayCounter.text = streak.dec().toString()
            }

            override fun onIncrease(position: Int) {
                val streak = itemView.dayCounter.text.toString().toInt()
                itemView.dayCounter.text = streak.inc().toString()
            }

            override fun onEdit(position: Int) {
                TODO("Change Activity to Edit")
            }
        })

    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentItem = habits[position]

        holder.habitTitle.text = currentItem.title
        holder.streak.text = currentItem.streak.toString()
    }

    override fun getItemCount() = habits.size

    class ViewHolder(itemView : View, listener : HabitClickListener) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
        val habitTitle: TextView = itemView.habitTitle
        val streak: TextView = itemView.dayCounter
        val decreaseCounterButton : Button = itemView.decreaseCounterButton
        val increaseCounterButton : Button = itemView.increaseCounterButton
        val listener = listener

        init {
            decreaseCounterButton.setOnClickListener(this)
            increaseCounterButton.setOnClickListener(this)
        }

        override fun onClick(v: View?) {
            when (itemView.id) {
                itemView.decreaseCounterButton.id -> listener.onDecrease(this.layoutPosition)
                itemView.increaseCounterButton.id -> listener.onIncrease(this.layoutPosition)
            }
        }
    }

    interface HabitClickListener {
        fun onDecrease(position : Int)
        fun onIncrease(position : Int)
        fun onEdit(position : Int)
    }
}
</code>```

and the following is my XML code defining one of my cards:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="10dp"
    app:cardBackgroundColor="#eeeeee"
    app:cardCornerRadius="10dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/cardHeader"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/habitTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="10dp"
                android:text="@string/default_card_title"
                android:textSize="18sp" />

            <Space
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1" />

            <ImageView
                android:id="@+id/settingsIcon"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_gravity="bottom"
                android:layout_marginRight="10dp"
                app:srcCompat="@android:drawable/ic_menu_manage" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/cardControls"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <Button
                android:id="@+id/decreaseCounterButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="-"
                android:textAllCaps="false"
                android:textSize="30sp" />

            <Space
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1" />

            <TextView
                android:id="@+id/dayCounter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:fontFamily="sans-serif-medium"
                android:text="0"
                android:textAlignment="center"
                android:textSize="30sp"
                android:textStyle="bold" />

            <Space
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1" />

            <Button
                android:id="@+id/increaseCounterButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="+"
                android:textSize="30sp" />
        </LinearLayout>

    </LinearLayout>

</androidx.cardview.widget.CardView>
</code>```

Any additional explanation that can be provided as to what I did wrong and what is going on in detail would be really appreciated!

答:
It should be view?.id instead of itemView.id

```<code>        override fun onClick(v: View?) {
            when (v?.id) {
                itemView.decreaseCounterButton.id -> listener.onDecrease(this.layoutPosition)
                itemView.increaseCounterButton.id -> listener.onIncrease(this.layoutPosition)
            }
        }
</code>```

Additionally, your code with bugs. You handle HabitClickListener only update UI, when you scroll your data will be update base on habits. It means it will be revert when you scroll. Make sure streak of model Habit is var

```<code>        return ViewHolder(itemView, object: HabitClickListener {
            override fun onDecrease(position: Int) {
                habits[position].streak = habits[position].streak.dec()
                itemView.dayCounter.text = shabits[position].streak.toString()
            }

            override fun onIncrease(position: Int) {
                habits[position].streak = habits[position].streak.inc()
                itemView.dayCounter.text = shabits[position].streak.toString()
            }

            override fun onEdit(position: Int) {
                TODO("Change Activity to Edit")
            }
        })
</code>```

Body:
I'm in the process of fiddling my way to a working app using Kotlin and I have hit a roadblock when trying to implement OnClickListeners for my three buttons. I have my RecyclerView populate properly, but despite following the recommendations on this SO post (except in Kotlin) and following the documentation, though I am still having trouble getting the implementation to work.

The code below is my adapter class for the implementation.

class BrowseHabitsAdapter(private val habits: ArrayList<Habit>) :
    RecyclerView.Adapter<BrowseHabitsAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.habit_card, parent, false)

        return ViewHolder(itemView, object: HabitClickListener {
            override fun onDecrease(position: Int) {
                val streak = itemView.dayCounter.text.toString().toInt()
                itemView.dayCounter.text = streak.dec().toString()
            }

            override fun onIncrease(position: Int) {
                val streak = itemView.dayCounter.text.toString().toInt()
                itemView.dayCounter.text = streak.inc().toString()
            }

            override fun onEdit(position: Int) {
                TODO("Change Activity to Edit")
            }
        })

    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentItem = habits[position]

        holder.habitTitle.text = currentItem.title
        holder.streak.text = currentItem.streak.toString()
    }

    override fun getItemCount() = habits.size

    class ViewHolder(itemView : View, listener : HabitClickListener) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
        val habitTitle: TextView = itemView.habitTitle
        val streak: TextView = itemView.dayCounter
        val decreaseCounterButton : Button = itemView.decreaseCounterButton
        val increaseCounterButton : Button = itemView.increaseCounterButton
        val listener = listener

        init {
            decreaseCounterButton.setOnClickListener(this)
            increaseCounterButton.setOnClickListener(this)
        }

        override fun onClick(v: View?) {
            when (itemView.id) {
                itemView.decreaseCounterButton.id -> listener.onDecrease(this.layoutPosition)
                itemView.increaseCounterButton.id -> listener.onIncrease(this.layoutPosition)
            }
        }
    }

    interface HabitClickListener {
        fun onDecrease(position : Int)
        fun onIncrease(position : Int)
        fun onEdit(position : Int)
    }
}

and the following is my XML code defining one of my cards:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="10dp"
    app:cardBackgroundColor="#eeeeee"
    app:cardCornerRadius="10dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/cardHeader"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/habitTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="10dp"
                android:text="@string/default_card_title"
                android:textSize="18sp" />

            <Space
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1" />

            <ImageView
                android:id="@+id/settingsIcon"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_gravity="bottom"
                android:layout_marginRight="10dp"
                app:srcCompat="@android:drawable/ic_menu_manage" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/cardControls"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <Button
                android:id="@+id/decreaseCounterButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="-"
                android:textAllCaps="false"
                android:textSize="30sp" />

            <Space
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1" />

            <TextView
                android:id="@+id/dayCounter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:fontFamily="sans-serif-medium"
                android:text="0"
                android:textAlignment="center"
                android:textSize="30sp"
                android:textStyle="bold" />

            <Space
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1" />

            <Button
                android:id="@+id/increaseCounterButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="+"
                android:textSize="30sp" />
        </LinearLayout>

    </LinearLayout>

</androidx.cardview.widget.CardView>

Any additional explanation that can be provided as to what I did wrong and what is going on in detail would be really appreciated!

Body:
It should be view?.id instead of itemView.id

        override fun onClick(v: View?) {
            when (v?.id) {
                itemView.decreaseCounterButton.id -> listener.onDecrease(this.layoutPosition)
                itemView.increaseCounterButton.id -> listener.onIncrease(this.layoutPosition)
            }
        }

Additionally, your code with bugs. You handle HabitClickListener only update UI, when you scroll your data will be update base on habits. It means it will be revert when you scroll. Make sure streak of model Habit is var

        return ViewHolder(itemView, object: HabitClickListener {
            override fun onDecrease(position: Int) {
                habits[position].streak = habits[position].streak.dec()
                itemView.dayCounter.text = shabits[position].streak.toString()
            }

            override fun onIncrease(position: Int) {
                habits[position].streak = habits[position].streak.inc()
                itemView.dayCounter.text = shabits[position].streak.toString()
            }

            override fun onEdit(position: Int) {
                TODO("Change Activity to Edit")
            }
        })


答:
try:

```<code>df["average"] = (df.abs()/np.arange(1,4)).mean(axis=1)
</code>```

if there are more columns then:

```<code>df["average"] = (df[['A','B','C']].abs()/np.arange(1,4)).mean(axis=1)
</code>```

Body:
try:

df["average"] = (df.abs()/np.arange(1,4)).mean(axis=1)

if there are more columns then:

df["average"] = (df[['A','B','C']].abs()/np.arange(1,4)).mean(axis=1)


问:
Understanding the wss.clients object in the ws npm package
I am working with the npm ws library on a Node.js server. I was looking at the documentation and found a way to loop through the clients to, for example, send a message to everyone using the wss.clients object:

```<code>const WebSocket = require('ws');
const wss = new WebSocket.server({ port:8080 });
//...
wss.clients.forEach(client => {
  client.send("A message to you!");
});
</code>```

I initially thought that wss.clients was an array because it let me iterate through it with the array prototype forEach(), but when I tried running wss.clients.find() on it to send a message only to a specific connection, I got an error:

```<code>TypeError: wss.clients.find is not a function
</code>```

I ran console.log(Array.isArray(wss.clients)) it said false. When I tried console.log(wss.clients), I got an object looking like this:

```<code>Set { WebSocket { ... } }
</code>```

So, my question is, how is the wss.clients object able to run the array prototype forEach()? It worked without using Object.keys() or anything.
I also tried wss.clients.pop() out of curiosity, and it gave another type error.

What really is wss.clients? An object or an array?

答:
I have discovered (thanks to @waiaan) that the type of wss.clients is a Set.
Sets have different methods than arrays, but they are similar.

The best implementation for Set.prototype.find() would be to define a method like this:

```<code>Set.prototype.find = function(cb) {
    for (const e of this) {
        if (cb(e)) {
            return e;
        }
    }
}
</code>```

More about arrays and sets in this article.

Body:
I am working with the npm ws library on a Node.js server. I was looking at the documentation and found a way to loop through the clients to, for example, send a message to everyone using the wss.clients object:

const WebSocket = require('ws');
const wss = new WebSocket.server({ port:8080 });
//...
wss.clients.forEach(client => {
  client.send("A message to you!");
});

I initially thought that wss.clients was an array because it let me iterate through it with the array prototype forEach(), but when I tried running wss.clients.find() on it to send a message only to a specific connection, I got an error:

TypeError: wss.clients.find is not a function

I ran console.log(Array.isArray(wss.clients)) it said false. When I tried console.log(wss.clients), I got an object looking like this:

Set { WebSocket { ... } }

So, my question is, how is the wss.clients object able to run the array prototype forEach()? It worked without using Object.keys() or anything.
I also tried wss.clients.pop() out of curiosity, and it gave another type error.

What really is wss.clients? An object or an array?

Body:
I have discovered (thanks to @waiaan) that the type of wss.clients is a Set.
Sets have different methods than arrays, but they are similar.

The best implementation for Set.prototype.find() would be to define a method like this:

Set.prototype.find = function(cb) {
    for (const e of this) {
        if (cb(e)) {
            return e;
        }
    }
}

More about arrays and sets in this article.


答:
Here's an example that gets the output you're looking for with duplicates removed.

people = [
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ];

 const uniqAnimals = [...new Set(people.flatMap(p => p.animals).map(a => a.category))];

 console.log(uniqAnimals);```

Title: Copy data in array of a nested array of an object


问:
appends duplicated in next object
I have two objects of the same class, which has an array property. After populating the first array, then the second, the second array prepends the values in the first.</p>

```<code>from random import *
class Army:
    divisions = []
    def __init__(self, name):
        self.name = name
def rnd(max):
    return randint(0, max - 1)
def init_army(i):
    army = Army(names[i])
    armies.append(army)
    divisions = rnd(num_divisions) + 1
    for i in range(divisions):
        army.divisions.append(rnd(num_divisions) + 1)
names = ["name1", "name2"]
armies = []
num_armies = 2
num_divisions = 6
for i in range(num_armies):
    init_army(i)
    print(armies[i].name, armies[i].divisions)
Typical Output:
name1 [5, 1]
name2 [5, 1, 2, 5, 6, 2, 1]
</code>```

答:
The lines

```<code>class Army:
    divisions = []
</code>```

make divisions a class attribute.

Turn it into an instance attribute:

```<code>class Army:

    def __init__(self, name):
        self.divisions = []
        self.name = name
</code>```

In python there is no declaration. Instead, names (variables and attributes) are defined by assignment.

Where you assign things matters.

Please have a look at namespaces

Title: appends duplicated in next object

Body:
I have two objects of the same class, which has an array property. After populating the first array, then the second, the second array prepends the values in the first.

from random import *
class Army:
    divisions = []
    def __init__(self, name):
        self.name = name
def rnd(max):
    return randint(0, max - 1)
def init_army(i):
    army = Army(names[i])
    armies.append(army)
    divisions = rnd(num_divisions) + 1
    for i in range(divisions):
        army.divisions.append(rnd(num_divisions) + 1)
names = ["name1", "name2"]
armies = []
num_armies = 2
num_divisions = 6
for i in range(num_armies):
    init_army(i)
    print(armies[i].name, armies[i].divisions)
Typical Output:
name1 [5, 1]
name2 [5, 1, 2, 5, 6, 2, 1]

Body:
The lines

class Army:
    divisions = []

make divisions a class attribute.

Turn it into an instance attribute:

class Army:

    def __init__(self, name):
        self.divisions = []
        self.name = name

In python there is no declaration. Instead, names (variables and attributes) are defined by assignment.

Where you assign things matters.

Please have a look at namespaces


问:
Using purrr modify2 to modify a vector, based on elements of two vectors
I'm attempting to modify values in a vector, based on two conditions using two different vectors and purrr::modify2, haven't quite got the syntax correct and can't find examples on web.  Here is mwe:

```<code>library(tidyverse)
library(magrittr)
arr1 <- c(6, 2, 3, 2, 1, 5, 4, 2, 3, 7)
arr2 <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
prob <- c(0.65, 0.45)

arr1 %<>% modify2(arr1,
                  arr2,
                  ~ if (.x == 2 & .y == 0) ~ rbinom(1,1,prob[1]) * 2
                  else
                       if (.x == 2 & .y != 0) ~ rbinom(1,1,prob[2]) * 2)
</code>```

I'm trying to get it to find when .x == 2 and .y == 0 (same index in both arrays), then replace the 2 in .x with the value generated by rbinom(1,1,prob[1]) * 2, which I think should be either 0 or 2? Then if .x == 2 and .y != 0, use a different probability to replace the value in arr1.  I also want the rbinom calculation done individually for each entry, if that makes sense?  Do I need to use function (x) ......   notation to make it evaluates for each instance? Obviously simpler and/or more elegant solutions most welcome. Thx. J

答:
One potential solution is to use case_when:

```<code>arr1 <- modify2(arr1, arr2, ~dplyr::case_when(
  .x == 2 && .y == 0 ~ rbinom(1,1,prob[1]) * 2,
  .x == 2 && .y != 0 ~ rbinom(1,1,prob[2]) * 2,
  TRUE ~ .x ))
</code>```

Note that you don't need %<>%; you are already passing arr1 as the first argument, so you can simply assign the result back with the standard <-.

Body:
I'm attempting to modify values in a vector, based on two conditions using two different vectors and purrr::modify2, haven't quite got the syntax correct and can't find examples on web.  Here is mwe:

library(tidyverse)
library(magrittr)
arr1 <- c(6, 2, 3, 2, 1, 5, 4, 2, 3, 7)
arr2 <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
prob <- c(0.65, 0.45)

arr1 %<>% modify2(arr1,
                  arr2,
                  ~ if (.x == 2 & .y == 0) ~ rbinom(1,1,prob[1]) * 2
                  else
                       if (.x == 2 & .y != 0) ~ rbinom(1,1,prob[2]) * 2)

I'm trying to get it to find when .x == 2 and .y == 0 (same index in both arrays), then replace the 2 in .x with the value generated by rbinom(1,1,prob[1]) * 2, which I think should be either 0 or 2? Then if .x == 2 and .y != 0, use a different probability to replace the value in arr1.  I also want the rbinom calculation done individually for each entry, if that makes sense?  Do I need to use function (x) ......   notation to make it evaluates for each instance? Obviously simpler and/or more elegant solutions most welcome. Thx. J

Body:
One potential solution is to use case_when:

arr1 <- modify2(arr1, arr2, ~dplyr::case_when(
  .x == 2 && .y == 0 ~ rbinom(1,1,prob[1]) * 2,
  .x == 2 && .y != 0 ~ rbinom(1,1,prob[2]) * 2,
  TRUE ~ .x ))

Note that you don't need %<>%; you are already passing arr1 as the first argument, so you can simply assign the result back with the standard <-.