问:
LiveData from room and MutableLiveData to display error message
Source code can be found at : https://github.com/AliRezaeiii/TVMaze

I have following repository class :

```<code>class ShowRepository(
    private val showDao: ShowDao,
    private val api: TVMazeService
) {

    /**
     * A list of shows that can be shown on the screen.
     */
    val shows: LiveData<List<Show>> =
        Transformations.map(showDao.getShows()) {
            it.asDomainModel()
        }

    /**
     * Refresh the shows stored in the offline cache.
     */
    suspend fun refreshShows(): Result<List<Show>> = withContext(Dispatchers.IO) {
        try {
            val news = api.fetchShowList().await()
            showDao.insertAll(*news.asDatabaseModel())
            Result.Success(news)
        } catch (err: HttpException) {
            Result.Error(err)
        }
    }
}
</code>```

As I understand Room does not support MutableLiveData rather it support LiveData. So I have created two object in my ViewModel to be observed :

```<code>class MainViewModel(
    private val repository: ShowRepository,
    app: Application
) : AndroidViewModel(app) {

    private val _shows = repository.shows
    val shows: LiveData<List<Show>>
        get() = _shows

    private val _liveData = MutableLiveData<Result<List<Show>>>()
    val liveData: LiveData<Result<List<Show>>>
        get() = _liveData

    /**
     * init{} is called immediately when this ViewModel is created.
     */
    init {
        if (isNetworkAvailable(app)) {
            viewModelScope.launch {
                _liveData.postValue(repository.refreshShows())
            }
        }
    }
}
</code>```

I use show LiveData varialbe to submit list in my Activity :

```<code>viewModel.shows.observe(this, Observer { shows ->
            viewModelAdapter.submitList(shows)
        })
</code>```

And I use LiveData variable to display error message when an exception occurs in refreshShows() of repository :

```<code>viewModel.liveData.observe(this, Observer { result ->
            if (result is Result.Error) {
                Toast.makeText(this, getString(R.string.failed_loading_msg), Toast.LENGTH_LONG).show()
                Timber.e(result.exception)
            }
        })
</code>```

Do you think is there a better solution to have one LiveData in ViewModel rather than two?

答: I think you can improve ur code, using this repo as a base. It uses a single source of truth strategy using livedata. I think you will have to dig the repo a bit to understand the code, but to sum up, this code will get data from the api, store in ur room, and provide ur room query's anwer as a result, so observing this will do it all.</p>

Body:
Source code can be found at : https://github.com/AliRezaeiii/TVMaze

I have following repository class :

class ShowRepository(
    private val showDao: ShowDao,
    private val api: TVMazeService
) {

    /**
     * A list of shows that can be shown on the screen.
     */
    val shows: LiveData<List<Show>> =
        Transformations.map(showDao.getShows()) {
            it.asDomainModel()
        }

    /**
     * Refresh the shows stored in the offline cache.
     */
    suspend fun refreshShows(): Result<List<Show>> = withContext(Dispatchers.IO) {
        try {
            val news = api.fetchShowList().await()
            showDao.insertAll(*news.asDatabaseModel())
            Result.Success(news)
        } catch (err: HttpException) {
            Result.Error(err)
        }
    }
}

As I understand Room does not support MutableLiveData rather it support LiveData. So I have created two object in my ViewModel to be observed :

class MainViewModel(
    private val repository: ShowRepository,
    app: Application
) : AndroidViewModel(app) {

    private val _shows = repository.shows
    val shows: LiveData<List<Show>>
        get() = _shows

    private val _liveData = MutableLiveData<Result<List<Show>>>()
    val liveData: LiveData<Result<List<Show>>>
        get() = _liveData

    /**
     * init{} is called immediately when this ViewModel is created.
     */
    init {
        if (isNetworkAvailable(app)) {
            viewModelScope.launch {
                _liveData.postValue(repository.refreshShows())
            }
        }
    }
}

I use show LiveData varialbe to submit list in my Activity :

viewModel.shows.observe(this, Observer { shows ->
            viewModelAdapter.submitList(shows)
        })

And I use LiveData variable to display error message when an exception occurs in refreshShows() of repository :

viewModel.liveData.observe(this, Observer { result ->
            if (result is Result.Error) {
                Toast.makeText(this, getString(R.string.failed_loading_msg), Toast.LENGTH_LONG).show()
                Timber.e(result.exception)
            }
        })

Do you think is there a better solution to have one LiveData in ViewModel rather than two?


来源: stackexchange

问:
Flyway command line: Invalid argument: -placeholders
What is the exact syntax required to pass a placeholder to flyway command line?

I have attempted to add a placeholder to my flyway command line migrate but getting exceptions when calling it.
I have been back to the documentation several times re-checking syntax/case/etc but cannot spot what I am doing wrong here.

It looks something like this

flyway -url="jdbc:postgresql://<host>:<port>/<database>" -user=<user> -password=<pwd> -placeholders.abc=123 migrate -X

And I get this exception

```<code>org.flywaydb.core.api.FlywayException: Invalid argument: -placeholders
        at org.flywaydb.commandline.CommandLineArguments.validate(CommandLineArguments.java:183)
        at org.flywaydb.commandline.Main.main(Main.java:86)```
```

答:
Turns out on windows that I needed to enclose the placeholders in double quotes.

flyway -url="jdbc:postgresql://<host>:<port>/<database>" -user=<user> -password=<pwd> "-placeholders.abc=123" migrate -X

ContentLicense: CC BY-SA 4.0

Body:
What is the exact syntax required to pass a placeholder to flyway command line?

I have attempted to add a placeholder to my flyway command line migrate but getting exceptions when calling it.
I have been back to the documentation several times re-checking syntax/case/etc but cannot spot what I am doing wrong here.

It looks something like this

flyway -url="jdbc:postgresql://<host>:<port>/<database>" -user=<user> -password=<pwd> -placeholders.abc=123 migrate -X

And I get this exception

org.flywaydb.core.api.FlywayException: Invalid argument: -placeholders
        at org.flywaydb.commandline.CommandLineArguments.validate(CommandLineArguments.java:183)
        at org.flywaydb.commandline.Main.main(Main.java:86)```


问:
What's the meaning of some sort of custom binary file?
In Head First C book, there is a "there are no dumb questions" section.

Are bitfields really just used to save space?

No, They're important if you need to read low-level binary information

Such as?

If you're reading or writing some sort of custom binary file.

What is that mean?

答:
I'm not sure if this is what the author was referring to, but here's an imaginary example where one might be tempted to use a bitfield:

Let's say we define an image file format. To display the image, the software needs to know the dimensions of that image, so we decide that our file format should start with a header defining the dimensions of the image. Let's also assume that - for some reason - we don't ever want to store images larger than, say, 16x16 pixels. Therefore we then decide that we can save space by not using full bytes to specify the dimensions in x and y, but instead we just use 4 bits each.

In a case like that, someone might want to use a bitfield, because it allows easy access to parts of a byte (or integers in general). However, since bitfields are not portable, you would still be better off doing the bit-manipulation by hand.


问:
checking 2nd part of expression is an increment of the 1st
Specifically, I'm looking to create a Reg Ex for a tax year in the format yyyy/yy where 2019/20 would correspond to the tax year of 06/04/2019 to 05/04/2020.

So the basic reg ex we have is ^2[0-9]{3}-[0-9]{2}$ which works to ensure the format is correct but will allow the likes of 2019-30 or 2019-18 etc when the only possible ending for 2019 is 20.

So does anyone know how I would validate that the section after the "/" was the last 2 digits of section 1 incremented by 1? If it was going to be 100% correct then this would also though have to take into account 2099/00 for 2099/2100.

So valid examples would include:
2001/02, 2002/03...2010/11, 2012/13, 2099/00 all the way through to 2999/00

Invalid would be anything where the 2 sections were not exactly +1 different so the likes of:
2010/12, 2100/10, 2010/09, 2019/19 etc

Any pointers for this would be appreciated.

答:
file f1

```<code>2012/13
2012/02
2012/12
2199/00
2199/11
</code>```

script f1.awk

```<code>match($1, /2[0-9]([0-9]{2})/, m) {
  if (($2 == m[1]+1) || (m[1] == 99 && $2 == "00")) {
    print($1"/"$2)
  }
}
</code>```

call:

```<code>gawk -F"/" -f f1.awk f1
</code>```

result:

```<code>2012/13
2199/00
</code>```

Explanation:

```<code>-F"/"     sets / as field separator
m[1]      is a reference to a group of 2 numbers set in regex
IF        checks the assumed condition
          and takes into account the special case 99/00
</code>```

Body:
file f1

2012/13
2012/02
2012/12
2199/00
2199/11

script f1.awk

match($1, /2[0-9]([0-9]{2})/, m) {
  if (($2 == m[1]+1) || (m[1] == 99 && $2 == "00")) {
    print($1"/"$2)
  }
}

call:

gawk -F"/" -f f1.awk f1

result:

2012/13
2199/00

Explanation:

-F"/"     sets / as field separator
m[1]      is a reference to a group of 2 numbers set in regex
IF        checks the assumed condition
          and takes into account the special case 99/00


问:
Should I use high-resolution time types as parameters to avoid duration_casts?
I read that if the highest resolution type your program uses is, say, milliseconds and this type will cover the whole range your values are in, you should stick with it mostly, to avoid having duration_casts everywhere.
Instead you would have only one, inside the function, if all you need is a precision of, let's say, seconds.

However, for return types of functions you would conversely return the lowest resolution possible, to have the lowest possible amount of duration_casts (and here even optimal performance, since you would do the conversion anyway in this case).

Unfortunately I didn't find a source that covers this issue comprehensively (or really, in any way). Is this the way std::chrono should be used (assuming one is not eager about the last possible bit of performance)?

答:
I don't think there's a lot one can say in general about this strategy except that yes, you don't want to needlessly litter your code with duration_cast.  Reserve duration_cast only for those conversions where you want to truncate the precision.  And in those cases recognize that duration_cast truncates towards zero.  C++17 introduces 3 other truncation strategies:

floor: truncate towards negative infinity

ceil: truncate towards positive infinity

round: truncate towards nearest, towards even on tie

(If you are in C++11/14 you can grab these handy utilities here).

And certainly if milliseconds is the finest precision you want to deal with, taking milliseconds as parameter types is a good strategy.

Using a coarser precision for return types might be good for some applications, but probably not for all.  Consider:

```<code>seconds process(milliseconds input);
</code>```

process is some function that takes a duration input, performs some operation on it, and returns the duration output.  And in this example I've chosen a coarser precision than the input (seconds).  Presumably, at some point I've truncated the precision of the input, and in the process lost information.

Now if the purpose of process is to truncate precision, this is perfectly fine.  But if the purpose of process is something else and you're just returning seconds so that clients can do either of:

```<code>milliseconds result1 = process(input);
seconds      result2 = process(input);
</code>```

then you may not be doing the client any favors.  Certainly the syntax for obtaining result2 is very clean.  But you've also taken away the choice of this client on the direction of truncation (down, up, nearest, etc.).  Maybe that is a good thing for your application.  But it won't be a good thing for everyone, and thus not for a general purpose library.

As another example, lets look at the return type of one of the functions in <chrono> itself:

```<code>template<class Rep1, class Period1, class Rep2, class Period2>
constexpr
common_type_t<duration<Rep1, Period1>, duration<Rep2, Period2>>
operator+(const duration<Rep1, Period1>& lhs,
          const duration<Rep2, Period2>& rhs);
</code>```

In this example the function (operator+) returns the finest precision from its inputs as opposed to the coarsest, in an effort to not loose any information.  The client is free to truncate that result if desired.  For those who aren't familiar with common_type_t, this is consistent with:

```<code>constexpr
milliseconds
operator+(const seconds& lhs, const milliseconds& rhs);
</code>```

Body:
I don't think there's a lot one can say in general about this strategy except that yes, you don't want to needlessly litter your code with duration_cast.  Reserve duration_cast only for those conversions where you want to truncate the precision.  And in those cases recognize that duration_cast truncates towards zero.  C++17 introduces 3 other truncation strategies:

floor: truncate towards negative infinity

ceil: truncate towards positive infinity

round: truncate towards nearest, towards even on tie

(If you are in C++11/14 you can grab these handy utilities here).

And certainly if milliseconds is the finest precision you want to deal with, taking milliseconds as parameter types is a good strategy.

Using a coarser precision for return types might be good for some applications, but probably not for all.  Consider:

seconds process(milliseconds input);

process is some function that takes a duration input, performs some operation on it, and returns the duration output.  And in this example I've chosen a coarser precision than the input (seconds).  Presumably, at some point I've truncated the precision of the input, and in the process lost information.

Now if the purpose of process is to truncate precision, this is perfectly fine.  But if the purpose of process is something else and you're just returning seconds so that clients can do either of:

milliseconds result1 = process(input);
seconds      result2 = process(input);

then you may not be doing the client any favors.  Certainly the syntax for obtaining result2 is very clean.  But you've also taken away the choice of this client on the direction of truncation (down, up, nearest, etc.).  Maybe that is a good thing for your application.  But it won't be a good thing for everyone, and thus not for a general purpose library.

As another example, lets look at the return type of one of the functions in <chrono> itself:

template<class Rep1, class Period1, class Rep2, class Period2>
constexpr
common_type_t<duration<Rep1, Period1>, duration<Rep2, Period2>>
operator+(const duration<Rep1, Period1>& lhs,
          const duration<Rep2, Period2>& rhs);

In this example the function (operator+) returns the finest precision from its inputs as opposed to the coarsest, in an effort to not loose any information.  The client is free to truncate that result if desired.  For those who aren't familiar with common_type_t, this is consistent with:

constexpr
milliseconds
operator+(const seconds& lhs, const milliseconds& rhs);


问:
Razor in-line if statement not working?
I've got an exception throwing at this line, and can't figure out why...maybe someone else can spot it

```<code><img src="@{Model.Image != null ? Model.Image.FileName : "";}" width="200px" id="ImagePreview"/>
</code>```

The exception I'm getting is:

```<code>error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
</code>```

答:
You need to use the expression (explicit) code block style for that expression:

```<code><img src="@(Model.Image != null ? Model.Image.FileName : "")" width="200px" id="ImagePreview"/>
</code>```

see the gu's post

ContentLicense: CC BY-SA 3.0

Title: Razor in-line if statement not working?

Body:
I've got an exception throwing at this line, and can't figure out why...maybe someone else can spot it

The exception I'm getting is:

error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Body:
You need to use the expression (explicit) code block style for that expression:

<img src="@(Model.Image != null ? Model.Image.FileName : "")" width="200px" id="ImagePreview"/>

see the gu's post


问:
Read AWS S3 GZIP Object using GetObjectRequest with range
I am trying to read a big AWS S3 Compressed Object(gz).I don't want to read the whole object, want to read it in parts,so that i can process the uncompressed data in parallel
I am reading it with GetObjectRequest with "Range" Header, where i am setting byte range.
However, when i give a byte range in between (100,200), it fails with "Not in GZIP format"
The reason for failure is , AWS request return a stream,however when i parse it to GZIPInputStream it fails as "GZIPInputStream" expects the first byte (GZIP_MAGIC = 0x8b1f) to confirm is it gzip , which is not present in the stream.

```<code>   GetObjectRequest rangeObjectRequest = new GetObjectRequest(<<Bucket>>, <<Key>>).withRange(100, 200);
   S3Object object = s3Client.getObject(rangeObjectRequest);
   S3ObjectInputStream rawData = object.getObjectContent();
   InputStream data =  new GZIPInputStream(rawData);
</code>```

Can anyone guide the right approach?

答:
GZIP is a compression format in which each byte in the file depends on all of the bytes that precede it. Which means that you can't pick an arbitrary byte range out of the file and make sense of it.

If you need to read byte ranges, you'll need to store it uncompressed.

You could also create your own file storage format that stores chunks of the file as separately-compressed blocks. You could do this using the ZIP format, where each file in the archive represents a specific block size. But you'd need to implement your own ZIP directory reader to make that work.

Body:
I am trying to read a big AWS S3 Compressed Object(gz).I don't want to read the whole object, want to read it in parts,so that i can process the uncompressed data in parallel
I am reading it with GetObjectRequest with "Range" Header, where i am setting byte range.
However, when i give a byte range in between (100,200), it fails with "Not in GZIP format"
The reason for failure is , AWS request return a stream,however when i parse it to GZIPInputStream it fails as "GZIPInputStream" expects the first byte (GZIP_MAGIC = 0x8b1f) to confirm is it gzip , which is not present in the stream.

   GetObjectRequest rangeObjectRequest = new GetObjectRequest(<<Bucket>>, <<Key>>).withRange(100, 200);
   S3Object object = s3Client.getObject(rangeObjectRequest);
   S3ObjectInputStream rawData = object.getObjectContent();
   InputStream data =  new GZIPInputStream(rawData);

Can anyone guide the right approach?


问:
Do I need to release the COM object on every 'foreach' iteration?
Here's the (potential) problem:

I create a COM object, and then use a 'foreach' to iterate through each element in a collection it returns.  Do I need to release each individual element I iterate through in the collection?  (See code below.)  If so, I can't think of a way to effectively to release it from within a 'finally' statement, just in case there is an error as the item is being operated upon.

Any suggestions?

```<code>private static void doStuff()
{
    ComObjectClass manager = null;

    try
    {
        manager = new ComObjectClass();
        foreach (ComObject item in manager.GetCollectionOfItems())
        {
            Log.Debug(item.Name);
            releaseComObject(item); // <-- Do I need this line?
                                    //     It isn't in a 'finally' block...
                                    //             ...Possible memory leak?
        }
    }
    catch (Exception) { }
    finally
    {
        releaseComObject(manager);
    }
}

private static void releaseComObject(object instance)
{
    if (instance != null)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(instance);
        }
        catch
        {
            /* log potential memory leak */
            Log.Debug("Potential memory leak: Unable to release COM object.");
        }
        finally
        {
            instance = null;
        }
    }
}
</code>```

答:
Another way is to create your own iterator function :

IEnumerable<ComObject> GetChildItems(this ComObjectClass manager) {
    ComObject comObject = null;

    ComObject[] collectionOfComItems = manager.GetCollectionOfItems();
    for (int i = 0; i < collectionOfComItems.Length; i++) {
        try {
            comObject = collectionOfComItems[i];

            yield return comObject;
        } finally {
            if (comObject != null)
                Marshal.ReleaseComObject(comObject);
        }
    }

    yield break;
}

private static void doStuff() {
    ComObjectClass manager = null;

    try {
        manager = new ComObjectClass();

        foreach (ComObject item in manager.GetChildItems()) {
            Log.Debug(item.Name);
        }
    } finally {
        releaseComObject(manager);
    }
}
```

I feel this makes your code much more readable, especially if you need to iterate through the child items at multiple times.

ContentLicense: CC BY-SA 2.5

Body:
Here's the (potential) problem:

I create a COM object, and then use a 'foreach' to iterate through each element in a collection it returns.  Do I need to release each individual element I iterate through in the collection?  (See code below.)  If so, I can't think of a way to effectively to release it from within a 'finally' statement, just in case there is an error as the item is being operated upon.

Any suggestions?

private static void doStuff()
{
    ComObjectClass manager = null;

    try
    {
        manager = new ComObjectClass();
        foreach (ComObject item in manager.GetCollectionOfItems())
        {
            Log.Debug(item.Name);
            releaseComObject(item); // <-- Do I need this line?
                                    //     It isn't in a 'finally' block...
                                    //             ...Possible memory leak?
        }
    }
    catch (Exception) { }
    finally
    {
        releaseComObject(manager);
    }
}

private static void releaseComObject(object instance)
{
    if (instance != null)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(instance);
        }
        catch
        {
            /* log potential memory leak */
            Log.Debug("Potential memory leak: Unable to release COM object.");
        }
        finally
        {
            instance = null;
        }
    }
}

Body:
Another way is to create your own iterator function :

IEnumerable<ComObject> GetChildItems(this ComObjectClass manager) {
    ComObject comObject = null;

    ComObject[] collectionOfComItems = manager.GetCollectionOfItems();
    for (int i = 0; i < collectionOfComItems.Length; i++) {
        try {
            comObject = collectionOfComItems[i];

            yield return comObject;
        } finally {
            if (comObject != null)
                Marshal.ReleaseComObject(comObject);
        }
    }

    yield break;
}

private static void doStuff() {
    ComObjectClass manager = null;

    try {
        manager = new ComObjectClass();

        foreach (ComObject item in manager.GetChildItems()) {
            Log.Debug(item.Name);
        }
    } finally {
        releaseComObject(manager);
    }
}

I feel this makes your code much more readable, especially if you need to iterate through the child items at multiple times.


问:
Rails image_tag width attribute to use a percentage / auto value?
image_tag('batman.png' size:'100%xauto')

The size 100% x Auto is ignored as it does not follow the convention outlined in the Rails API.

Is there a way to do this in rails without the need of a global / specific css class?

答:
```<code><%= image_tag('batman.png', :size => '100%xauto') %>
</code>```


问:
how can I calculate totals within a query, depending on the date?
Below you can see my query, which gives the following result:

```<code>select t.actual_date,
   t.id_key,
   t.attendance_status,
   t.money_step,
   sum(t.money_step) over (partition by t.id_key order by t.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)as accumulated
from example t
order by t.id_key, t.actual_date
</code>```

I want the "accumulated" column to add up the value of "money_step" for each id_key.
If the attendance_status is the second time '15' for an Id, the counter should add up from the beginning. For ID_KEY = 1 it should look like this:

accumulated:

```<code>Row 1:20
Row 2: 80
Row 3: 100
Row 4: 120
</code>```

How can I do this in the query? Can someone help me?

答:
I understand that you want to reset the sum after the first row where attendance_status has value 15. One option uses a conditional max() to define the subgroup:

```<code>select
    actual_date,
   id_key,
   attendance_status,
   money_step,
   sum(t.money_step) over (
       partition by id_key, grp
       order by actual_date
   ) as accumulated
from (
    select
        e.*,
        max(case when attendance_status = 15 then 1 else 0 end) over(
            partition by id_key
            order by actual_date
            rows between unbounded preceding and 1 preceding
        ) grp
    from example e
) e
order by id_key, actual_date
</code>```

Body:
Below you can see my query, which gives the following result:

select t.actual_date,
   t.id_key,
   t.attendance_status,
   t.money_step,
   sum(t.money_step) over (partition by t.id_key order by t.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)as accumulated
from example t
order by t.id_key, t.actual_date

I want the "accumulated" column to add up the value of "money_step" for each id_key.
If the attendance_status is the second time '15' for an Id, the counter should add up from the beginning. For ID_KEY = 1 it should look like this:

accumulated:

Row 1:20
Row 2: 80
Row 3: 100
Row 4: 120

How can I do this in the query? Can someone help me?

Body:
I understand that you want to reset the sum after the first row where attendance_status has value 15. One option uses a conditional max() to define the subgroup:

select
    actual_date,
   id_key,
   attendance_status,
   money_step,
   sum(t.money_step) over (
       partition by id_key, grp
       order by actual_date
   ) as accumulated
from (
    select
        e.*,
        max(case when attendance_status = 15 then 1 else 0 end) over(
            partition by id_key
            order by actual_date
            rows between unbounded preceding and 1 preceding
        ) grp
    from example e
) e
order by id_key, actual_date


问:
Can LAMBDA function, while doing aggregation, take condition from another column in python?
I am looking for a way, if there exists a one, to perform an aggregatation on a df using only lambda approach, subject to a condition from another column. Here is a small microcosm of the problem.

```<code>df = pd.DataFrame({'ID':[1,1,1,1,2,2],
                   'revenue':[40,55,75,80,35,60],
                   'month':['2012-01-01','2012-02-01','2012-01-01','2012-03-01','2012-02-01','2012-03-01']})
print(df)
   ID       month  revenue
0   1  2012-01-01       40
1   1  2012-02-01       55
2   1  2012-01-01       75
3   1  2012-03-01       80
4   2  2012-02-01       35
5   2  2012-03-01       60
</code>```

If you need to have unique months for every ID, then the following code is good (this code is just for demonstration 'month':'nunique' works here).

```<code>df = df.groupby(['ID']).agg({'month':lambda x:x.nunique()}).reset_index()
print(df)
   ID  month
0   1      3
1   2      2
</code>```

But, I need to count unique months when revenue was greater than 50 by taking two variables (revenue & month) in lambda something like lambda x,y: ... .

I could have done it like df[df['revenue'] > 50].groupby.(....), but there are many other columns in the agg() where this condition is not needed. So, does there exist an approach where lambda could take 2 variables simultaneously??

Expected output:

```<code>   ID  month
0   1      3
1   2      1
</code>```

答:
Unfortunately it is possible not easy/ performance way, because GroupBy.agg processing each column separately:

Dont use it, because extremly slow if large df or many groups.

```<code>def f(x):
   a = df.loc[x.index]
   return a.loc[a['revenue'] > 50, 'month'].nunique()

df1 = df.groupby(['ID']).agg({'month':f}).reset_index()
print(df1)
   ID  month
0   1      3
1   2      1
</code>```

So one possible solution is filter before or using GroupBy.apply.

Body:
I am looking for a way, if there exists a one, to perform an aggregatation on a df using only lambda approach, subject to a condition from another column. Here is a small microcosm of the problem.

df = pd.DataFrame({'ID':[1,1,1,1,2,2],
                   'revenue':[40,55,75,80,35,60],
                   'month':['2012-01-01','2012-02-01','2012-01-01','2012-03-01','2012-02-01','2012-03-01']})
print(df)
   ID       month  revenue
0   1  2012-01-01       40
1   1  2012-02-01       55
2   1  2012-01-01       75
3   1  2012-03-01       80
4   2  2012-02-01       35
5   2  2012-03-01       60

If you need to have unique months for every ID, then the following code is good (this code is just for demonstration 'month':'nunique' works here).

df = df.groupby(['ID']).agg({'month':lambda x:x.nunique()}).reset_index()
print(df)
   ID  month
0   1      3
1   2      2

But, I need to count unique months when revenue was greater than 50 by taking two variables (revenue & month) in lambda something like lambda x,y: ... .

I could have done it like df[df['revenue'] > 50].groupby.(....), but there are many other columns in the agg() where this condition is not needed. So, does there exist an approach where lambda could take 2 variables simultaneously??

Expected output:

   ID  month
0   1      3
1   2      1

Body:
Unfortunately it is possible not easy/ performance way, because GroupBy.agg processing each column separately:

Dont use it, because extremly slow if large df or many groups.

def f(x):
   a = df.loc[x.index]
   return a.loc[a['revenue'] > 50, 'month'].nunique()

df1 = df.groupby(['ID']).agg({'month':f}).reset_index()
print(df1)
   ID  month
0   1      3
1   2      1

So one possible solution is filter before or using GroupBy.apply.


问:
Handling the OnNavigatedFrom / OnNavigatedTo events in the ViewModel
I am trying to figure out a way for my ViewModel to handle saving or restore the page's state when the page is navigated From or To.

The first thing I tried was to add an EventToCommand behavior to the page, but the events (OnNavigatedFrom and OnNavigatedTo) are declared protected and the EventToCommand does not see the events to bind to.

Next I thought I would try using the Messenger class to pass a message to the ViewModel using code in the View's code behind:

```<code>protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    Messenger.Default.Send<PhoneApplicationPage>(this);
    base.OnNavigatedFrom(e);
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    Messenger.Default.Send<PhoneApplicationPage>(this);
    base.OnNavigatedTo(e);
}
</code>```

But this seems to have two issues, first is having this code in the code behind page. Second, the ViewModel cannot tell the difference between the OnNavigatedFrom and the OnNavigatedTo events without having to create a set a wrapper classes for the PhoneApplicationPage object (see UPDATE below).

What is the most MVVM-Light friendly way to handle these events?

UPDATE:
I was able to resolve the second issue by Sending the Messages like this:

```<code>protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    Messenger.Default.Send<PhoneApplicationPage>(this,"NavigatedFrom");
    base.OnNavigatedFrom(e);
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    Messenger.Default.Send<PhoneApplicationPage>(this, "NavigatedTo");
    base.OnNavigatedTo(e);
}
</code>```

and Registering them like this:

```<code>Messenger.Default.Register<PhoneApplicationPage>(this, "NavigatedFrom", false, (action) => SaveState(action));
Messenger.Default.Register<PhoneApplicationPage>(this, "NavigatedTo", false, (action) => RestoreState(action));
</code>```

答:
Executing a command from code behind is far cleaner than going through the whole messaging mess. After all there's nothing wrong with the view knowing about its DataContext.

```<code>    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        viewModel.NavigatedToCommand.Execute(e.Uri);
    }

    ProfileViewModel viewModel
    {
        get
        {
            return this.DataContext as ProfileViewModel;
        }
    }
</code>```

Update: Passing in NavigationContext.QueryString is probably more useful, since it already parses out the parameters and value.

Body:
I am trying to figure out a way for my ViewModel to handle saving or restore the page's state when the page is navigated From or To.

The first thing I tried was to add an EventToCommand behavior to the page, but the events (OnNavigatedFrom and OnNavigatedTo) are declared protected and the EventToCommand does not see the events to bind to.

Next I thought I would try using the Messenger class to pass a message to the ViewModel using code in the View's code behind:

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    Messenger.Default.Send<PhoneApplicationPage>(this);
    base.OnNavigatedFrom(e);
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    Messenger.Default.Send<PhoneApplicationPage>(this);
    base.OnNavigatedTo(e);
}

But this seems to have two issues, first is having this code in the code behind page. Second, the ViewModel cannot tell the difference between the OnNavigatedFrom and the OnNavigatedTo events without having to create a set a wrapper classes for the PhoneApplicationPage object (see UPDATE below).

What is the most MVVM-Light friendly way to handle these events?

UPDATE:
I was able to resolve the second issue by Sending the Messages like this:

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    Messenger.Default.Send<PhoneApplicationPage>(this,"NavigatedFrom");
    base.OnNavigatedFrom(e);
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    Messenger.Default.Send<PhoneApplicationPage>(this, "NavigatedTo");
    base.OnNavigatedTo(e);
}

and Registering them like this:

Messenger.Default.Register<PhoneApplicationPage>(this, "NavigatedFrom", false, (action) => SaveState(action));
Messenger.Default.Register<PhoneApplicationPage>(this, "NavigatedTo", false, (action) => RestoreState(action));

Body:
Executing a command from code behind is far cleaner than going through the whole messaging mess. After all there's nothing wrong with the view knowing about its DataContext.

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        viewModel.NavigatedToCommand.Execute(e.Uri);
    }

    ProfileViewModel viewModel
    {
        get
        {
            return this.DataContext as ProfileViewModel;
        }
    }

Update: Passing in NavigationContext.QueryString is probably more useful, since it already parses out the parameters and value.


问:
The `fields` option must be a list or tuple or "__all__". Got str
I am trying to create comment for my article model but i am having issue in the serializer part where it says

```<code>The `fields` option must be a list or tuple or "__all__". Got str.
</code>```

I already included the parts that are needed,but i don't know where the problem is coming from.

Models.py

```<code>class Comment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name='author1')
    article = models.OneToOneField(Article, on_delete=models.CASCADE, related_name='author2')
    content = models.CharField(max_length=100)
</code>```

Serializers.py

```<code>
class CommentCreateSerializer(serializers.ModelSerializer):
    content = serializers.CharField(required=False)

    class Meta:
        model = Comment
        fields = ('content')

    def create(self, validated_data):
     return Comment.objects.create(**validated_data)

</code>```

Does anybody know why?

答:
It should be

```<code>fields = ('content',)</code>```

This is because, ('content') is a string with unnecessary brackets, where as ('content',) is a tuple

Alternatively, you can try this too...

```<code>fields = ['content']
</code>```

Body:
I am trying to create comment for my article model but i am having issue in the serializer part where it says

The `fields` option must be a list or tuple or "__all__". Got str.

I already included the parts that are needed,but i don't know where the problem is coming from.

Models.py

class Comment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name='author1')
    article = models.OneToOneField(Article, on_delete=models.CASCADE, related_name='author2')
    content = models.CharField(max_length=100)

Serializers.py

class CommentCreateSerializer(serializers.ModelSerializer):
    content = serializers.CharField(required=False)

    class Meta:
        model = Comment
        fields = ('content')

    def create(self, validated_data):
     return Comment.objects.create(**validated_data)

Does anybody know why?

Body:
It should be

fields = ('content',)

This is because, ('content') is a string with unnecessary brackets, where as ('content',) is a tuple

Alternatively, you can try this too...

fields = ['content']


问:
Status Bar Style issues since Xcode 11.4
Since Xcode 11.4 overriding the preferredStatusBarStyle property does not seem to work anymore in some cases.

We have an extension of UINavigationController where we override it for basically every ViewController but this property is no longer called since Xcode 11.4. Therefore the status bar is black for mostly all ViewControllers.

```<code>extension UINavigationController {

    override open var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

}
</code>```

It also stopped working for some ViewControllers where we override preferredStatusBarStyle again. The property gets accessed, however, the status bar does not change its color.

View controller-based status bar appearance is set to YES in info.plist.

Issue occurs on simulator and real devices.

Does anyone have this problem too?

答:
Ok I found a solution. Looks like I need to set the barStyle of the navigationBar to .black as described here

```<code>navigationController?.navigationBar.barStyle = .black
</code>```

Not sure though why this is necessary now.

The UINavigationController extension is no longer needed then.

Body:
Since Xcode 11.4 overriding the preferredStatusBarStyle property does not seem to work anymore in some cases.

We have an extension of UINavigationController where we override it for basically every ViewController but this property is no longer called since Xcode 11.4. Therefore the status bar is black for mostly all ViewControllers.

extension UINavigationController {

    override open var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

}

It also stopped working for some ViewControllers where we override preferredStatusBarStyle again. The property gets accessed, however, the status bar does not change its color.

View controller-based status bar appearance is set to YES in info.plist.

Issue occurs on simulator and real devices.

Does anyone have this problem too?

Body:
Ok I found a solution. Looks like I need to set the barStyle of the navigationBar to .black as described here

navigationController?.navigationBar.barStyle = .black

Not sure though why this is necessary now.

The UINavigationController extension is no longer needed then.


问:
jrebel standalone could not find agent library in macos
i'm running gradle task at project root directory but it erros, looks as below:

$> ./gradlew bootRun

Error occurred during initialization of VM Could not find agent
  library /Users/xxx/bin/jrebel/libjrebel64.dylib in absolute path, with
  error: dlopen(/Users/xxx/bin/jrebel/libjrebel64.dylib, 1): image not
  found

it setup jrebel follow https://manuals.jrebel.com/jrebel/standalone/springboot.html#spring-boot-using-gradle

And, i checked agentpath and is right.

Anyone had same problem?

答: Isn't there a blank space in your username? I would try to redownload the JRebel again, unzip it into some other folder and then try again.</p>


问:
Given a periphery of island mark its interior in matrix (Algorithm)
We are given a matrix of size N which is completely filled with 0's and we are also given a list of coordinates which contains the coordinates of the periphery of an island. Now we have to mark the island (periphery + area that is part of the island) as 1's.

I am having trouble coming up with a solution to this problem, I thought of bfs/dfs but can't think of a way to implement this.
(Please assume that there is 1 island only and the input is correct i.e. all input coordinates form a closed shape and are valid

```<code>N = 5
coordinates =
0,2
1,1
1,3
2,0
2,4
3,1
3,3
4,2
</code>```

So this is what output should look like ---

```<code>    0 1 2 3 4
  0 0 0 1 0 0
  1 0 1 1 1 0
  2 1 1 1 1 1
  3 0 1 1 1 0
  4 0 0 1 0 0
</code>```

All the coordinates marked and the square boxes inside them marked which are a part of the island.

答:
Seems that peripheral coordinates are just ends of filled horizontal lines.

In this case use for-loop to set elements inside lines to 1. Pseudocode:

```<code>lastrow = -1
lastcol = -1
for every line:
   extract row, col
   if row = lastrow:
       for (i=lastcol + 1; i<=col; i++):   //fill line
          A[row][i] = 1
       lastrow = -1    // to treat possible space in the line
   else:
       A[row][col] = 1     //set the only cell
   lastrow = row
   lastcol = col
</code>```

Body:
We are given a matrix of size N which is completely filled with 0's and we are also given a list of coordinates which contains the coordinates of the periphery of an island. Now we have to mark the island (periphery + area that is part of the island) as 1's.

I am having trouble coming up with a solution to this problem, I thought of bfs/dfs but can't think of a way to implement this.
(Please assume that there is 1 island only and the input is correct i.e. all input coordinates form a closed shape and are valid

N = 5
coordinates =
0,2
1,1
1,3
2,0
2,4
3,1
3,3
4,2

So this is what output should look like ---

    0 1 2 3 4
  0 0 0 1 0 0
  1 0 1 1 1 0
  2 1 1 1 1 1
  3 0 1 1 1 0
  4 0 0 1 0 0

All the coordinates marked and the square boxes inside them marked which are a part of the island.

Body:
Seems that peripheral coordinates are just ends of filled horizontal lines.

In this case use for-loop to set elements inside lines to 1. Pseudocode:

lastrow = -1
lastcol = -1
for every line:
   extract row, col
   if row = lastrow:
       for (i=lastcol + 1; i<=col; i++):   //fill line
          A[row][i] = 1
       lastrow = -1    // to treat possible space in the line
   else:
       A[row][col] = 1     //set the only cell
   lastrow = row
   lastcol = col


问:
Firestore rule to check the value of a dynamic field within a map
Think of a poll app, which has a map in a Firestore document.
This map has the vote key as string and a number as value (counter).
For instance “what is the best food”:

```<code>{
...
...
poll : [
    pizza : 10,
    barbecue: 3,
    pasta: 1,
    ...
     ]
...
}
</code>```

The items can vary depending on the poll. Only one vote per user. Only logged in users can vote (Firestore rule).
The minimum amount is zero, people can switch from one to another (decrease moment).
Also, the increase should be only +1.

Transactions protect the app to avoid less than 0 for any item and +1 is controlled there.
Is there a way to protect also with the Firestore rules?
To be honest, I’m not sure if it’s necessary.

I can get the affected items with map diff functions. But how do I check for that specific changed item value?
The map diff result brings a set, however I cannot use the keys retrieved by the set in the request.resource.data, otherwise the problem would be solved.
I could check whether it’s 0 and also check with current data if the difference is 1.

The key will be in the map for sure, since it comes from the diff function from the map itself.

答:
Update Feb 2021: this doesn't work for the latest firebase since the keys are  a set which can't be indexed

You can get the affected keys using

```<code>let affectedKeys = request.resource.data.poll.diff(resource.data.poll).affectedKeys();
</code>```

However according to the firebase docs on MapDiff it's not possible to get the changes in values, only in keys.

If you know how many poll items there are, you can do something like

```<code>let differenceOfOne = request.resource.data.poll[affectedKeys[0]] == resource.data.poll[affectedKeys[0]] + 1 || request.resource.data.poll[affectedKeys[0]] == resource.data.poll[affectedKeys[0]] - 1
</code>```

and repeat that line for every index up to the maximum number of items (loops are not allowed in firebase rules).

Body:
Think of a poll app, which has a map in a Firestore document.
This map has the vote key as string and a number as value (counter).
For instance “what is the best food”:

{
...
...
poll : [
    pizza : 10,
    barbecue: 3,
    pasta: 1,
    ...
     ]
...
}

The items can vary depending on the poll. Only one vote per user. Only logged in users can vote (Firestore rule).
The minimum amount is zero, people can switch from one to another (decrease moment).
Also, the increase should be only +1.

Transactions protect the app to avoid less than 0 for any item and +1 is controlled there.
Is there a way to protect also with the Firestore rules?
To be honest, I’m not sure if it’s necessary.

I can get the affected items with map diff functions. But how do I check for that specific changed item value?
The map diff result brings a set, however I cannot use the keys retrieved by the set in the request.resource.data, otherwise the problem would be solved.
I could check whether it’s 0 and also check with current data if the difference is 1.

The key will be in the map for sure, since it comes from the diff function from the map itself.

Body:
Update Feb 2021: this doesn't work for the latest firebase since the keys are  a set which can't be indexed

You can get the affected keys using

let affectedKeys = request.resource.data.poll.diff(resource.data.poll).affectedKeys();

However according to the firebase docs on MapDiff it's not possible to get the changes in values, only in keys.

If you know how many poll items there are, you can do something like

let differenceOfOne = request.resource.data.poll[affectedKeys[0]] == resource.data.poll[affectedKeys[0]] + 1 || request.resource.data.poll[affectedKeys[0]] == resource.data.poll[affectedKeys[0]] - 1

and repeat that line for every index up to the maximum number of items (loops are not allowed in firebase rules).


问:
Remove unused code Google Page Speed and others errors
Google Page Speed report me here an error that I can't understand.

Remove unused code
I use all the javascript that Google Page Speed says, in fact vendor.js is the main script of the project. Compiled and unified with Webpack and Laravel.

Then why does Google Page Speed say I don't use these scripts?
Before I uploaded the lazysizes plugin I didn't get any of this.

On the other hand, the website loads quickly. I think Google Page Speed is very unreliable.

答:
Remove Unused Code is explained here

It isn't that the entire script isn't used, it is that large portions of the script are not used for initial page render.

Google is encouraging you to split your JavaScript into essential code to render the page / initialise components and then put everything else in separate files that are loaded later.

It is also encouraging you to purge any redundant JavaScript from those files.

This is to save Kb being downloaded, as well as to save on JavaScript parsing and compilation time by the V8 engine (important for slower processors in low-end mobile phones).

To check this yourself open developer tools in Google Chrome and open the 'coverage' window. Press record and see how much of each script is not used. On your site around 60% of the JS downloaded is not used initially, you should push the 40% you use down the wire first and load the rest after everything else has loaded. (this is extremely difficult unless you build for it in the first place, do the best you can!).

As for your site being fast - it loads fully in 7 seconds for me on my PC with a leased line (so about as fast as you can get, albeit I am in the UK so that may add a second overall)

On a simulated 4G connection with a 4x CPU slowdown (to simulate a mobile phone with limited processing power that is not connected to WiFi) your site takes nearly 18 seconds to complete loading with a total page weight of 2.5Mb (zipped - its 5.5Mb unzipped).

This is the test that PSI performs on the 'Mobile' tab (4x slowdown and 4G simulation)

Page weight is one of your biggest problems along with the volume of JavaScript the site uses, those are the areas to focus on. Also try to reduce the number of requests if possible, you have 149 different network requests and only a maximum of 8 at a time can be downloaded simultaneously.

While PSI is only a tool it does produce fairly accurate results, the "Field Data" at the top is real world data from browsers so I would pay particular attention to that, in particular "First Contentful Paint (FCP)" where 40% of your users are experience an average or slow time.


问:
How to refresh the content of a grid continiously from the code behind file
I try to refresh the content of my grid continiously with a parallel thread. Thats the code which is not working:

```<code>private void ContiniouslyRefreshPage(int interval)
        {
            var startTimeSpan = TimeSpan.Zero;
            var periodTimeSpan = TimeSpan.FromSeconds(interval);
            Dictionary<string, string> lastCheck = bluetoothService.CheckRequirements();
            var timer = new System.Threading.Timer((e) =>
            {
                Dictionary<string, string> newCheck = bluetoothService.CheckRequirements();
                if (!(lastCheck.Count == newCheck.Count && !bluetoothService.CheckRequirements().Except(lastCheck).Any()))
                {
                    Application.Current.MainPage = new MasterDetail
                    {
                        Detail = new NavigationPage(new TestingPage())
                        {
                            BarBackgroundColor = Color.White,
                            BarTextColor = Color.Black
                        }
                    };
                    lastCheck = newCheck;
                }
            }, null, startTimeSpan, periodTimeSpan);
        }
</code>```

The if-clause works, so the page should only refesh when there is a change of my dataset (dataset is returned by CheckRequirements-Method)

The code is not working: It gets into the if-clause when there is a change but it doesn't initialize and display the new Page.

I think this is not the best practise at all, i'd like to have an advice how to do it better.

答:
The updating UI opeation should be executed in the main thread. Try to put the related function code in the main thread. Such as: </p>

```<code>private void ContiniouslyRefreshPage(int interval)
{
    ...
    MainThread.BeginInvokeOnMainThread(() =>
    {
        Application.Current.MainPage = new MasterDetail
        {
            Detail = new NavigationPage(new TestingPage())
            {
                BarBackgroundColor = Color.White,
                BarTextColor = Color.Black
            }
        };
    };
}
</code>```

Body:
I try to refresh the content of my grid continiously with a parallel thread. Thats the code which is not working:

private void ContiniouslyRefreshPage(int interval)
        {
            var startTimeSpan = TimeSpan.Zero;
            var periodTimeSpan = TimeSpan.FromSeconds(interval);
            Dictionary<string, string> lastCheck = bluetoothService.CheckRequirements();
            var timer = new System.Threading.Timer((e) =>
            {
                Dictionary<string, string> newCheck = bluetoothService.CheckRequirements();
                if (!(lastCheck.Count == newCheck.Count && !bluetoothService.CheckRequirements().Except(lastCheck).Any()))
                {
                    Application.Current.MainPage = new MasterDetail
                    {
                        Detail = new NavigationPage(new TestingPage())
                        {
                            BarBackgroundColor = Color.White,
                            BarTextColor = Color.Black
                        }
                    };
                    lastCheck = newCheck;
                }
            }, null, startTimeSpan, periodTimeSpan);
        }

The if-clause works, so the page should only refesh when there is a change of my dataset (dataset is returned by CheckRequirements-Method)

The code is not working: It gets into the if-clause when there is a change but it doesn't initialize and display the new Page.

I think this is not the best practise at all, i'd like to have an advice how to do it better.

Body:
The updating UI opeation should be executed in the main thread. Try to put the related function code in the main thread. Such as:

private void ContiniouslyRefreshPage(int interval)
{
    ...
    MainThread.BeginInvokeOnMainThread(() =>
    {
        Application.Current.MainPage = new MasterDetail
        {
            Detail = new NavigationPage(new TestingPage())
            {
                BarBackgroundColor = Color.White,
                BarTextColor = Color.Black
            }
        };
    };
}


问:
Is it possible to create a function where [[prototype]] refers to another function
I would like to create function objects (yes, all functions are objects) with some control over the prototypal inheritance, that is, I would like one function to inherit from another.

I can make objects that have prototypal inheritance, and know to set the prototype property of a function performing as a constructor to initialize the [[prototype]] property of the object.

However, when creating a function, I must use the function operator or the Function constructor. I could try to swizzle Function.prototype, but (1) don't know if that is writable, and (2) that just seems quite dangerous [still, I should try doing that].

btw: I only care to do this for V8 within node.JS, so if there are means that work only for that environment, that would be acceptable.

For the record, I have seen this:
Is it possible to create a function with another prototype than Function.prototype?

答:
In V8 (and most other browsers/engines except IE) you can change an object's prototype by setting the __prototype__ __proto__ attribute. Setting the prototype attribute will instead change the prototype that is used to create an object if the function is invoked as a constructor function. This should not be what you want.

Afaik there currently is no standard conform way to directly "subclass" a function (or array for that matter). There's only Object.create, but there is no Function.create or Array.create.

EDIT: I just realized that function objects do not have the __prototype__ attribute and changing / setting it will not turn an object into a function.
I believe though that I just recently watched a talk by Brendan Eich (the creator of JavaScript) in which he talked about Function and Array equivalents of Object.create. And infact, googling for "Function.create brendan eich" reveals the following blog post by Eich in which he talks about his wish to implement Function.create and Array.create.

EDIT 2: Ok, I screwed up. Pretty much. The non-standard attribute is of course __proto__ and not __prototype__. Setting __proto__ works fine for functions with some restrictions, which are:

To be able to call aFunction you must initialize it with an actual function, eg:

```<code>var aFunction = function () {};
</code>```

This is important. Calling a function does not access the prototype chain, so if you define aFunction as an object and simply set the  __proto__ attribute, you will not able to call aFunction.

You can now assign any other function to aFunction.__proto__ and reading any members (including methods) will correctly delegate to the prototype chain if the porperty is not found on aFunction itself.

Calling aFunction() will always invoke the function that was originally declared when aFunction was defined and will never invoke aFunction's prototype function. So the body of the function is not subject to inheritence.

Sorry for screwing up first with the name of the attribute. Hope this helps you nevertheless.

Body:
In V8 (and most other browsers/engines except IE) you can change an object's prototype by setting the __prototype__ __proto__ attribute. Setting the prototype attribute will instead change the prototype that is used to create an object if the function is invoked as a constructor function. This should not be what you want.

Afaik there currently is no standard conform way to directly "subclass" a function (or array for that matter). There's only Object.create, but there is no Function.create or Array.create.

EDIT: I just realized that function objects do not have the __prototype__ attribute and changing / setting it will not turn an object into a function.
I believe though that I just recently watched a talk by Brendan Eich (the creator of JavaScript) in which he talked about Function and Array equivalents of Object.create. And infact, googling for "Function.create brendan eich" reveals the following blog post by Eich in which he talks about his wish to implement Function.create and Array.create.

EDIT 2: Ok, I screwed up. Pretty much. The non-standard attribute is of course __proto__ and not __prototype__. Setting __proto__ works fine for functions with some restrictions, which are:

To be able to call aFunction you must initialize it with an actual function, eg:

var aFunction = function () {};

This is important. Calling a function does not access the prototype chain, so if you define aFunction as an object and simply set the  __proto__ attribute, you will not able to call aFunction.

You can now assign any other function to aFunction.__proto__ and reading any members (including methods) will correctly delegate to the prototype chain if the porperty is not found on aFunction itself.

Calling aFunction() will always invoke the function that was originally declared when aFunction was defined and will never invoke aFunction's prototype function. So the body of the function is not subject to inheritence.

Sorry for screwing up first with the name of the attribute. Hope this helps you nevertheless.


问:
Jenkins freezes on sh commands after changing agents
I've added new logic to my Jenkinsfile that in a specific stage I change agents and run commands such as sh.

Problem:

I wanted to change agents and run commands there. However, it seems like a race condition where if the pipeline's agent runs a docker (in the pipeline declarative block), and in one of the stages you change agent, the agent doesn't run shell commands, it just hangs and stays stuck.

Please notice that I want my docker and label to be on the pipeline declaration block and not in specific stages (using agent none), since I want all stages but the last stage to run in this specific agent and specific docker.

Is there a bug in this script? I made a miniature script that reproduces this "bug", you can run this on your own jenkins to try it out for yourself (add docker-credentials to passwords in jenkins), it seems like a bug with jenkins:

```<code>#!/usr/bin/env groovy

pipeline
{
    agent
    {
        docker
        {
            alwaysPull true
            image 'ubuntu:xenial'
            registryCredentialsId 'docker-credentials'
            registryUrl 'https://index.docker.io/v1/'
            label 'master'
          }
    }

    stages
    {
        stage("Initialize")
        {
            steps
            {
                script
                {
                    println("Initializing")
                }
            }
        }

        stage("First agent stage")
        {
            steps
            {
                script
                {
                    sh(script: "ls", label: "Working shell scripts")
                }
            }
        }

        stage("Second agent stage")
        {
            agent
            {
                label 'master'
            }
            steps
            {
                script
                {
                    sh(script: "ls", label: "Hung shell scripts")
                }
            }
        }
    }
}
</code>```

Notice if you change from this:

```<code>agent
{
    docker
    {
        alwaysPull true
        image 'ubuntu:xenial'
        registryCredentialsId 'docker-credentials'
        registryUrl 'https://index.docker.io/v1/'
        label 'master'
      }
}
</code>```

to this:

```<code>agent
{
    label 'master'
}
</code>```

It starts working again...

答: It seems like this issue had to do with something on my own jenkins server. Once I reinstalled the jenkins server it worked just fine.</p>

Body:
I've added new logic to my Jenkinsfile that in a specific stage I change agents and run commands such as sh.

Problem:

I wanted to change agents and run commands there. However, it seems like a race condition where if the pipeline's agent runs a docker (in the pipeline declarative block), and in one of the stages you change agent, the agent doesn't run shell commands, it just hangs and stays stuck.

Please notice that I want my docker and label to be on the pipeline declaration block and not in specific stages (using agent none), since I want all stages but the last stage to run in this specific agent and specific docker.

Is there a bug in this script? I made a miniature script that reproduces this "bug", you can run this on your own jenkins to try it out for yourself (add docker-credentials to passwords in jenkins), it seems like a bug with jenkins:

#!/usr/bin/env groovy

pipeline
{
    agent
    {
        docker
        {
            alwaysPull true
            image 'ubuntu:xenial'
            registryCredentialsId 'docker-credentials'
            registryUrl 'https://index.docker.io/v1/'
            label 'master'
          }
    }

    stages
    {
        stage("Initialize")
        {
            steps
            {
                script
                {
                    println("Initializing")
                }
            }
        }

        stage("First agent stage")
        {
            steps
            {
                script
                {
                    sh(script: "ls", label: "Working shell scripts")
                }
            }
        }

        stage("Second agent stage")
        {
            agent
            {
                label 'master'
            }
            steps
            {
                script
                {
                    sh(script: "ls", label: "Hung shell scripts")
                }
            }
        }
    }
}

Notice if you change from this:

agent
{
    docker
    {
        alwaysPull true
        image 'ubuntu:xenial'
        registryCredentialsId 'docker-credentials'
        registryUrl 'https://index.docker.io/v1/'
        label 'master'
      }
}

to this:

agent
{
    label 'master'
}

It starts working again...


问:
How use a print statement from a defined function in Python
How can I call this defined function with customized text before each animation, so i can just print it like print(Anim("text"))?

```<code>import time
import sys

animation = "|/-\\"

def Anim(text):
    for i in range(20):
        time.sleep(0.1)
        sys.stdout.write("\r" + animation[i % len(animation)])
        sys.stdout.flush()
</code>```

答:
Is this what you want?</p>

```<code>import time

animation = "|/-\\"

def Anim(text):
    for i in range(20):
        time.sleep(0.1)
        yield "\r" + animation[i % len(animation)]

for frame in Anim(animation):
    print(frame, flush=True, end="")
</code>```

Body:
How can I call this defined function with customized text before each animation, so i can just print it like print(Anim("text"))?

import time
import sys

animation = "|/-\\"

def Anim(text):
    for i in range(20):
        time.sleep(0.1)
        sys.stdout.write("\r" + animation[i % len(animation)])
        sys.stdout.flush()

Body:
Is this what you want?

import time

animation = "|/-\\"

def Anim(text):
    for i in range(20):
        time.sleep(0.1)
        yield "\r" + animation[i % len(animation)]

for frame in Anim(animation):
    print(frame, flush=True, end="")


问:
Show edge id on click
What I´m trying to achieve here with cytoscape.js library that when I click on an edge then the id of that edge will be shown instead of hovering.

for example the ab id should be displayed only when I click on the edge. I don´t want to display id´s of nodes when I click.

Thanks for help in advance.

is there any documentation with more examples than cytoscape.js ?

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),
    style: [{
        selector: "node",
        style: {
          content: "data(id)"
        }
      },
      {
        selector: "edge",
        style: {
          "curve-style": "bezier",
          "target-arrow-shape": "triangle"
        }
      }
    ],
    elements: {
      nodes: [{
        data: {
          id: "a"
        }
      }, {
        data: {
          id: "b"
        }
      }],
      edges: [{
        data: {
          id: "ab",
          source: "a",
          target: "b"
        }
      }]
    },
    layout: {
      name: "grid"
    }
  }));

  function makePopper(ele) {
    let ref = ele.popperRef(); // used only for positioning

    ele.tippy = tippy(ref, { // tippy options:
      content: () => {
        let content = document.createElement('div');

        content.innerHTML = ele.id();

        return content;
      },
      trigger: 'manual' // probably want manual mode
    });
  }

  cy.ready(function() {
    cy.elements().forEach(function(ele) {
      makePopper(ele);
    });
  });

  cy.elements().unbind('mouseover');
  cy.elements().bind('mouseover', (event) => event.target.tippy.show());

  cy.elements().unbind('mouseout');
  cy.elements().bind('mouseout', (event) => event.target.tippy.hide());

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}

h1 {
  opacity: 0.5;
  font-size: 1em;
  font-weight: bold;
}</code>```

  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">

  <link rel="stylesheet" href="https://unpkg.com/tippy.js@4.0.1/index.css" />

```

答:
This is basic cytoscape.js functionality. You are using these two lines as your event trigger:

```<code>cy.elements().unbind('mouseover');
cy.elements().bind('mouseover', (event) => event.target.tippy.show());

cy.elements().unbind('mouseout');
cy.elements().bind('mouseout', (event) => event.target.tippy.hide());
</code>```

If you take a look at the code, you notice two things:

You are calling the .bind() function on cy.elements(), thus calling the bind on every element in the cytoscape.js graph

You are using the mouse-over and mouse-out event to trigger the popper tooltip

The simple fix would be this:

```<code>cy.nodes().unbind('mouseover');
cy.nodes().bind('mouseover', (event) => event.target.tippy.show());

cy.nodes().unbind('mouseout');
cy.nodes().bind('mouseout', (event) => event.target.tippy.hide());

cy.edges().unbind('mousedown');
cy.edges().bind('mousedown ', (event) => event.target.tippy.show());

cy.edges().unbind('mouseup');
cy.edges().bind('mouseup', (event) => event.target.tippy.hide());
</code>```

In your code, this would look like this:

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),
    style: [{
        selector: "node",
        style: {
          content: "data(id)"
        }
      },
      {
        selector: "edge",
        style: {
          "curve-style": "bezier",
          "target-arrow-shape": "triangle"
        }
      }
    ],
    elements: {
      nodes: [{
        data: {
          id: "a"
        }
      }, {
        data: {
          id: "b"
        }
      }],
      edges: [{
        data: {
          id: "ab",
          source: "a",
          target: "b"
        }
      }]
    },
    layout: {
      name: "grid"
    }
  }));

  function makePopper(ele) {
    let ref = ele.popperRef(); // used only for positioning

    ele.tippy = tippy(ref, { // tippy options:
      content: () => {
        let content = document.createElement('div');

        content.innerHTML = ele.id();

        return content;
      },
      trigger: 'manual' // probably want manual mode
    });
  }

  cy.ready(function() {
    cy.elements().forEach(function(ele) {
      makePopper(ele);
    });
  });

  cy.nodes().unbind('mouseover');
  cy.nodes().bind('mouseover', (event) => event.target.tippy.show());

  cy.nodes().unbind('mouseout');
  cy.nodes().bind('mouseout', (event) => event.target.tippy.hide());

  cy.edges().unbind('mousedown');
  cy.edges().bind('mousedown', (event) => event.target.tippy.show());

  cy.edges().unbind('mouseup');
  cy.edges().bind('mouseup', (event) => event.target.tippy.hide());

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}

h1 {
  opacity: 0.5;
  font-size: 1em;
  font-weight: bold;
}</code>```

  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">

  <link rel="stylesheet" href="https://unpkg.com/tippy.js@4.0.1/index.css" />

```

Title: Show edge id on click

Body:
What I´m trying to achieve here with cytoscape.js library that when I click on an edge then the id of that edge will be shown instead of hovering.

for example the ab id should be displayed only when I click on the edge. I don´t want to display id´s of nodes when I click.

Thanks for help in advance.

is there any documentation with more examples than cytoscape.js ?

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),
    style: [{
        selector: "node",
        style: {
          content: "data(id)"
        }
      },
      {
        selector: "edge",
        style: {
          "curve-style": "bezier",
          "target-arrow-shape": "triangle"
        }
      }
    ],
    elements: {
      nodes: [{
        data: {
          id: "a"
        }
      }, {
        data: {
          id: "b"
        }
      }],
      edges: [{
        data: {
          id: "ab",
          source: "a",
          target: "b"
        }
      }]
    },
    layout: {
      name: "grid"
    }
  }));

  function makePopper(ele) {
    let ref = ele.popperRef(); // used only for positioning

    ele.tippy = tippy(ref, { // tippy options:
      content: () => {
        let content = document.createElement('div');

        content.innerHTML = ele.id();

        return content;
      },
      trigger: 'manual' // probably want manual mode
    });
  }

  cy.ready(function() {
    cy.elements().forEach(function(ele) {
      makePopper(ele);
    });
  });

  cy.elements().unbind('mouseover');
  cy.elements().bind('mouseover', (event) => event.target.tippy.show());

  cy.elements().unbind('mouseout');
  cy.elements().bind('mouseout', (event) => event.target.tippy.hide());

});

body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}

h1 {
  opacity: 0.5;
  font-size: 1em;
  font-weight: bold;
}

  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">

  <link rel="stylesheet" href="https://unpkg.com/tippy.js@4.0.1/index.css" />

Body:
This is basic cytoscape.js functionality. You are using these two lines as your event trigger:

cy.elements().unbind('mouseover');
cy.elements().bind('mouseover', (event) => event.target.tippy.show());

cy.elements().unbind('mouseout');
cy.elements().bind('mouseout', (event) => event.target.tippy.hide());

If you take a look at the code, you notice two things:

You are calling the .bind() function on cy.elements(), thus calling the bind on every element in the cytoscape.js graph

You are using the mouse-over and mouse-out event to trigger the popper tooltip

The simple fix would be this:

cy.nodes().unbind('mouseover');
cy.nodes().bind('mouseover', (event) => event.target.tippy.show());

cy.nodes().unbind('mouseout');
cy.nodes().bind('mouseout', (event) => event.target.tippy.hide());

cy.edges().unbind('mousedown');
cy.edges().bind('mousedown ', (event) => event.target.tippy.show());

cy.edges().unbind('mouseup');
cy.edges().bind('mouseup', (event) => event.target.tippy.hide());

In your code, this would look like this:

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),
    style: [{
        selector: "node",
        style: {
          content: "data(id)"
        }
      },
      {
        selector: "edge",
        style: {
          "curve-style": "bezier",
          "target-arrow-shape": "triangle"
        }
      }
    ],
    elements: {
      nodes: [{
        data: {
          id: "a"
        }
      }, {
        data: {
          id: "b"
        }
      }],
      edges: [{
        data: {
          id: "ab",
          source: "a",
          target: "b"
        }
      }]
    },
    layout: {
      name: "grid"
    }
  }));

  function makePopper(ele) {
    let ref = ele.popperRef(); // used only for positioning

    ele.tippy = tippy(ref, { // tippy options:
      content: () => {
        let content = document.createElement('div');

        content.innerHTML = ele.id();

        return content;
      },
      trigger: 'manual' // probably want manual mode
    });
  }

  cy.ready(function() {
    cy.elements().forEach(function(ele) {
      makePopper(ele);
    });
  });

  cy.nodes().unbind('mouseover');
  cy.nodes().bind('mouseover', (event) => event.target.tippy.show());

  cy.nodes().unbind('mouseout');
  cy.nodes().bind('mouseout', (event) => event.target.tippy.hide());

  cy.edges().unbind('mousedown');
  cy.edges().bind('mousedown', (event) => event.target.tippy.show());

  cy.edges().unbind('mouseup');
  cy.edges().bind('mouseup', (event) => event.target.tippy.hide());

});

body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}

h1 {
  opacity: 0.5;
  font-size: 1em;
  font-weight: bold;
}

<head>
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
  <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
  <script src="https://unpkg.com/popper.js@1.14.7/dist/umd/popper.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/cytoscape-popper@1.0.4/cytoscape-popper.min.js"></script>
  <script src="https://unpkg.com/tippy.js@4.0.1/umd/index.all.min.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/tippy.js@4.0.1/index.css" />
</head>

<body>
  <div id="cy"></div>
</body>


问:
Compare String with each element of a String Array using Streams
Hi i want to count how many time a String is found in a Array of Strings using Streams

What i have thought so far is this:

```<code>Stream<String> stream=Arrays.stream(array);

int counter= (int) stream.filter(c-> c.contains("something")).count();

return counter;
</code>```

The problem that i get is that most of the time i get an error of NullPointerException and i think is because of .count() if it doesn't get any much inside filter(c-> c.contains("something")).
And i came to this conclusion cause if i run it with out .count() like that stream.filter(c-> c.contains("something")); without returning nothing, it won't throw an Exception. I'm not sure about it but that's what i think.

Any ideas on how i can count the times a String appears in and Array of Strings using Streams?

答:
The problem that i get is that most of the time i get an error of
  NullPointerException and i think is because of .count()  And i came to
  this conclusion cause if i run it with out .count()
  it won't throw an Exception.

The reason being you cannot replicate the NullPointerException without calling count is because streams are lazy evaluated i.e. the entire pipeline is not executed until an eager operation (an operation which triggers the processing of the pipeline) is invoked.

We can come to the conclusion that Arrays.stream(array) is not the culprit for the NullPointerException because it would have blown up regardless of wether you called an eager operation on the stream or not as the parameter to Arrays.stream should be nonNull or else it would bomb out with the aforementioned error.

Thus we can come to the conclusion that the elements inside the array are the culprits for this error in the code you've illustrated but then you should ask your self are null elements allowed in the first place and if so then filter them out before performing c.contains("something") and if not then you should debug at which point in your application were nulls added to the array when they should not be. find the bug rather than suppress it.

if null's are allowed in the first place then the solution is simple i.e. filter the nulls out before calling .contains:

```<code>int counter = (int)stream.filter(Objects::nonNull)
                         .filter(c -> c.contains("something")) // or single filter with c -> c != null && c.contains("something") as pred
                         .count();
</code>```

Body:
Hi i want to count how many time a String is found in a Array of Strings using Streams

What i have thought so far is this:

Stream<String> stream=Arrays.stream(array);

int counter= (int) stream.filter(c-> c.contains("something")).count();

return counter;

The problem that i get is that most of the time i get an error of NullPointerException and i think is because of .count() if it doesn't get any much inside filter(c-> c.contains("something")).
And i came to this conclusion cause if i run it with out .count() like that stream.filter(c-> c.contains("something")); without returning nothing, it won't throw an Exception. I'm not sure about it but that's what i think.

Any ideas on how i can count the times a String appears in and Array of Strings using Streams?

Body:
The problem that i get is that most of the time i get an error of
  NullPointerException and i think is because of .count()  And i came to
  this conclusion cause if i run it with out .count()
  it won't throw an Exception.

The reason being you cannot replicate the NullPointerException without calling count is because streams are lazy evaluated i.e. the entire pipeline is not executed until an eager operation (an operation which triggers the processing of the pipeline) is invoked.

We can come to the conclusion that Arrays.stream(array) is not the culprit for the NullPointerException because it would have blown up regardless of wether you called an eager operation on the stream or not as the parameter to Arrays.stream should be nonNull or else it would bomb out with the aforementioned error.

Thus we can come to the conclusion that the elements inside the array are the culprits for this error in the code you've illustrated but then you should ask your self are null elements allowed in the first place and if so then filter them out before performing c.contains("something") and if not then you should debug at which point in your application were nulls added to the array when they should not be. find the bug rather than suppress it.

if null's are allowed in the first place then the solution is simple i.e. filter the nulls out before calling .contains:

int counter = (int)stream.filter(Objects::nonNull)
                         .filter(c -> c.contains("something")) // or single filter with c -> c != null && c.contains("something") as pred
                         .count();


问:
SQL: select all records not selected by another query
I am looking for an SQL query to select all records not selected by another query on the same table.
Specifically I want to select all records which have duplicates of a particular field('fieldA') and then delete all but one of those records.

So a select statement might be something like the following (which doesn't work!):

```select * from table where id not in(select * from table group by fieldA)```

If a single query is not possible then what would be the most efficient solution?

答:
Specifically I want to select all records which have duplicates of a particular field('fieldA') and then delete all but one of those records.

In that case, join it:

```<code>delete x
from myTable x
 join myTable z on x.field = z.field
where x.id > z.id
</code>```

Body:
I am looking for an SQL query to select all records not selected by another query on the same table.
Specifically I want to select all records which have duplicates of a particular field('fieldA') and then delete all but one of those records.

So a select statement might be something like the following (which doesn't work!):

select * from table where id not in(select * from table group by fieldA)

If a single query is not possible then what would be the most efficient solution?

Body:
Specifically I want to select all records which have duplicates of a particular field('fieldA') and then delete all but one of those records.

In that case, join it:

delete x
from myTable x
 join myTable z on x.field = z.field
where x.id > z.id


问:
How to resize a cropped image?
Goal:

My current goal is to crop the original image from pictureBox1 and show it in pictureBox2 and increase it's size (Height & Width) by 0.8.

Current Code:

```<code>//...
private Point LocationXY;
private Point LocationX1Y1;

private void button1_Click(object sender, EventArgs e)
{
    if (Clipboard.ContainsImage())
    {
        pictureBox1.Image?.Dispose();
        pictureBox1.Image = Clipboard.GetImage();
    }
}

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
        LocationXY = e.Location;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;
        pictureBox1.Invalidate();
    }
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;

        pictureBox1.Invalidate();
        pictureBox2.Invalidate();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (MouseButtons == MouseButtons.Left)
        e.Graphics.DrawRectangle(Pens.Red, GetRect());
}

private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
    var src = GetRect();

    if (src == Rectangle.Empty) return;

    var des = new Rectangle(0, 0, src.Width, src.Height);

    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    e.Graphics.CompositingQuality = CompositingQuality.HighQuality;

    e.Graphics.DrawImage(pictureBox1.Image,
        des, src, GraphicsUnit.Pixel);
}

private Rectangle GetRect()
{
    return new Rectangle(
        Math.Min(LocationXY.X, LocationX1Y1.X),
        Math.Min(LocationXY.Y, LocationX1Y1.Y),
        Math.Abs(LocationXY.X - LocationX1Y1.X),
        Math.Abs(LocationXY.Y - LocationX1Y1.Y)
        );
}
//...
</code>```

Cropping the image:

```<code>//...
private Bitmap GetCroppedImage()
{
    var src = GetRect();

    if (src == Rectangle.Empty) return null;

    var des = new Rectangle(0, 0, src.Width, src.Height);
    var b = new Bitmap(src.Width, src.Height);

    using (var g = Graphics.FromImage(b))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;

        g.DrawImage(pictureBox1.Image, des, src, GraphicsUnit.Pixel);
    }
    return b;
}
//...
</code>```

Current code - what does it do

Currently this code is able to mark an red area in pictureBox1 and show the cropped image in pictureBox2.

Question:

How do I increase/resize the cropped image height and width by 0.8?

答:
```<code>public static Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
            graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
        }
    }

    return destImage;
}
</code>```

Usage:

```<code>ResizeImage(originalImg, (int)(originalImg.Width * 0.8), (int)(originalImg.Height * 0.8));
</code>```

Title: How to resize a cropped image?

Body:
Goal:

My current goal is to crop the original image from pictureBox1 and show it in pictureBox2 and increase it's size (Height & Width) by 0.8.

Current Code:

//...
private Point LocationXY;
private Point LocationX1Y1;

private void button1_Click(object sender, EventArgs e)
{
    if (Clipboard.ContainsImage())
    {
        pictureBox1.Image?.Dispose();
        pictureBox1.Image = Clipboard.GetImage();
    }
}

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
        LocationXY = e.Location;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;
        pictureBox1.Invalidate();
    }
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;

        pictureBox1.Invalidate();
        pictureBox2.Invalidate();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (MouseButtons == MouseButtons.Left)
        e.Graphics.DrawRectangle(Pens.Red, GetRect());
}

private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
    var src = GetRect();

    if (src == Rectangle.Empty) return;

    var des = new Rectangle(0, 0, src.Width, src.Height);

    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    e.Graphics.CompositingQuality = CompositingQuality.HighQuality;

    e.Graphics.DrawImage(pictureBox1.Image,
        des, src, GraphicsUnit.Pixel);
}

private Rectangle GetRect()
{
    return new Rectangle(
        Math.Min(LocationXY.X, LocationX1Y1.X),
        Math.Min(LocationXY.Y, LocationX1Y1.Y),
        Math.Abs(LocationXY.X - LocationX1Y1.X),
        Math.Abs(LocationXY.Y - LocationX1Y1.Y)
        );
}
//...

Cropping the image:

//...
private Bitmap GetCroppedImage()
{
    var src = GetRect();

    if (src == Rectangle.Empty) return null;

    var des = new Rectangle(0, 0, src.Width, src.Height);
    var b = new Bitmap(src.Width, src.Height);

    using (var g = Graphics.FromImage(b))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;

        g.DrawImage(pictureBox1.Image, des, src, GraphicsUnit.Pixel);
    }
    return b;
}
//...

Current code - what does it do

Currently this code is able to mark an red area in pictureBox1 and show the cropped image in pictureBox2.

Question:

How do I increase/resize the cropped image height and width by 0.8?

Body:
public static Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
            graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
        }
    }

    return destImage;
}

Usage:

ResizeImage(originalImg, (int)(originalImg.Width * 0.8), (int)(originalImg.Height * 0.8));


问:
Losing references to objects inside containers
I am struggling to fix a piece of code, even though I believe I know the cause. I did search a lot on Stack Overflow and many people had similar issues (and good answers were provided), but still, I am not sure I understand the problem with my code.

I tried giving a smaller example, but the structure I have is not simple by itself. I hope the following is simple enough.

My objective on the excerpt:

Have a vector of points.

Have a vector of segments. (Whose endpoints are reference to points in the vector above)

Have a vector of events. (That keep a reference to the exhisting segments and points)

```<code>segment::segment (point &pt1, point&pt2, int i) {
   s = &pt1; e = &pt2; ind = i; // point *s, point *e, int ind
}
event::event (segment &s, point &pt, int tp) {
   seg = &s; type = tp; p = &pt; //segment *seg, int type, point *p
}
void pre_process (int size, std::vector<point>& pts, std::vector<event>& evts,
        std::vector<segment>& segs) {
    float x, y;
    for (int i = 0; i < size; ++ i) {
        std::cin >> x >> y;
        pts.push_back({x,y});
    }
    for (int i = 0; i < size; ++i) {
        int j = (i+1)%size;
        if (cmpXY(pts[i], pts[j]))
            segs.push_back({pts[i], pts[j], i});
        else
            segs.push_back({pts[j], pts[i], i});
        evts.push_back({segs[i], *segs[i].s, 0});
        evts.push_back({segs[i], *segs[i].e, 1});
        std::cout << 2*i << "\n";
        std::cout << segs[i].s << "\n";       //ALWAYS EQUAl
        std::cout << evts[2*i].seg->s << "\n";
    } // LINE X
    for (int i = 0; i < size; ++i) { //LINE Y
        std::cout << 2*i << "\n";
        std::cout << segs[i].s << "\n";        //DIFFERENT SOMETIMES
        std::cout << evts[2*i].seg->s << "\n";
    }
</code>```

So, the problem is that some of addresses my objects are pointing to change from LINE X to LINE Y. In particular, pts and segs remain the same.

From what I know and from what I understood here or here I cannot get the reference to an object on the stack of any function (my for loop, for example). However, I believe the lifetime of the object on the container is the same as the container itself. It makes me believe that all objects I push_back() should persist through the function pre_proccess and the function that is calling it.

答:
push_back on vector (might) invalidate previous reference/iterator.

it happens in the loop there

```<code>if (cmpXY(pts[i], pts[j]))
    segs.push_back({pts[i], pts[j], i});
else
    segs.push_back({pts[j], pts[i], i});
evts.push_back({segs[i], *segs[i].s, 0});
</code>```

you have to reserve enough place in segs to avoid reallocation (or change the logic).

Body:
I am struggling to fix a piece of code, even though I believe I know the cause. I did search a lot on Stack Overflow and many people had similar issues (and good answers were provided), but still, I am not sure I understand the problem with my code.

I tried giving a smaller example, but the structure I have is not simple by itself. I hope the following is simple enough.

My objective on the excerpt:

Have a vector of points.

Have a vector of segments. (Whose endpoints are reference to points in the vector above)

Have a vector of events. (That keep a reference to the exhisting segments and points)

segment::segment (point &pt1, point&pt2, int i) {
   s = &pt1; e = &pt2; ind = i; // point *s, point *e, int ind
}
event::event (segment &s, point &pt, int tp) {
   seg = &s; type = tp; p = &pt; //segment *seg, int type, point *p
}
void pre_process (int size, std::vector<point>& pts, std::vector<event>& evts,
        std::vector<segment>& segs) {
    float x, y;
    for (int i = 0; i < size; ++ i) {
        std::cin >> x >> y;
        pts.push_back({x,y});
    }
    for (int i = 0; i < size; ++i) {
        int j = (i+1)%size;
        if (cmpXY(pts[i], pts[j]))
            segs.push_back({pts[i], pts[j], i});
        else
            segs.push_back({pts[j], pts[i], i});
        evts.push_back({segs[i], *segs[i].s, 0});
        evts.push_back({segs[i], *segs[i].e, 1});
        std::cout << 2*i << "\n";
        std::cout << segs[i].s << "\n";       //ALWAYS EQUAl
        std::cout << evts[2*i].seg->s << "\n";
    } // LINE X
    for (int i = 0; i < size; ++i) { //LINE Y
        std::cout << 2*i << "\n";
        std::cout << segs[i].s << "\n";        //DIFFERENT SOMETIMES
        std::cout << evts[2*i].seg->s << "\n";
    }

So, the problem is that some of addresses my objects are pointing to change from LINE X to LINE Y. In particular, pts and segs remain the same.

From what I know and from what I understood here or here I cannot get the reference to an object on the stack of any function (my for loop, for example). However, I believe the lifetime of the object on the container is the same as the container itself. It makes me believe that all objects I push_back() should persist through the function pre_proccess and the function that is calling it.

Body:
push_back on vector (might) invalidate previous reference/iterator.

it happens in the loop there

if (cmpXY(pts[i], pts[j]))
    segs.push_back({pts[i], pts[j], i});
else
    segs.push_back({pts[j], pts[i], i});
evts.push_back({segs[i], *segs[i].s, 0});

you have to reserve enough place in segs to avoid reallocation (or change the logic).