问:
error when using slick slider on multiple elements
I'm trying to apply the Slick Slider plugin in my project. the plugin works ok when it's applied to just 1 element. but when I try to apply it to more than 1 element, it only works for the 1st element in the script.. after that it returns an error _.$slides is null. Tarnjeet Singh said it might be because there are multiple slick slider script in the page, but I checked and there's only 1 script call. what am I doing wrong here?

my HTML looks like this:

```<code><section class="gallery-slide slider use-slider">
    <div class="slide">
        <a href="#">
            <div class="my-slide-img"
            style="background-image: url('/assets/img/gallery/2010/img-0001.jpg');"></div>
        </a>
    </div>
    <div class="slide">
        <a href="#">
            <div class="my-slide-img"
            style="background-image: url('/assets/img/gallery/2010/img-0002.jpg');"></div>
        </a>
    </div>
</section>

<section class="other-slide slider use-slider">
    <div class="slide fc02">
        <a href="#" target="_blank()">
            <div class="other-slide-img"
            style="background-image: url('/assets/img/cover/img-1001.jpg');">
            </div>

            <div class="other-slide-title">My First Post</div>
        </a>
    </div>
    <div class="slide fc02">
        <a href="#" target="_blank()">
            <div class="other-slide-img"
            style="background-image: url('/assets/img/cover/img-1002.jpg');">
            </div>

            <div class="other-slide-title">My Second Post</div>
        </a>
    </div>
</section>
</code>```

and this is the script I've tried.. I even tried using each as advised by kanudo

```<code>$('.use-slider').each(function(key, item) {
    var selector = 'slider_'+key.toString();

    $(this).attr('id', selector);

    var sliderID = '#' + $(this).attr('id');

    if ($(sliderID).hasClass('gallery-slide')) {
        $(sliderID).slick({
            slidesToShow: 4,
            slidesToScroll: 1,
            autoplay: true,
            autoplaySpeed: 2500,
            arrows: false,
            dots: false,
            pauseOnHover: true,
            responsive: [{
                breakpoint: 992,
                settings: {
                    slidesToShow: 3
                }
            }, {
                breakpoint: 768,
                settings: {
                    slidesToShow: 2
                }
            }, {
                breakpoint: 520,
                settings: {
                    slidesToShow: 2
                }
            }]
        });
    }
    else if ($(sliderID).hasClass('other-slide')) {
        $(sliderID).slick({
            slidesToShow: 4,
            slidesToScroll: 1,
            autoplay: false,
            autoplaySpeed: 2500,
            arrows: false,
            dots: false,
            pauseOnHover: true,
            responsive: [{
                breakpoint: 992,
                settings: {
                    slidesToShow: 3
                }
            }, {
                breakpoint: 768,
                settings: {
                    slidesToShow: 2
                }
            }, {
                breakpoint: 520,
                settings: {
                    slidesToShow: 2
                }
            }]
        });
    }
});
</code>```

答:
I finally got it working by using a more specific selector. it turns out the script DID run more than once so the same element was affected twice.. that's what was causing the _.$slides is null error. so everytime the slick plugin is applied to an element, I needed to remove the use-slider class to make sure that element will only be affected once.

here's how my script looks like now. in case anyone have the same problem.

```<code>$('.gallery-slide.use-slider').each(function(key, item) {
  var selector = 'gallery_slider-' + key;
  $(this).attr('id', selector);
  var sliderID = '#' + selector;
  $(sliderID).slick({
    slidesToShow: 4,
    slidesToScroll: 1,
    .. (other slick slider parameters)
  });
  $(sliderID).removeClass('use-slider');
});

$('.other-slide.use-slider').each(function(key, item) {
  var selector = 'other_slider-' + key;
  $(this).attr('id', selector);
  var sliderID = '#' + selector;
  $(sliderID).slick({
    slidesToShow: 4,
    slidesToScroll: 1,
    .. (other slick slider parameters)
  });
  $(sliderID).removeClass('use-slider');
});
</code>```

Body:
I'm trying to apply the Slick Slider plugin in my project. the plugin works ok when it's applied to just 1 element. but when I try to apply it to more than 1 element, it only works for the 1st element in the script.. after that it returns an error _.$slides is null. Tarnjeet Singh said it might be because there are multiple slick slider script in the page, but I checked and there's only 1 script call. what am I doing wrong here?

my HTML looks like this:

My First Post

My Second Post

and this is the script I've tried.. I even tried using each as advised by kanudo

$('.use-slider').each(function(key, item) {
    var selector = 'slider_'+key.toString();

    $(this).attr('id', selector);

    var sliderID = '#' + $(this).attr('id');

    if ($(sliderID).hasClass('gallery-slide')) {
        $(sliderID).slick({
            slidesToShow: 4,
            slidesToScroll: 1,
            autoplay: true,
            autoplaySpeed: 2500,
            arrows: false,
            dots: false,
            pauseOnHover: true,
            responsive: [{
                breakpoint: 992,
                settings: {
                    slidesToShow: 3
                }
            }, {
                breakpoint: 768,
                settings: {
                    slidesToShow: 2
                }
            }, {
                breakpoint: 520,
                settings: {
                    slidesToShow: 2
                }
            }]
        });
    }
    else if ($(sliderID).hasClass('other-slide')) {
        $(sliderID).slick({
            slidesToShow: 4,
            slidesToScroll: 1,
            autoplay: false,
            autoplaySpeed: 2500,
            arrows: false,
            dots: false,
            pauseOnHover: true,
            responsive: [{
                breakpoint: 992,
                settings: {
                    slidesToShow: 3
                }
            }, {
                breakpoint: 768,
                settings: {
                    slidesToShow: 2
                }
            }, {
                breakpoint: 520,
                settings: {
                    slidesToShow: 2
                }
            }]
        });
    }
});

Body:
I finally got it working by using a more specific selector. it turns out the script DID run more than once so the same element was affected twice.. that's what was causing the _.$slides is null error. so everytime the slick plugin is applied to an element, I needed to remove the use-slider class to make sure that element will only be affected once.

here's how my script looks like now. in case anyone have the same problem.

$('.gallery-slide.use-slider').each(function(key, item) {
  var selector = 'gallery_slider-' + key;
  $(this).attr('id', selector);
  var sliderID = '#' + selector;
  $(sliderID).slick({
    slidesToShow: 4,
    slidesToScroll: 1,
    .. (other slick slider parameters)
  });
  $(sliderID).removeClass('use-slider');
});

$('.other-slide.use-slider').each(function(key, item) {
  var selector = 'other_slider-' + key;
  $(this).attr('id', selector);
  var sliderID = '#' + selector;
  $(sliderID).slick({
    slidesToShow: 4,
    slidesToScroll: 1,
    .. (other slick slider parameters)
  });
  $(sliderID).removeClass('use-slider');
});


来源: stackexchange

问:
LinkedList indexOf method implementation
I have the following method in a program of mine:

```<code>/**
 * Returns the index of the first occurrence of the specified item.
 * If the specified item in not part of the list
 * the method indexOf returns -1
 *
 * @param item
 * @return index of the first occurrence of the item; -1 if the word was not found.
 */
public int indexOf(String item) {

    int index = 0;

    //While we haven't reached the end of the list
    while(head != null) {
        //If the items are equal return true
        if(head.item == item) {
            return index;
        }
        //Set the head to the next and increment the index
        head = head.next;
        index++;
    }
    return -1;
}
</code>```

While everything looks correct to me (other than needing to change head.item == item to head.item.equals(item)), it is not giving me the correct index.

While it does give me -1 for an element that is not in the lest, every time it is returning 0 as the index for an element that is in the list and I cannot figure out for the life of me why index is not incrementing.

Any input would be greatly appreciated! Thanks

答:
You seem to be changing the head value when you iterate through the list in indexOf and contains. The head value should always point to the first entry in your list and only be changed if needed by append and prepend. To iterate, you should use a local variable to cycle through the list. Also you should use .equals to compare String values, not ==.

public int indexOf(String item) {

    int index = 0;
    Node current = head;

    //While we haven't reached the end of the list
    while(current != null) {
        //If the items are equal return the index
        if(current.item.equals(item)) {
            return index;
        }
        //Set current to the next and increment the index
        current = current.next;
        index++;
    }
    return -1;
}
```

ContentLicense: CC BY-SA 4.0

Body:
I have the following method in a program of mine:

/**
 * Returns the index of the first occurrence of the specified item.
 * If the specified item in not part of the list
 * the method indexOf returns -1
 *
 * @param item
 * @return index of the first occurrence of the item; -1 if the word was not found.
 */
public int indexOf(String item) {

    int index = 0;

    //While we haven't reached the end of the list
    while(head != null) {
        //If the items are equal return true
        if(head.item == item) {
            return index;
        }
        //Set the head to the next and increment the index
        head = head.next;
        index++;
    }
    return -1;
}

While everything looks correct to me (other than needing to change head.item == item to head.item.equals(item)), it is not giving me the correct index.

While it does give me -1 for an element that is not in the lest, every time it is returning 0 as the index for an element that is in the list and I cannot figure out for the life of me why index is not incrementing.

Any input would be greatly appreciated! Thanks


问:
Problem plotting line at price coordinates
I am writing a simple indicator displaying vertical and
horizontal lines.
The vertical line should be plotted at the new york open price which
I am getting from a timestamp comparison, however the lines y coordinate
is not correct. Any help highly appreciated as I am struggling for a while now.</p>

```<code>//@version=4
study("Sessions",overlay=true, scale=scale.none)
t1 = timestamp("GMT", year, month, dayofmonth, 0, 00, 00)
t2 = timestamp("GMT-5", year, month, dayofmonth, 0, 00, 00)

backLook = 86400000 * 1.5

displayCondition = timeframe.isdwm == false and (time > timenow - backLook)

vline(BarIndex, Color, LineStyle, LineWidth) => // Verticle Line, 54 lines maximum allowable per indicator
    return = line.new(BarIndex, -1000, BarIndex, 1000, xloc.bar_index, extend.both, Color, LineStyle, LineWidth)

drawPrice(price) =>
    x = bar_index
    y = price
    txt = tostring(price)
    label.new(x, price, txt)

    // y position is always wrong, the label text displays the correct price though
    line.new(x1=t2, y1=y, color=#ec4069, x2=time + 86400000, y2=y,xloc=xloc.bar_time)

// ny open
if(time == t2 and displayCondition)
    vline(bar_index, #ec4069, line.style_solid, 1)

if(time == t2 and displayCondition)
    drawPrice(open)

// gmt open
if(time == t1 and displayCondition)
    vline(bar_index, #000000, line.style_solid, 1)

</code>```

答:
The reason for the problem is the 'No Scale' mode. In order to disable that mode and fix the problem, remove the scale parameter from the study call:

```<code>study("Sessions",overlay=true)
</code>```

Body:
I am writing a simple indicator displaying vertical and
horizontal lines.
The vertical line should be plotted at the new york open price which
I am getting from a timestamp comparison, however the lines y coordinate
is not correct. Any help highly appreciated as I am struggling for a while now.

//@version=4
study("Sessions",overlay=true, scale=scale.none)
t1 = timestamp("GMT", year, month, dayofmonth, 0, 00, 00)
t2 = timestamp("GMT-5", year, month, dayofmonth, 0, 00, 00)

backLook = 86400000 * 1.5

displayCondition = timeframe.isdwm == false and (time > timenow - backLook)

vline(BarIndex, Color, LineStyle, LineWidth) => // Verticle Line, 54 lines maximum allowable per indicator
    return = line.new(BarIndex, -1000, BarIndex, 1000, xloc.bar_index, extend.both, Color, LineStyle, LineWidth)

drawPrice(price) =>
    x = bar_index
    y = price
    txt = tostring(price)
    label.new(x, price, txt)

    // y position is always wrong, the label text displays the correct price though
    line.new(x1=t2, y1=y, color=#ec4069, x2=time + 86400000, y2=y,xloc=xloc.bar_time)

// ny open
if(time == t2 and displayCondition)
    vline(bar_index, #ec4069, line.style_solid, 1)

if(time == t2 and displayCondition)
    drawPrice(open)

// gmt open
if(time == t1 and displayCondition)
    vline(bar_index, #000000, line.style_solid, 1)

Body:
The reason for the problem is the 'No Scale' mode. In order to disable that mode and fix the problem, remove the scale parameter from the study call:

study("Sessions",overlay=true)


问:
Fortran array input
I haven't done any Fortran programming for year and it seems I'm rather rusty now. So, I won't provide you with all my failed attempts but will humbly ask you to help me with the following.
I've got the following "input" file

```<code>1 5 e 4
A b & 1
c Z ; b
y } " N
t r ' +
</code>```

It can have more columns and/or rows. I would now like to assign each of these ASCII characters to arrays x(i,j) so that I can process them further after ICHAR conversions. In this example i=1,4, j=1,5, but it can be any No depending on the input file. The simplest example

```<code>PROGRAM Example
integer :: i, j
CHARACTER, ALLOCATABLE, DIMENSION(:,:) :: A
READ *, A
ALLOCATE (A(i,j))
PRINT *, A
END PROGRAM Example
</code>```

compiles (Example.f95) but

```<code>cat input | ./Example.f95
</code>```

does not give any output.
I would greatly appreciate an advice on how to import the afore-mentioned strings into the program as x(i,j) terms of an array.

答:
In Fortran, it's always best to know in advance how big your arrays need to be. I understand that in your case you can't know.

Assuming that your input is at least formatted correctly (i.e. the columns match up and have only a single space in between them), I've created a code that should in theory be able to read them in an arbitrary shape. (Not quite arbitrary, it assumes that there are fewer than 511 columns.)

It uses two ways:

It simply reads the first line in at once (1024 characters, hence the 511 limit on columns) then calculates from the length the number of columns

It then allocates an array with a guessed number of rows, and once it notices that the guess was too small, it creates a new allocation with double the number of rows. It then uses the move_alloc command to swap the allocations.

To find when it should end reading the values, it simply checks whether the read returns the IOSTAT_END error code.

Here's the code:

```<code>program read_input

    use iso_fortran_env, only: IOSTAT_END
    implicit none
    character, dimension(:,:), allocatable :: A, A_tmp
    character(len=1024) :: line  ! Assumes that there are never more than 500 or so columns
    integer :: i, ncol, nrow, nrow_guess
    integer :: ios
    character :: iom

    ! First, read the first line, to see how many columns there are
    read(*, '(A)', iostat=ios, iomsg=iom) line
    call iocheck('read first line', ios, iom)

    ncol = (len_trim(line) + 1) / 2

    ! Let's first allocate memory for two rows, we can make it more later.
    nrow_guess = 2
    allocate(A(ncol, nrow_guess))

    ! Instead of standard input, we're reading from the line we read before.
    read(line, '(*(A1,X))', iostat=ios, iomsg=iom) A(:, 1)
    call iocheck('read first line into vals', ios, iom)

    ! Now loop over all the rows
    nrow = 1
    read_loop: do

        if (nrow >= nrow_guess) then    ! We have guessed too small.
                                        ! This is a bit convoluted, but the best
                                        ! way to increase the array shape.
            nrow_guess = nrow_guess * 2
            allocate(A_tmp(ncol, nrow_guess))
            A_tmp(:, 1:nrow_guess/2) = A(:,:)
            call move_alloc(A_tmp, A)
        end if

        read(*, '(*(A1,X))', iostat = ios, iomsg=iom) A(:, nrow+1)
        if (ios == IOSTAT_END) exit read_loop   ! We're done reading.
        call iocheck('read line into vals', ios, iom)
        nrow = nrow + 1

    end do read_loop

    ! The last guess was probably too large,
    ! let's move it to an array of the correct size.
    if (nrow < nrow_guess) then
        allocate(A_tmp(ncol, nrow))
        A_tmp(:,:) = A(:, 1:nrow)
        call move_alloc(A_tmp, A)
    end if

    ! To show we have all values, print them out.
    do i = 1, nrow
        print '(*(X,A))', A(:, i)
    end do

contains

    ! This is a subroutine to check for IO Errors
    subroutine iocheck(op, ios, iom)
        character(len=*), intent(in) :: op, iom
        integer, intent(in) :: ios
        if (ios == 0) return
        print *, "IO ERROR"
        print *, "Operation: ", op
        print *, "Message: ", iom
    end subroutine iocheck
end program read_input
</code>```

Edited to add

I had trouble with the special characters in your example input file, otherwise I'd just have made a read(*, *) A(:, nrow) -- but that messed the special characters up. That's why I chose the explicit (*(A1, X)) format. Of course that messes up when your characters don't start at the first position in the line.

Title: Fortran array input

Body:
I haven't done any Fortran programming for year and it seems I'm rather rusty now. So, I won't provide you with all my failed attempts but will humbly ask you to help me with the following.
I've got the following "input" file

1 5 e 4
A b & 1
c Z ; b
y } " N
t r ' +

It can have more columns and/or rows. I would now like to assign each of these ASCII characters to arrays x(i,j) so that I can process them further after ICHAR conversions. In this example i=1,4, j=1,5, but it can be any No depending on the input file. The simplest example

PROGRAM Example
integer :: i, j
CHARACTER, ALLOCATABLE, DIMENSION(:,:) :: A
READ *, A
ALLOCATE (A(i,j))
PRINT *, A
END PROGRAM Example

compiles (Example.f95) but

cat input | ./Example.f95

does not give any output.
I would greatly appreciate an advice on how to import the afore-mentioned strings into the program as x(i,j) terms of an array.

Body:
In Fortran, it's always best to know in advance how big your arrays need to be. I understand that in your case you can't know.

Assuming that your input is at least formatted correctly (i.e. the columns match up and have only a single space in between them), I've created a code that should in theory be able to read them in an arbitrary shape. (Not quite arbitrary, it assumes that there are fewer than 511 columns.)

It uses two ways:

It simply reads the first line in at once (1024 characters, hence the 511 limit on columns) then calculates from the length the number of columns

It then allocates an array with a guessed number of rows, and once it notices that the guess was too small, it creates a new allocation with double the number of rows. It then uses the move_alloc command to swap the allocations.

To find when it should end reading the values, it simply checks whether the read returns the IOSTAT_END error code.

Here's the code:

program read_input

    use iso_fortran_env, only: IOSTAT_END
    implicit none
    character, dimension(:,:), allocatable :: A, A_tmp
    character(len=1024) :: line  ! Assumes that there are never more than 500 or so columns
    integer :: i, ncol, nrow, nrow_guess
    integer :: ios
    character :: iom

    ! First, read the first line, to see how many columns there are
    read(*, '(A)', iostat=ios, iomsg=iom) line
    call iocheck('read first line', ios, iom)

    ncol = (len_trim(line) + 1) / 2

    ! Let's first allocate memory for two rows, we can make it more later.
    nrow_guess = 2
    allocate(A(ncol, nrow_guess))

    ! Instead of standard input, we're reading from the line we read before.
    read(line, '(*(A1,X))', iostat=ios, iomsg=iom) A(:, 1)
    call iocheck('read first line into vals', ios, iom)

    ! Now loop over all the rows
    nrow = 1
    read_loop: do

        if (nrow >= nrow_guess) then    ! We have guessed too small.
                                        ! This is a bit convoluted, but the best
                                        ! way to increase the array shape.
            nrow_guess = nrow_guess * 2
            allocate(A_tmp(ncol, nrow_guess))
            A_tmp(:, 1:nrow_guess/2) = A(:,:)
            call move_alloc(A_tmp, A)
        end if

        read(*, '(*(A1,X))', iostat = ios, iomsg=iom) A(:, nrow+1)
        if (ios == IOSTAT_END) exit read_loop   ! We're done reading.
        call iocheck('read line into vals', ios, iom)
        nrow = nrow + 1

    end do read_loop

    ! The last guess was probably too large,
    ! let's move it to an array of the correct size.
    if (nrow < nrow_guess) then
        allocate(A_tmp(ncol, nrow))
        A_tmp(:,:) = A(:, 1:nrow)
        call move_alloc(A_tmp, A)
    end if

    ! To show we have all values, print them out.
    do i = 1, nrow
        print '(*(X,A))', A(:, i)
    end do

contains

    ! This is a subroutine to check for IO Errors
    subroutine iocheck(op, ios, iom)
        character(len=*), intent(in) :: op, iom
        integer, intent(in) :: ios
        if (ios == 0) return
        print *, "IO ERROR"
        print *, "Operation: ", op
        print *, "Message: ", iom
    end subroutine iocheck
end program read_input

Edited to add

I had trouble with the special characters in your example input file, otherwise I'd just have made a read(*, *) A(:, nrow) -- but that messed the special characters up. That's why I chose the explicit (*(A1, X)) format. Of course that messes up when your characters don't start at the first position in the line.


问:
Private trait in public interface when blanket implement public trait to private trait
Currently, I'm trying to blanket implement a public trait on any struct that implement a private trail, but i get compiler warning: private trait `mod_b::PrivateTrait` in public interface (error E0445) Is there anyway to fix this?

main.rs:

```<code>trait PublicTrait {}

mod mod_b
{
    use PublicTrait;
    trait PrivateTrait {}

    impl<T: PrivateTrait> PublicTrait for T {}
}

pub fn main ()
{
}
</code>```

答:
You need to make the PrivateTrait public

trait PublicTrait {}

mod mod_b {
    use crate::PublicTrait;
    pub trait PrivateTrait {}

    impl<T: PrivateTrait> PublicTrait for T {}
}

fn test<T: PublicTrait>(_: T){
    println!("public")
}

struct Private;
impl mod_b::PrivateTrait for Private {}

pub fn main() {
    test(Private);
}

```

<p>Or to keep <code>PrivateTrait</code> private in <code>mod_b</code></p>

<pre class="lang-rust prettyprint-override"><code>trait PublicTrait {}

mod mod_b {
    use crate::PublicTrait;
    trait PrivateTrait {}

    impl<T: PublicTrait> PrivateTrait for T {}
}

fn main() {}
</code>```

Body:
Currently, I'm trying to blanket implement a public trait on any struct that implement a private trail, but i get compiler warning: private trait `mod_b::PrivateTrait` in public interface (error E0445) Is there anyway to fix this?

main.rs:

trait PublicTrait {}

mod mod_b
{
    use PublicTrait;
    trait PrivateTrait {}

    impl<T: PrivateTrait> PublicTrait for T {}
}

pub fn main ()
{
}

Body:
You need to make the PrivateTrait public

trait PublicTrait {}

mod mod_b {
    use crate::PublicTrait;
    pub trait PrivateTrait {}

    impl<T: PrivateTrait> PublicTrait for T {}
}

fn test<T: PublicTrait>(_: T){
    println!("public")
}

struct Private;
impl mod_b::PrivateTrait for Private {}

pub fn main() {
    test(Private);
}

Or to keep PrivateTrait private in mod_b

trait PublicTrait {}

mod mod_b {
    use crate::PublicTrait;
    trait PrivateTrait {}

    impl<T: PublicTrait> PrivateTrait for T {}
}

fn main() {}


问:
how to set a default value on a data does not exists on the table
I have this mysql query sample which is to get the latest status of a user from another table

you can see it here : SQL FIDDLE

So if an accountId  exists in heat table it will get the lastest status but if the accountId doesn't exist on the table the supposed status was -1

but when I tried to run the query the accountId that wasn't on the heat table it returns NULL instead of -1

I tried to replace the IFNULL to IF or COALESCE but still, it returns NULL

答:
Solution for your problem:

```<code>SELECT M.accountid,IFNULL(HS.status,-1) as status
FROM members M
LEFT JOIN
(SELECT accountID,MAX(dateCreated) as MaxDate
FROM Heat
GROUP BY accountID) H
ON M.accountID = H.accountID
LEFT JOIN Heat HS
ON H.accountId = HS.accountId AND H.MaxDate = HS.dateCreated
WHERE M.isDeleted != 1
ORDER BY M.accountid ASC;
</code>```

Demo for the same (Sample Data Structure is based on columns given in query):

SQL FIDDLE

Body:
Solution for your problem:

SELECT M.accountid,IFNULL(HS.status,-1) as status
FROM members M
LEFT JOIN
(SELECT accountID,MAX(dateCreated) as MaxDate
FROM Heat
GROUP BY accountID) H
ON M.accountID = H.accountID
LEFT JOIN Heat HS
ON H.accountId = HS.accountId AND H.MaxDate = HS.dateCreated
WHERE M.isDeleted != 1
ORDER BY M.accountid ASC;

Demo for the same (Sample Data Structure is based on columns given in query):

SQL FIDDLE


问:
Sonarqube RTC integration and capability
I want to integrate RTC with sonarqube, requirement to do the same is to check the code with sonarqube and on successful result only it should get delivered to server.
As of now I have installed sonar server on my machine with JAZZ RTC plugin.
Now how to go about the above requirement, how to trigger the sonarqube test to every checkin, what all are the capabilities available to me.</p>

答:
I have a workaround of this by using jenkins.
Installed Team concert plugin in jenkins.
Installed Sonarqube plugins in jenkins.
Configured RTC and sonarqube in global configurations of jenkins.
Created job in jenkins defining the RTC configuration, respository workspace to build, and sonar settings to perform sonar checks on the code checked out from stream.

Note:- Also installed and configured maven plugin in jenkins.


问:
click_action attribute for web push notification through FCM
My questions is some what similar to (question) but with some differences.
I am using FCM Admin SDK, but still do not see an option to send the click_action attribute for Web Push notifications.
I checked out admin.messaging.NotificationMessagePayload as well, but looks like this is only applicable to Android and iOS.

As per the comments in the above questions, this click_action is not available for web push using http v1 API (and I think FCM admin SDK as well)

Please help me on how to send the click_action attribute for a web push notification using FCM Admin SDK.
If there are any other workarounds, that would be helpful as well.

Thanks in advance.

答:
There is some confusion on how to open a page once you click on the notification popup. The documentation asks to use FCMOptions link attribute however it does not correctly open the page but just brings the browser to the foreground with the last tab to focus(). The solution to this is to change the payload to  use click_action.

```<code>"notification":{
   "body":"this is the notification text",
   "title":"New Notification",
   "click_action":"https://theURLyouwanttoopen.com/"
}
</code>```

Check more

Body:
There is some confusion on how to open a page once you click on the notification popup. The documentation asks to use FCMOptions link attribute however it does not correctly open the page but just brings the browser to the foreground with the last tab to focus(). The solution to this is to change the payload to  use click_action.

"notification":{
   "body":"this is the notification text",
   "title":"New Notification",
   "click_action":"https://theURLyouwanttoopen.com/"
}

Check more


问:
CSS: equal border around 3 images (different sizes) dynamically generated
I have a div that get 3 spans with images in them. The images are often different sizes, images are dynamically selected.

```<code><div id="main" style="display: block;">
 <span id="1"><img src="url1" style="max-width:30%"></span>
 <span id="2"><img src="url2" style="max-width:30%"></span>
 <span id="3"><img src="url3" style="max-width:30%"></span>
</div>
</code>```

The image fit width wise. What I am looking for is equal borders around the different size images.

Have tried: .main span {border: solid 5px gray; height: 100%;} and many other options.

On a computer, the 3 images would be side by side. On a phone the images would be on top of each other. And all with equal borders.

Thanks.

答:
Use media queries to place the images on top of each other on the phone and side by side on computer.

Do not use inline-styles, because they will overwrite your style sheet.

Does this suit your needs?

body {
  margin: 0;
  padding: 0;
}

* {
  /* subtract border and padding from element's width */
  box-sizing: border-box;
}

#main .image-list {
  display: flex;
  flex-wrap: wrap;
}

#main .image-list>span {
  display: block;
  /*add 4px (2 x 2px) space between photos */
  padding: 2px;
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  align-items: streach;
  justify-content: center;
}

#main span.border {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

#main span.border img {
  /*replace with width: 100% if you want to force the image to full width */
  max-width: 100%;
  display: block;
}

/* Desktop break-point */

@media (min-width: 992px) {
  #main .image-list > span {
    width: 33.333%;
    padding: 0 2px;
  }
  #main .image-list>span:nth-child(3n) {
    padding-right: 0;
  }
  #main .image-list>span:nth-child(4n+1) {
    padding-left: 0;
  }
  #main span.border {
    border: 5px solid gray;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main">
  <div class="image-list">
    <span id="1">
      <span class="border"><img src="https://picsum.photos/100/100?gravity=east"></span>
    </span>
    <span id="2">
      <span class="border">
        <img src="https://picsum.photos/600/600?gravity=west">
      </span>
    </span>
    <span id="3">
      <span class="border">
        <img src="https://picsum.photos/500/500?gravity=south">
      </span>
    <div>
    </div></code>```

Body:
I have a div that get 3 spans with images in them. The images are often different sizes, images are dynamically selected.

The image fit width wise. What I am looking for is equal borders around the different size images.

Have tried: .main span {border: solid 5px gray; height: 100%;} and many other options.

On a computer, the 3 images would be side by side. On a phone the images would be on top of each other. And all with equal borders.

Thanks.

Body:
Use media queries to place the images on top of each other on the phone and side by side on computer.

Do not use inline-styles, because they will overwrite your style sheet.

Does this suit your needs?

body {
  margin: 0;
  padding: 0;
}

* {
  /* subtract border and padding from element's width */
  box-sizing: border-box;
}

#main .image-list {
  display: flex;
  flex-wrap: wrap;
}

#main .image-list>span {
  display: block;
  /*add 4px (2 x 2px) space between photos */
  padding: 2px;
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  align-items: streach;
  justify-content: center;
}

#main span.border {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

#main span.border img {
  /*replace with width: 100% if you want to force the image to full width */
  max-width: 100%;
  display: block;
}

/* Desktop break-point */

@media (min-width: 992px) {
  #main .image-list > span {
    width: 33.333%;
    padding: 0 2px;
  }
  #main .image-list>span:nth-child(3n) {
    padding-right: 0;
  }
  #main .image-list>span:nth-child(4n+1) {
    padding-left: 0;
  }
  #main span.border {
    border: 5px solid gray;
  }
}

<div id="main">
  <div class="image-list">
    <span id="1">
      <span class="border"><img src="https://picsum.photos/100/100?gravity=east"></span>
    </span>
    <span id="2">
      <span class="border">
        <img src="https://picsum.photos/600/600?gravity=west">
      </span>
    </span>
    <span id="3">
      <span class="border">
        <img src="https://picsum.photos/500/500?gravity=south">
      </span>
    <div>
    </div>


问:
how can I balance these brackets in this recursive function?
I'm trying to write a recursive Python function to get all of the successive 1 or 2 digit orderings from a given number.  For example, given 123, the result would be: [[1, 2, 3], [12, 3], [1, 23]].

I've written a function that seems to be on the right track but I can't balance the brackets.

```<code>def gen_codes(num):

    if len(str(num)) == 1:
        return [[num]]
    result = []
    for i in range(1, 3):
        rest_str = str(num)[i:]
        path = [int(str(num)[0:i])]
        if len(rest_str):
            path = [path + x for x in gen_codes(int(rest_str))]
        result.append(path)
    return result

print(gen_codes(123))
</code>```

This outputs:

```<code>[[[1, [2, 3]], [1, 23]], [[12, 3]]]
</code>```

Expected:

```<code>[[1, 2, 3], [12, 3], [1, 23]]
</code>```

答:
Your problem is with this line:

```<code>path = [path + x for x in gen_codes(int(rest_str))]
</code>```

as it is adding an extra level of nesting of the lists. You should replace this code:

```<code>if len(rest_str):
    path = [path + x for x in gen_codes(int(rest_str))]
result.append(path)
</code>```

with

```<code>if len(rest_str):
    for x in gen_codes(int(rest_str)):
        result.append(path + x)
else:
    result.append(path)
</code>```

and then your code will produce the desired results. For example:

```<code>print(gen_codes(123))
print(gen_codes(1234))
print(gen_codes(12345))
</code>```

Output:

```<code>[[1, 2, 3], [1, 23], [12, 3]]
[[1, 2, 3, 4], [1, 2, 34], [1, 23, 4], [12, 3, 4], [12, 34]]
[[1, 2, 3, 4, 5], [1, 2, 3, 45], [1, 2, 34, 5], [1, 23, 4, 5], [1, 23, 45], [12, 3, 4, 5], [12, 3, 45], [12, 34, 5]]
</code>```

Body:
I'm trying to write a recursive Python function to get all of the successive 1 or 2 digit orderings from a given number.  For example, given 123, the result would be: [[1, 2, 3], [12, 3], [1, 23]].

I've written a function that seems to be on the right track but I can't balance the brackets.

def gen_codes(num):

    if len(str(num)) == 1:
        return [[num]]
    result = []
    for i in range(1, 3):
        rest_str = str(num)[i:]
        path = [int(str(num)[0:i])]
        if len(rest_str):
            path = [path + x for x in gen_codes(int(rest_str))]
        result.append(path)
    return result

print(gen_codes(123))

This outputs:

[[[1, [2, 3]], [1, 23]], [[12, 3]]]

Expected:

[[1, 2, 3], [12, 3], [1, 23]]

Body:
Your problem is with this line:

path = [path + x for x in gen_codes(int(rest_str))]

as it is adding an extra level of nesting of the lists. You should replace this code:

if len(rest_str):
    path = [path + x for x in gen_codes(int(rest_str))]
result.append(path)

with

if len(rest_str):
    for x in gen_codes(int(rest_str)):
        result.append(path + x)
else:
    result.append(path)

and then your code will produce the desired results. For example:

print(gen_codes(123))
print(gen_codes(1234))
print(gen_codes(12345))

Output:

[[1, 2, 3], [1, 23], [12, 3]]
[[1, 2, 3, 4], [1, 2, 34], [1, 23, 4], [12, 3, 4], [12, 34]]
[[1, 2, 3, 4, 5], [1, 2, 3, 45], [1, 2, 34, 5], [1, 23, 4, 5], [1, 23, 45], [12, 3, 4, 5], [12, 3, 45], [12, 34, 5]]


问:
Checking what choices Mathematica makes when you specify "Automatic"
So I'm doing some benchmarking of a method for numerical optimization in Mathematica and I'm getting some inconsistent results when I use the Method->Automatic specification with FindMinimum. What I want to do is check what method it is choosing. I know I can use AbsoluteOptions[] to extract the choices from a some output, like a Graphics object, but this doesn't work with FindMinimum, ie

AbsoluteOptions[ Findminimum[ f[x], {x, 0.}, Method->Automatic ], Method ]

doesn't work. Can I do this?

答:
I don't think there is a general way to find what method is used by numerical functions, other than reading the documentation.  The documentation on unconstrained optimization is pretty good, though.  There it says:

With Method -> Automatic, Mathematica uses the "quasi-Newton" method
  unless the problem is structurally a sum of squares, in which case
  the Levenberg-Marquardt variant of the "Gauss-Newton" method is used.
  When given two starting conditions in each variable, the "principal axis"
  method is used.

Additionally, for constrained problems the interior point method is used.  If the problem is linear (objective and constraints) linear programming will be used.  (LP itself has, I think, three methods that are used, depending on size and other features.)

ContentLicense: CC BY-SA 3.0


问:
Laravel: Swift_TransportException: Connection could not be established with host
Can't send email from Laravel platform. Tried with different another emails (gmail, mailgun) and they work properly but it seems that can't make it work with the one our customer wants to use:

```<code>MAIL_DRIVER=smtp
MAIL_HOST=xxx.xxx.xx
MAIL_PORT=25
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
</code>```

We got this error:

Swift_TransportException: Connection could not be established with
  host [php_network_getaddresses: getaddrinfo failed: Name or service
  not known #0] in
  .../vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php:269

I can connect with telnet from the server so it apparently everything's ok. But I find very weird this configuration. Do I need to check something else in Laravel to make it work?

EDIT 1:

Tried with this configuration too:

```<code>MAIL_DRIVER=smtp
MAIL_HOST=xxx.xxx.xx
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=TLS
</code>```

Keep getting the same error,tho

答: this can be the case if a proxy is used on the Internet. check without using a proxy</p>

Body:
Can't send email from Laravel platform. Tried with different another emails (gmail, mailgun) and they work properly but it seems that can't make it work with the one our customer wants to use:

MAIL_DRIVER=smtp
MAIL_HOST=xxx.xxx.xx
MAIL_PORT=25
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

We got this error:

Swift_TransportException: Connection could not be established with
  host [php_network_getaddresses: getaddrinfo failed: Name or service
  not known #0] in
  .../vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php:269

I can connect with telnet from the server so it apparently everything's ok. But I find very weird this configuration. Do I need to check something else in Laravel to make it work?

EDIT 1:

Tried with this configuration too:

MAIL_DRIVER=smtp
MAIL_HOST=xxx.xxx.xx
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=TLS

Keep getting the same error,tho


问:
Do Timers run on their Own threads in Node.js?
I am a bit confused here I know Javascript is a single-threaded language but while reading about the event loop. I got to know that in case of setTimeout or setInterval javascript calls web API provided by the browser which spawns a new thread to execute timer on that thread. but what happens in the case of node.js environment with timers how do they execute/work?</p>

答:
No. Timers are just scheduled on the same thread and will call their callbacks when the time expires.

Depending on what OS your are on and what javascript interpreters you use they will use various APIs form poll to epoll to kqueue to overlapped I/O on Windows but in general asynchronous APIs have similar features. So let's ignore platform differences and look at a cross-platform API that exists on all OSes: the POSIX select() system call.

The select function in C looks something like this:

```<code>int select(int nfds, fd_set *readfds, fd_set *writefds,
              fd_set *exceptfds, struct timeval *timeout);
</code>```

Where nfds is total number of file descriptors (including network sockets) you are waiting/listening on, readfds is the list/set of read file descriptors you are waiting on, writefds is the list/set of write file descriptors, exceptfds is the list/set of error file descriptors (think stderr) and timeval is the timeout for the function.

This system call blocks - yes, in non-blocking, asynchronous code there is a piece of blocking system call. The main difference between non-blocking code and blocking threaded code is that the entire program blocks in only one place, the select() function (or whatever equivalent you use).

This function only returns if any of the file descriptors have activity on them or if the timeout expires.

By managing the timeout and calculating the next value of timeval you can implement a function like setTimeout

I've written much deeper explanations of how this works in answers to the following related questions:

I know that callback function runs asynchronously, but why?

Event Queuing in NodeJS

how node.js server is better than thread based server

Node js architecture and performance

Performance of NodeJS with large amount of callbacks

Does javascript process using an elastic racetrack algorithm

Is there any other way to implement a "listening" function without an infinite while loop?

I recommend you at least browse each of the answers I wrote above because they are almost all non-duplicates. They sometimes overlap but explain different aspects of asynchronous code execution.

The gist of it is that javascript does not execute code in parallel to implement timers. It doesn't need to. Instead it waits in parallel. Once you understand the difference between running code in parallel and waiting (doing nothing) in parallel you will understand how things like node.js achieve high performance and how events work better.

Body:
No. Timers are just scheduled on the same thread and will call their callbacks when the time expires.

Depending on what OS your are on and what javascript interpreters you use they will use various APIs form poll to epoll to kqueue to overlapped I/O on Windows but in general asynchronous APIs have similar features. So let's ignore platform differences and look at a cross-platform API that exists on all OSes: the POSIX select() system call.

The select function in C looks something like this:

int select(int nfds, fd_set *readfds, fd_set *writefds,
              fd_set *exceptfds, struct timeval *timeout);

Where nfds is total number of file descriptors (including network sockets) you are waiting/listening on, readfds is the list/set of read file descriptors you are waiting on, writefds is the list/set of write file descriptors, exceptfds is the list/set of error file descriptors (think stderr) and timeval is the timeout for the function.

This system call blocks - yes, in non-blocking, asynchronous code there is a piece of blocking system call. The main difference between non-blocking code and blocking threaded code is that the entire program blocks in only one place, the select() function (or whatever equivalent you use).

This function only returns if any of the file descriptors have activity on them or if the timeout expires.

By managing the timeout and calculating the next value of timeval you can implement a function like setTimeout

I've written much deeper explanations of how this works in answers to the following related questions:

I know that callback function runs asynchronously, but why?

Event Queuing in NodeJS

how node.js server is better than thread based server

Node js architecture and performance

Performance of NodeJS with large amount of callbacks

Does javascript process using an elastic racetrack algorithm

Is there any other way to implement a "listening" function without an infinite while loop?

I recommend you at least browse each of the answers I wrote above because they are almost all non-duplicates. They sometimes overlap but explain different aspects of asynchronous code execution.

The gist of it is that javascript does not execute code in parallel to implement timers. It doesn't need to. Instead it waits in parallel. Once you understand the difference between running code in parallel and waiting (doing nothing) in parallel you will understand how things like node.js achieve high performance and how events work better.


问:
Load separate .env from package.json
```<code>"start:dev": "set NODE_ENV=development&&nodemon ./bin/www",
"start:test": "set NODE_ENV=testing&&nodemon ./bin/www",
</code>```

I have two separate .env files dev.env and test.env
I want to load dev.env on npm run start:dev and load test.env on npm run start:test

I have searched every where on the Internet, but no help.

Any help is appreciated.

答:
The dotenv NPM package loads a file called .env by default, but this behaviour can be overriden. So you can do something like:

```<code>const { config } = require('dotenv')
if (process.env.NODE_ENV === 'development') {
    config({ path: '/full/path/to/your/dev.env' })
} else if (process.env.NODE_ENV === 'testing') {
    config({ path: '/full/path/to/your/test.env' })
}
</code>```

Title: Load separate .env from package.json

Body:
"start:dev": "set NODE_ENV=development&&nodemon ./bin/www",
"start:test": "set NODE_ENV=testing&&nodemon ./bin/www",

I have two separate .env files dev.env and test.env
I want to load dev.env on npm run start:dev and load test.env on npm run start:test

I have searched every where on the Internet, but no help.

Any help is appreciated.

Body:
The dotenv NPM package loads a file called .env by default, but this behaviour can be overriden. So you can do something like:

const { config } = require('dotenv')
if (process.env.NODE_ENV === 'development') {
    config({ path: '/full/path/to/your/dev.env' })
} else if (process.env.NODE_ENV === 'testing') {
    config({ path: '/full/path/to/your/test.env' })
}


问:
apply function and top_n doesn't work well together
I have a simple dataframe df in R:

```<code>year, var1, var2, var3
1990, 23, 1, 133
1991, 25, 3, 120
1992, 28, 2, 110
...
</code>```

The data goes on for hundreds of rows.

I want to select top 10 values for var1, var2, var3 using apply() and top_n() in R, like this:

```<code>df %>%
 select(var1, var2, var3) %>%
 apply(2, top_n(10), na.rm = TRUE)
</code>```

But I get the error:
Error in UseMethod("tbl_vars"): no applicable method for "tbl_vars" applied to an object of class "c('double', 'numeric')"

I thought that apply could help me avoid using a for loop to get the top 10 values variable by variable but I wasn't able to do so.

It seems a simple problem, but I haven't found good answers online. Any thoughts?

答:
Usually, it is better to have data in long format which makes it very easy to do such operations.

You can use pivot_longer to get data in long format then for every column you can select top 10 values based on the value in the column.

```<code>library(dplyr)
df %>% tidyr::pivot_longer(cols = -year) %>% group_by(name) %>%  top_n(10, value)
</code>```

Body:
I have a simple dataframe df in R:

year, var1, var2, var3
1990, 23, 1, 133
1991, 25, 3, 120
1992, 28, 2, 110
...

The data goes on for hundreds of rows.

I want to select top 10 values for var1, var2, var3 using apply() and top_n() in R, like this:

df %>%
 select(var1, var2, var3) %>%
 apply(2, top_n(10), na.rm = TRUE)

But I get the error:
Error in UseMethod("tbl_vars"): no applicable method for "tbl_vars" applied to an object of class "c('double', 'numeric')"

I thought that apply could help me avoid using a for loop to get the top 10 values variable by variable but I wasn't able to do so.

It seems a simple problem, but I haven't found good answers online. Any thoughts?

Body:
Usually, it is better to have data in long format which makes it very easy to do such operations.

You can use pivot_longer to get data in long format then for every column you can select top 10 values based on the value in the column.

library(dplyr)
df %>% tidyr::pivot_longer(cols = -year) %>% group_by(name) %>%  top_n(10, value)


问:
Grade Viewing of Student in php
Hello, I am new in php
I am making an Web Based Online Grading System, my problem is I want to view my grade as a Student
When i logged in as a Student it displays all the data from the grades that i uploaded.

```<code>                      <?php
                      $con = mysqli_connect('localhost','root','','grade') or die(mysqli_error());
                      $query = "Select * from grades where sID <= ID";
                      $result = mysqli_query($con,$query);
                          while ($row = mysqli_fetch_assoc($result)) {
                            $studentid = $row['StudentID'];
                             $firstname = $row['StudentName'];
                             $subject = $row['Subject'];
                             $desc = $row['Description'];
                              $first = $row['Prelim'];
                              $second = $row['Midterm'];
                             $third = $row['PreFinal'];
                             $fourth = $row['Final'];
                             $final = $row['Equi'];
                             $remark = $row['Remarks'];
                    ?>
                      <td> <?php echo $subject ?> </td>
                      <td> <?php echo $desc ?> </td>

                      <td> <?php echo $first ?> </td>
                      <td> <?php echo $second ?> </td>
                      <td> <?php echo $third ?> </td>
                      <td> <?php echo $fourth ?> </td>
                      <td> <?php echo $final ?> </td>
                      <td> <?php echo $remark ?> </td>
                    </tr>
                      <?php } ?>
</code>```

答:
You  will want to change your query to use WHERE in relation to StudentID (ore perhaps sID?? not sure based on your query statement):

```<code>"SELECT * FROM `grades` where `StudentID` = ?"
</code>```

? being the ID value which may need to be bound, if it's numeric and you check that it is before using it in the query may not need binding but binding parameters is safer.

Presumably, you have stored the StudentID in a session or cookie after the user logs in, so that is where you would draw that value from.

Title: Grade Viewing of Student in php

Body:
Hello, I am new in php
I am making an Web Based Online Grading System, my problem is I want to view my grade as a Student
When i logged in as a Student it displays all the data from the grades that i uploaded.

                      <?php
                      $con = mysqli_connect('localhost','root','','grade') or die(mysqli_error());
                      $query = "Select * from grades where sID <= ID";
                      $result = mysqli_query($con,$query);
                          while ($row = mysqli_fetch_assoc($result)) {
                            $studentid = $row['StudentID'];
                             $firstname = $row['StudentName'];
                             $subject = $row['Subject'];
                             $desc = $row['Description'];
                              $first = $row['Prelim'];
                              $second = $row['Midterm'];
                             $third = $row['PreFinal'];
                             $fourth = $row['Final'];
                             $final = $row['Equi'];
                             $remark = $row['Remarks'];
                    ?>
                       <?php echo $subject ?>
                       <?php echo $desc ?>

                       <?php echo $first ?>
                       <?php echo $second ?>
                       <?php echo $third ?>
                       <?php echo $fourth ?>
                       <?php echo $final ?>
                       <?php echo $remark ?>

                      <?php } ?>

Body:
You  will want to change your query to use WHERE in relation to StudentID (ore perhaps sID?? not sure based on your query statement):

"SELECT * FROM `grades` where `StudentID` = ?"

? being the ID value which may need to be bound, if it's numeric and you check that it is before using it in the query may not need binding but binding parameters is safer.

Presumably, you have stored the StudentID in a session or cookie after the user logs in, so that is where you would draw that value from.


问:
NameError: 'discord' is not defined?
This is for a discord bot I am making, and I have tried to set the bot's status. I've found an answer that looks like await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="for e/info")) and I have put it in an on_ready event function. However, it gives me the following exception:

```<code>Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py",
    line 312, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\user\OneDrive\Desktop\EffeKtive\bot.py", line 14, in on_ready
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="for
      e/info"))
NameError: name 'discord' is not defined
</code>```

I feel that I am missing an import.

答:
You may have installed discord.py in a seperate location, try installing it to C:\Windows\system32>. You also may be missing an import.
If you are trying to add commands, you also have to: from discord.ext import commands.
Is it possible for you to post your code?

Title: NameError: 'discord' is not defined?

Body:
This is for a discord bot I am making, and I have tried to set the bot's status. I've found an answer that looks like await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="for e/info")) and I have put it in an on_ready event function. However, it gives me the following exception:

Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py",
    line 312, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\user\OneDrive\Desktop\EffeKtive\bot.py", line 14, in on_ready
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="for
      e/info"))
NameError: name 'discord' is not defined

I feel that I am missing an import.


问:
Celery worker takes tasks fairly
I'm working on celery worker. And I have some questions.

I use 4 celery workers with concurrency 3. They are working for same job. They are looking at same queue.
when I make task, I make 4 tasks at once. but each tasks takes different time.
It is like this:

```<code>task_list = [task1,task2,task3,task4]
# task1 : takes 10s
# task2 : takes 30s
# task3 : takes 50s
# task4 : takes 70s

for task in task_list:
    result = current_app.send_task("task_queue",(task),)

</code>```

It is sent to same queue which workers are looking at.
when I creates multiple sets of tasks, I expected this:

```<code>Worker1: task1, task4,....
Worker2: task2, task3,...
Worker3: task3, task2,...
Worker4: task4, task1,...
</code>```

So that each workers works fairly enough
But What I actually experiencing is:

```<code>Worker1: task1, task1, task1,....
Worker2: task2, task2, task2,...
Worker3: task3, task3, task3,...
Worker4: task4, task4, task4,...
</code>```

Because of this situation, when some workers work hard, the other workers do nothing.
I tried to add priority to tasks, and use additional options for celery worker, but it didn't help.

here is command lines when i activate celery worker.

```<code>celery -A django-project worker -n worker01 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 --concurrency=3
celery -A django-project worker -n worker02 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 --concurrency=3
celery -A django-project worker -n worker03 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 --concurrency=3
celery -A django-project worker -n worker04 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 --concurrency=3
</code>```

is there any situation like this or is there any solution for this case?

答:
At this moment, all I can do is just shuffle sequence of tasks to that same number of task can go different number of workers

```<code>import random

...
task_list = [task1,task2,task3,task4]

random.shuffle(task_list)

for task in task_list:
    result = current_app.send_task("task_queue",(task),)
</code>```

I hope I can find another way to send tasks fairly to workers

Title: Celery worker takes tasks fairly

Body:
I'm working on celery worker. And I have some questions.

I use 4 celery workers with concurrency 3. They are working for same job. They are looking at same queue.
when I make task, I make 4 tasks at once. but each tasks takes different time.
It is like this:

task_list = [task1,task2,task3,task4]
# task1 : takes 10s
# task2 : takes 30s
# task3 : takes 50s
# task4 : takes 70s

for task in task_list:
    result = current_app.send_task("task_queue",(task),)

It is sent to same queue which workers are looking at.
when I creates multiple sets of tasks, I expected this:

Worker1: task1, task4,....
Worker2: task2, task3,...
Worker3: task3, task2,...
Worker4: task4, task1,...

So that each workers works fairly enough
But What I actually experiencing is:

Worker1: task1, task1, task1,....
Worker2: task2, task2, task2,...
Worker3: task3, task3, task3,...
Worker4: task4, task4, task4,...

Because of this situation, when some workers work hard, the other workers do nothing.
I tried to add priority to tasks, and use additional options for celery worker, but it didn't help.

here is command lines when i activate celery worker.

celery -A django-project worker -n worker01 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 --concurrency=3
celery -A django-project worker -n worker02 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 --concurrency=3
celery -A django-project worker -n worker03 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 --concurrency=3
celery -A django-project worker -n worker04 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 --concurrency=3

is there any situation like this or is there any solution for this case?

Body:
At this moment, all I can do is just shuffle sequence of tasks to that same number of task can go different number of workers

import random

...
task_list = [task1,task2,task3,task4]

random.shuffle(task_list)

for task in task_list:
    result = current_app.send_task("task_queue",(task),)

I hope I can find another way to send tasks fairly to workers


问:
*ngIf Assigned via string variable
I have an Angular (Angular 9) parent component that holds a form.  I want to abstract and generalize display of validation errors, so I have created a child component to handle validation error display.  Specifically, I'm trying to assign a string to an ngIf to display an error message if one exists dynamically.  Here is my template:

```<code>  <div class="alert">
    <div *ngFor="let i of InnerDisplayData">
      <div *ngIf="'i[0]'">
        {{ i[1] }} <br />
        {{ i[0] }}
      </div>
    </div>
  </div>
</code>```

Here is an excerpt from my component file:

```<code>this.InnerDisplayData = Array.from(this.valMap, ([x, y]) => [
      "(fg | async).controls['" + this.field + "'].errors." + x,
      y,
    ]);

    const sub: Subscription = this.fg.subscribe((x) => {
      console.log(JSON.stringify(x.controls["FirstName"].errors));
    });
</code>```

Where fg is @Input() fg: Observable<FormGroup>

fg is triggering correctly, and the 'required' validator is popping true when it should for the control.  My template shows that the string being generated (i[0]) for the innerDataDisplay is this:

(fg | async).controls['FirstName'].errors.required

However, it appears that the ngIf is triggering because it is looking at a truthy string, rather than evaluating the string.  Therefore, it is not reacting based on the conditions in the FormGroup and always displays the content.  What am I doing wrong?  Thanks!

答:
Angular doesn't really intend to be used the way you are trying to use it. It can certainly get you to where you want to go, but you don't need to dynamically generate strings as code at runtime inside template code. Maybe you can use eval() to do it this way but many would consider that a bad idea, and also unnecessary since you are using Angular.

It looks like what you have is a component that can take a FormGroup and control name and display all the validation errors for that control? If the validation messages are generic enough you can create a component that takes the FormControl as an input and the template can show the standard messages.

```<code>@Component({
  selector: 'app-error-messages',
  templateUrl: './error-messages.component.html',
  styleUrls: ['./error-messages.component.css']
})
export class ErrorMessagesComponent {
  @Input() control: FormControl;
}
</code>```

  Required.

  Must be greater than {{ control.errors.min.min }}.

  Must be less than {{ control.errors.max.max }}.

```

<p>From the code you posted I wasn't sure if you instead were looking for a component that didn't require using <code>*ngIf</code> on each possible validation type. You could also create an array of errors on the component and the use *ngFor over the array to display the message.</p>

<pre class="lang-js prettyprint-override"><code>this.errors = Object.keys(this.control.errors || {})
  .map(key => ({
     name: key, // the Validation, e.g. "required", "minLength", "max", etc.
     value: this.control.errors[key] // the error object in case you need it later
  }));
</code>```

I set up this stackblitz with an example of either component with a small form.

Title: *ngIf Assigned via string variable

Body:
I have an Angular (Angular 9) parent component that holds a form.  I want to abstract and generalize display of validation errors, so I have created a child component to handle validation error display.  Specifically, I'm trying to assign a string to an ngIf to display an error message if one exists dynamically.  Here is my template:

        {{ i[1] }}

        {{ i[0] }}

Here is an excerpt from my component file:

this.InnerDisplayData = Array.from(this.valMap, ([x, y]) => [
      "(fg | async).controls['" + this.field + "'].errors." + x,
      y,
    ]);

    const sub: Subscription = this.fg.subscribe((x) => {
      console.log(JSON.stringify(x.controls["FirstName"].errors));
    });

Where fg is @Input() fg: Observable<FormGroup>

fg is triggering correctly, and the 'required' validator is popping true when it should for the control.  My template shows that the string being generated (i[0]) for the innerDataDisplay is this:

(fg | async).controls['FirstName'].errors.required

However, it appears that the ngIf is triggering because it is looking at a truthy string, rather than evaluating the string.  Therefore, it is not reacting based on the conditions in the FormGroup and always displays the content.  What am I doing wrong?  Thanks!

Body:
Angular doesn't really intend to be used the way you are trying to use it. It can certainly get you to where you want to go, but you don't need to dynamically generate strings as code at runtime inside template code. Maybe you can use eval() to do it this way but many would consider that a bad idea, and also unnecessary since you are using Angular.

It looks like what you have is a component that can take a FormGroup and control name and display all the validation errors for that control? If the validation messages are generic enough you can create a component that takes the FormControl as an input and the template can show the standard messages.

@Component({
  selector: 'app-error-messages',
  templateUrl: './error-messages.component.html',
  styleUrls: ['./error-messages.component.css']
})
export class ErrorMessagesComponent {
  @Input() control: FormControl;
}

<div *ngIf="control.errors.required">
  Required.
</div>
<div *ngIf="control.errors.min">
  Must be greater than {{ control.errors.min.min }}.
</div>
<div *ngIf="control.errors.max">
  Must be less than {{ control.errors.max.max }}.
</div>
<!-- more error messages... -->

From the code you posted I wasn't sure if you instead were looking for a component that didn't require using *ngIf on each possible validation type. You could also create an array of errors on the component and the use *ngFor over the array to display the message.

this.errors = Object.keys(this.control.errors || {})
  .map(key => ({
     name: key, // the Validation, e.g. "required", "minLength", "max", etc.
     value: this.control.errors[key] // the error object in case you need it later
  }));

I set up this stackblitz with an example of either component with a small form.


问:
How to convert TEXT column into an indexable field?
In order to optimize an app's performance, I'm trying to index fields which are frequently used in WHERE queries.
The database is mariadb 10.3.

One of those big culprits is a msg column which is of type TEXT so it can not be indexed:

```<code>ERROR 1170 (42000): BLOB/TEXT column 'msg' used in key specification without a key length
</code>```

While the largest value is below, I don't mind if I need to truncate content of some of the msg rows to something like 2000 characters, if needed.

```<code>SELECT MAX(LENGTH(msg)) FROM msgs;
+------------------+
| MAX(LENGTH(msg)) |
+------------------+
|             2729 |
+------------------+
1 row in set (0.030 sec)
</code>```

Well when I truncated large fields, and converted the field to VARCHAR(2000) and then tried to index it again, I get:

```<code>ERROR 1071 (42000): Specified key was too long; max key length is 3072 bytes.
</code>```

Also, I can not make any changes to the app's codebase.

So I'm wondering what is the best way to achieve this?

答:
VARCHAR(2000) can hold 2000 characters.

A component of an index is limited to 3072 bytes.

What is the CHARACTER SET for msg?  Provide SHOW CREATE TABLE msgs

CHARACTER SET utf8 treats a character as (up to) 3 bytes for the above computation.

utf8mb4 - 4 bytes.

But...  Why would you want to index a really long string?  Are you going to say things like

```<code>SELECT * FROM msgs WHERE msg = 'This is a very long message to make a point; blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah';
</code>```

If you are going to use FULLTEXT, it does not have that limitation.

If you will use LIKE or REGEXP, OK.

Body:
In order to optimize an app's performance, I'm trying to index fields which are frequently used in WHERE queries.
The database is mariadb 10.3.

One of those big culprits is a msg column which is of type TEXT so it can not be indexed:

ERROR 1170 (42000): BLOB/TEXT column 'msg' used in key specification without a key length

While the largest value is below, I don't mind if I need to truncate content of some of the msg rows to something like 2000 characters, if needed.

SELECT MAX(LENGTH(msg)) FROM msgs;
+------------------+
| MAX(LENGTH(msg)) |
+------------------+
|             2729 |
+------------------+
1 row in set (0.030 sec)

Well when I truncated large fields, and converted the field to VARCHAR(2000) and then tried to index it again, I get:

ERROR 1071 (42000): Specified key was too long; max key length is 3072 bytes.

Also, I can not make any changes to the app's codebase.

So I'm wondering what is the best way to achieve this?

Body:
VARCHAR(2000) can hold 2000 characters.

A component of an index is limited to 3072 bytes.

What is the CHARACTER SET for msg?  Provide SHOW CREATE TABLE msgs

CHARACTER SET utf8 treats a character as (up to) 3 bytes for the above computation.

utf8mb4 - 4 bytes.

But...  Why would you want to index a really long string?  Are you going to say things like

SELECT * FROM msgs WHERE msg = 'This is a very long message to make a point; blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah';

If you are going to use FULLTEXT, it does not have that limitation.

If you will use LIKE or REGEXP, OK.


问:
Files opened in subprocess shell
At the end of the execution of the following script, I receive some errors like these:

```<code>filename.enc: No such file or directory
140347508795048:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('filename.enc','r')
140347508795048:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:
</code>```

It seems like Popen is trying to close the file at the end of execution, although it was removed.

```<code>#!/usr/bin/python
import subprocess, os

infile = "filename.enc"
outfile = "filename.dec"
opensslCmd = "openssl enc -a -d -aes-256-cbc -in %s -out %s" % (infile, outfile)
subprocess.Popen(opensslCmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
os.remove(infile)
</code>```

How can I close the file properly?

Thanks.

答:
You could try running the subprocess.Popen in a thread, and just deleting the file after the subprocess call returned.

see: Python subprocess: callback when cmd exits

Title: Files opened in subprocess shell

Body:
At the end of the execution of the following script, I receive some errors like these:

filename.enc: No such file or directory
140347508795048:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('filename.enc','r')
140347508795048:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:

It seems like Popen is trying to close the file at the end of execution, although it was removed.

#!/usr/bin/python
import subprocess, os

infile = "filename.enc"
outfile = "filename.dec"
opensslCmd = "openssl enc -a -d -aes-256-cbc -in %s -out %s" % (infile, outfile)
subprocess.Popen(opensslCmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
os.remove(infile)

How can I close the file properly?

Thanks.


问:
Google cloud functions not accessible from app engine (with ingress controls)
I have an API that I host through Google Cloud. The main entry point for the API is an App Engine instance (standard), which then needs to be able to call various cloud functions to execute its tasks.

To make the cloud functions secure, I want to set the ingress controls to "Allow internal only".

I've deployed the cloud functions and the App Engine in the same region (us-central1), but every time the App Engine instance tries to call a cloud function, it gets a 403 error. I've tried setting up a VPC connector for the App Engine, but that isn't helping.

Here's the app.yaml file:

```<code>service: my-test-app

runtime: nodejs10

env_variables:
    STAGE: "dev"

instance_class: F1

vpc_access_connector:
    name: "projects/my-test-project/locations/us-central1/connectors/test-vpc-connector"
</code>```

The key cloud function configuration is the Ingress Setting. I have it set to Allow internal traffic only. If I set it to Allow all traffic, everything works (just highly insecure!)

Any suggestions on what I might be missing?

答: I found the solution! If I set the App Engine to a flex environment, everything works. It looks like the standard environment was the issue.</p>

Body:
I have an API that I host through Google Cloud. The main entry point for the API is an App Engine instance (standard), which then needs to be able to call various cloud functions to execute its tasks.

To make the cloud functions secure, I want to set the ingress controls to "Allow internal only".

I've deployed the cloud functions and the App Engine in the same region (us-central1), but every time the App Engine instance tries to call a cloud function, it gets a 403 error. I've tried setting up a VPC connector for the App Engine, but that isn't helping.

Here's the app.yaml file:

service: my-test-app

runtime: nodejs10

env_variables:
    STAGE: "dev"

instance_class: F1

vpc_access_connector:
    name: "projects/my-test-project/locations/us-central1/connectors/test-vpc-connector"

The key cloud function configuration is the Ingress Setting. I have it set to Allow internal traffic only. If I set it to Allow all traffic, everything works (just highly insecure!)

Any suggestions on what I might be missing?


问:
Promise in Angular 9
I'm trying to write a synchronous function call in Angular using a Promise, but it still gets a different result than expected.
I have 2 functions that use the service that download data from the API:

```<code>getData1(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(1);
    },
    error => this.error = error
  );
}

getData2(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(2);
    },
    error => this.error = error
  );
}
</code>```

I'm trying to make the next function call after the response is completed. So:

```<code>data(shortcuts) {
  this.getData1(shortcuts[0]);
  this.getData2(shortcuts[1]);
}

ngOnInit() {
  const myPromise = new Promise((resolve) => {
    this.data(this.shortcuts);
    resolve(3)
  });
  myPromise.then((value) => {console.log(value)});
}

</code>```

But my browser prints this call order:

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

What am I doing wrong?

I also tried to use callbacks but the effect is always the same.

答:
If you want to use promises you can use async/await but instead you can use rxjs for doing this.

Observable flow

I create two functions to simulate your problem, one is called getDataAsObservable which represents your getData method, and another one called getDataAsPromise which represents your promise, then I use the concat that is an observable creation method from rxjs which sequentially emits all values from given Observable and then moves on to the next.

I pass first$, second$, and third$ asynchronous functions to concat and to subscribe in order to print the result out.

Promise flow

Otherwise, if you use async/await, you only need to wait for the response.

  import { Observable, concat } from 'rxjs';
  import { delay } from 'rxjs/operators';

  async ngOnInit() {
    // first execute promise flow and wait for the response
    await this.executePromiseFlow();
    // after promise flow we can execute observable flow
    this.executeObservableFlow();
  }

  executePromiseFlow = async () => {
    // I use toPromise method to convert observable to a promise
    const first = await this.getDataAsObservable(1).toPromise();
    console.info('[Promise] output', first);
    const second = await this.getDataAsObservable(2).toPromise();
    console.info('[Promise] output', second);
    const third = await this.getDataAsPromise(3);
    console.info('[Promise] output', third);
  }

  executeObservableFlow = () => {
    const second$ = this.getDataAsObservable(2);
    const first$ = this.getDataAsObservable(1);
    const third$ = this.getDataAsPromise(3);

    concat(first$, second$, third$)
      .subscribe((output) => console.info('[Observable] output', output))
  }

  getDataAsObservable = (value: number) => {
    return new Observable((observer) => {
      observer.next(value);
      observer.complete();
    }).pipe(
      delay(value * 2000), // simulate HTTP request time
    );
  }

  getDataAsPromise = (value: number) => {
    return Promise.resolve(value);
  }

```

You can read more about async/await here and rxjs here.

You can check a simple reproduction of this here on Stackblitz

Title: Promise in Angular 9

Body:
I'm trying to write a synchronous function call in Angular using a Promise, but it still gets a different result than expected.
I have 2 functions that use the service that download data from the API:

getData1(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(1);
    },
    error => this.error = error
  );
}

getData2(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(2);
    },
    error => this.error = error
  );
}

I'm trying to make the next function call after the response is completed. So:

data(shortcuts) {
  this.getData1(shortcuts[0]);
  this.getData2(shortcuts[1]);
}

ngOnInit() {
  const myPromise = new Promise((resolve) => {
    this.data(this.shortcuts);
    resolve(3)
  });
  myPromise.then((value) => {console.log(value)});
}

But my browser prints this call order:

3
1
2

What am I doing wrong?

I also tried to use callbacks but the effect is always the same.

Body:
If you want to use promises you can use async/await but instead you can use rxjs for doing this.

Observable flow

I create two functions to simulate your problem, one is called getDataAsObservable which represents your getData method, and another one called getDataAsPromise which represents your promise, then I use the concat that is an observable creation method from rxjs which sequentially emits all values from given Observable and then moves on to the next.

I pass first$, second$, and third$ asynchronous functions to concat and to subscribe in order to print the result out.

Promise flow

Otherwise, if you use async/await, you only need to wait for the response.

  import { Observable, concat } from 'rxjs';
  import { delay } from 'rxjs/operators';

  async ngOnInit() {
    // first execute promise flow and wait for the response
    await this.executePromiseFlow();
    // after promise flow we can execute observable flow
    this.executeObservableFlow();
  }

  executePromiseFlow = async () => {
    // I use toPromise method to convert observable to a promise
    const first = await this.getDataAsObservable(1).toPromise();
    console.info('[Promise] output', first);
    const second = await this.getDataAsObservable(2).toPromise();
    console.info('[Promise] output', second);
    const third = await this.getDataAsPromise(3);
    console.info('[Promise] output', third);
  }

  executeObservableFlow = () => {
    const second$ = this.getDataAsObservable(2);
    const first$ = this.getDataAsObservable(1);
    const third$ = this.getDataAsPromise(3);

    concat(first$, second$, third$)
      .subscribe((output) => console.info('[Observable] output', output))
  }

  getDataAsObservable = (value: number) => {
    return new Observable((observer) => {
      observer.next(value);
      observer.complete();
    }).pipe(
      delay(value * 2000), // simulate HTTP request time
    );
  }

  getDataAsPromise = (value: number) => {
    return Promise.resolve(value);
  }

You can read more about async/await here and rxjs here.

You can check a simple reproduction of this here on Stackblitz


问:
Running multiple containers on the same Service Fabric node
I have a windows Service Fabric node with 4 cores and I want to host 3 containerized stateless services on it, where each windows container is allocated 1 core to read a message from a queue and process it. I run some experiments and got these results:

1 container running on the node: message takes ~18 sec to be
processed, avg cpu usage per container: 24.7%, memory usage: 1 GB

2 containers running on the node: message takes ~25 sec to be
processed, avg cpu usage per container: 24.4%, memory usage: 1 GB

3 containers running on the node: message takes ~35 sec to be
processed, avg cpu usage per container: 24.6%, memory usage: 1 GB

I thought that containers are supposedly isolated, and I expected the processing time to be constant at ~18s regardless of the number of containers, but in this case, it seems that adding one container affects the processing time in other containers. Each container is set to use 1 core, so they shouldn't be overstepping to use each other's resources, and cpu is not reaching full utilization. Even if cpu was a bottleneck here, I'd expect that at least 2 containers would be able to run with ~18 sec processing time.

Is there a logical explanation for the results? Isn't it not possible to run multiple containers on the same Service Fabric host without affecting the performance of each when there are enough compute resources? How big could the Service Fabric overhead possibly be when trying to run multiple containers on the same node?

Thanks!

答:
Your container is not only using CPU, but also memory and I/O (disk, network), which can also become bottlenecks.

To see the overhead of SF, run the containers outside of SF and see if it makes a difference.

Use a machine with more memory, and after that, try using an SSD drive. See if that increases performance.

To avoid process overhead, consider using a single container and have multiple threads do parallel message processing. Make sure to assign it 3 cores.


问:
Where can I learn the basics of writing a lexer?
I want to learn how to write a lexer. My university course had an assignment where we had to write a parser (and a lexer to go along with it) but this was given to us with no instruction or feedback (beyond the mark) so I didn't really learn much from it.

After searching for this topic, I can only find fairly advanced write ups which focus on areas which I feel are a few steps ahead of where I am at. I want a discussion on the basics of writing a lexer for a very simple language which I can use as a basis for investigating tokenising more complex languages.

At this stage I'm not really interested in best practices or optimisation techniques but instead prefer a focus on the essentials. What are some good resources to get me started?

答: The Dragon Book is probably the definitive guide on the subject, although it can be a bit overwhelming. Language Implementation Patterns and Programming Language Pragmatics are great resources as well.</p>


问:
Android crop coordinates
I want to crop an image from gallery or camera and also get the crop coordinates X and Y for original image, not the cropped one.

I require these coordinates in order to use them in a POST request, where I send the original image and the coordinates of the crop.

How do I do this?

答:
```<code>  File tempDir = Environment.getExternalStorageDirectory();
                    tempDir = new File(tempDir.getAbsolutePath() + "/.temp/");
                    tempDir.mkdir();
                    File tempFile = null;
                    try {
                        tempFile = File.createTempFile("Trendii", ".png", tempDir);

                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                        byte[] bitmapData = bytes.toByteArray();

                        //write the bytes in file
                        FileOutputStream fos = new FileOutputStream(tempFile);
                        fos.write(bitmapData);
                        fos.flush();
                        fos.close();

                        float height = 0, width = 0;

                        if (bitmap != null) {
                            height = bitmap.getHeight();
                            width = bitmap.getWidth();
                        }

                        Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
                        Crop.of(Uri.fromFile(tempFile), destination, inspirationId, height, width).asSquare().start(InspirationDetailsActivity.this);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onPermissionDenied(PermissionDeniedResponse response) {
                    showSettingsDialog();
                }

                @Override
                public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
        } else {

            File tempDir = Environment.getExternalStorageDirectory();
            tempDir = new File(tempDir.getAbsolutePath() + "/.temp/");
            tempDir.mkdir();
            File tempFile = null;
            try {
                tempFile = File.createTempFile("Trendii", ".png", tempDir);

                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                byte[] bitmapData = bytes.toByteArray();

                //write the bytes in file
                FileOutputStream fos = new FileOutputStream(tempFile);
                fos.write(bitmapData);
                fos.flush();
                fos.close();

                float height = 0, width = 0;

                if (bitmap != null) {
                    height = bitmap.getHeight();
                    width = bitmap.getWidth();
                }

                Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
                Crop.of(Uri.fromFile(tempFile), destination, inspirationId, height, width).asSquare().start(this);

            } catch (IOException e) {
                e.printStackTrace();
            }
</code>```

Title: Android crop coordinates


答:
I believe this answer has a solution for you: </p>

```<code>scripts: {
  "set-env:production": "export $(cat .production.env | grep \"^[^#;]\" |xargs)",
  "set-env:development": "export $(cat .env | grep \"^[^#;]\" |xargs)",
}
</code>```

Title: Load separate .env from package.json

Body:
"start:dev": "set NODE_ENV=development&&nodemon ./bin/www",
"start:test": "set NODE_ENV=testing&&nodemon ./bin/www",

I have two separate .env files dev.env and test.env
I want to load dev.env on npm run start:dev and load test.env on npm run start:test

I have searched every where on the Internet, but no help.

Any help is appreciated.

Body:
I believe this answer has a solution for you:

scripts: {
  "set-env:production": "export $(cat .production.env | grep \"^[^#;]\" |xargs)",
  "set-env:development": "export $(cat .env | grep \"^[^#;]\" |xargs)",
}


问:
Can I tell Selenium to record in DOM mode instead of element ID mode?
I have been using Selenium in my DEV environment.  When I go to try some of my recorded tests on my Test environment, I find that the elements have different IDs (they are generated by the web framework).  I can change the test manually to use

```<code>document.forms[2].elements[3]
</code>```

instead of by id, which looks like this:

```<code>ellaMform:j_id77
</code>```

I'm looking for a way to tell selenium to record the dom:index value for the controls so that tests will be the same between DEV and TEST.

Similar question on SO points to a plugin but is not exactly what I need:
Make Selenium record IDs, not paths

答: IDE already has locator builders for several DOM styles (e.g., dom:index, which matches your model, or dom:name, which is less position-oriented).  By default, they are prioritized lower than ID locators, but you can choose which locator you want to use when you record the test.

Body:
I have been using Selenium in my DEV environment.  When I go to try some of my recorded tests on my Test environment, I find that the elements have different IDs (they are generated by the web framework).  I can change the test manually to use

document.forms[2].elements[3]

instead of by id, which looks like this:

ellaMform:j_id77

I'm looking for a way to tell selenium to record the dom:index value for the controls so that tests will be the same between DEV and TEST.

Similar question on SO points to a plugin but is not exactly what I need:
Make Selenium record IDs, not paths


问:
Pandas splitting Columns and creating Columns of tuples
I have a dataframe which looks as follows:

```<code># df

colA     colB          colC

rqp      129            a
pot      217;345        u
ghay     716            b
rbba     217;345        d
tary     612;811;760    a
kals     716            t
</code>```

The ColB (any component out of two shown) & ColC combination make a unique combination.
I want to create a dataframe from this dataframe which will look like the following

```<code># newdf:

colAA      coLBB

(129,a)    (a,rqp)
(217,u)    (u,pot)
(345,u)    (u,pot)
(716,b)    (b,ghay)
(217,d)    (d,rbba)
(345,d)    (d,rbba)
(612,a)    (a,tary)
(811,a)    (a,tary)
(760,a)    (a,tary)
(716,t)    (t,kals)
</code>```

I have tried creating new columns if there is a single element in colB, but cannot get how to do using the semicolon splitter and then how to create columns of tuples.

If I do not have any semicolon in ColB, then I can use

```<code>df['AA'] = list(zip(df[colB], df[colC]))
df['AB'] = list(zip(df[colC], df[colA]))
</code>```

However the presence of semicolon in ColB I am getting issues, as how to split that string into multiple ones and assign the tuples.
Any help will be very much appreciated.

答:
You can simply use str.split() with expand parameters to split the list and get new columns based on split.

```<code>df['colB'].str.split(pat=';',expand=True)
</code>```

Read more here

Body:
I have a dataframe which looks as follows:

# df

colA     colB          colC

rqp      129            a
pot      217;345        u
ghay     716            b
rbba     217;345        d
tary     612;811;760    a
kals     716            t

The ColB (any component out of two shown) & ColC combination make a unique combination.
I want to create a dataframe from this dataframe which will look like the following

# newdf:

colAA      coLBB

(129,a)    (a,rqp)
(217,u)    (u,pot)
(345,u)    (u,pot)
(716,b)    (b,ghay)
(217,d)    (d,rbba)
(345,d)    (d,rbba)
(612,a)    (a,tary)
(811,a)    (a,tary)
(760,a)    (a,tary)
(716,t)    (t,kals)

I have tried creating new columns if there is a single element in colB, but cannot get how to do using the semicolon splitter and then how to create columns of tuples.

If I do not have any semicolon in ColB, then I can use

df['AA'] = list(zip(df[colB], df[colC]))
df['AB'] = list(zip(df[colC], df[colA]))

However the presence of semicolon in ColB I am getting issues, as how to split that string into multiple ones and assign the tuples.
Any help will be very much appreciated.

Body:
You can simply use str.split() with expand parameters to split the list and get new columns based on split.

df['colB'].str.split(pat=';',expand=True)

Read more here


问:
Jquery / JavaScript get value from a td of table which is inside a div with id

                Firstname

                Secondname

                name1

                name2

```

This is my HTML structure and I need to get the values 'Firstname' and 'name1' from the table using Jquery or Javascript. Only the outer div has the id. Can someone help.

答:
Using jQuery, it's too easy.</p>

```<code>jQuery('#myDiv table tr:first-child td:first-child').html() // 'Firstname'
jQuery('#myDiv table tr:nth-child(2) td:first-child').html() // 'name1'

jQuery('#myDiv table tr:first-child td:nth-child(2)').html() // 'Secondname'
jQuery('#myDiv table tr:nth-child(2) td:nth-child(2)').html() // 'name2'
</code>```

Body:
                Firstname

                Secondname

                name1

                name2

This is my HTML structure and I need to get the values 'Firstname' and 'name1' from the table using Jquery or Javascript. Only the outer div has the id. Can someone help.

Body:
Using jQuery, it's too easy.

jQuery('#myDiv table tr:first-child td:first-child').html() // 'Firstname'
jQuery('#myDiv table tr:nth-child(2) td:first-child').html() // 'name1'

jQuery('#myDiv table tr:first-child td:nth-child(2)').html() // 'Secondname'
jQuery('#myDiv table tr:nth-child(2) td:nth-child(2)').html() // 'name2'


问:
Loop through a table valued function
I have a table x which has columns y and z it has 10 rows of data.

I then have a table-valued function getDetails(y,z) which takes values stored in table x in columns y and z to return a table tb with three columns.

I need to write a tsql query that loops values from table x through  function getDetails(y,z)to return one row per set of values y and zfrom table x in this case table tb should have 10 rows.

This is what I have so far which returns one row only each time I run it.

```<code>DECLARE @y NVARCHAR(50);
DECLARE @z NVARCHAR(2);

SELECT @y =y FROM x

SElECT @z =z FROM x

SELECT * from getDetails(@y,@z)
</code>```

This returns

```<code>       col1      col2     col3
       ---------------------
row1   Lorem     Ipsum     Sit
</code>```

//UPDATE
If anyone has an idea how I can use temp tables to achieve this please let me know

答:
You are trying to call user defined function for every row of table x. you dont need looping, you can go for set based operations itself.

Below I am creating table user defined function, which returns a table with 3 columns.

create FUNCTION dbo.testtableresult(@a int)
returns table as
return
select @a+1 as a1, @a+2 as a2, @a+3 as a3
```

<p>I am loading two rows into table variable and then calling the user defined function for each row.</p>

<pre class="lang-sql prettyprint-override"><code>DECLARE @table table(a int)

INSERT INTO @table values(1),(2)

SELECT t.a, t1.a1, t1.a2, t1.a3
FROM @table as t
CROSS APPLY dbo.testtableresult(t.a) as t1
</code>```

```<code>+---+----+----+----+
| a | a1 | a2 | a3 |
+---+----+----+----+
| 1 |  2 |  3 |  4 |
| 2 |  3 |  4 |  5 |
+---+----+----+----+
</code>```

Title: Loop through a table valued function

Body:
I have a table x which has columns y and z it has 10 rows of data.

I then have a table-valued function getDetails(y,z) which takes values stored in table x in columns y and z to return a table tb with three columns.

I need to write a tsql query that loops values from table x through  function getDetails(y,z)to return one row per set of values y and zfrom table x in this case table tb should have 10 rows.

This is what I have so far which returns one row only each time I run it.

DECLARE @y NVARCHAR(50);
DECLARE @z NVARCHAR(2);

SELECT @y =y FROM x

SElECT @z =z FROM x

SELECT * from getDetails(@y,@z)

This returns

       col1      col2     col3
       ---------------------
row1   Lorem     Ipsum     Sit

//UPDATE
If anyone has an idea how I can use temp tables to achieve this please let me know

Body:
You are trying to call user defined function for every row of table x. you dont need looping, you can go for set based operations itself.

Below I am creating table user defined function, which returns a table with 3 columns.

create FUNCTION dbo.testtableresult(@a int)
returns table as
return
select @a+1 as a1, @a+2 as a2, @a+3 as a3

I am loading two rows into table variable and then calling the user defined function for each row.

DECLARE @table table(a int)

INSERT INTO @table values(1),(2)

SELECT t.a, t1.a1, t1.a2, t1.a3
FROM @table as t
CROSS APPLY dbo.testtableresult(t.a) as t1

+---+----+----+----+
| a | a1 | a2 | a3 |
+---+----+----+----+
| 1 |  2 |  3 |  4 |
| 2 |  3 |  4 |  5 |
+---+----+----+----+


问:
tidyr - nesting_ alternatives
I am looking for way to replace nesting_ in my code as I saw the function is marked as Deprecated lifecycle.

Here is sample code where I used nesting_ in complete to passing a vector of columns' names and generate all possible combination between column a and pairs b & c.

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

data <- tibble(a = c(1, 1, 2, 2, 3),
  b = c("P-1", "P-2", "P-3", "P-2", "P-4"),
  c = c("O-1", "O-4", "O-2", "O-3", "O-3"))

#
nesting_variables <- c("b", "c", "c")
data %>%
  complete(a, nesting_(unique(nesting_variables)))
</code>```

output

```<code># A tibble: 15 x 3
       a b     c
   <dbl> <chr> <chr>
 1     1 P-1   O-1
 2     1 P-2   O-3
 3     1 P-2   O-4
 4     1 P-3   O-2
 5     1 P-4   O-3
 6     2 P-1   O-1
 7     2 P-2   O-3
 8     2 P-2   O-4
 9     2 P-3   O-2
10     2 P-4   O-3
11     3 P-1   O-1
12     3 P-2   O-3
13     3 P-2   O-4
14     3 P-3   O-2
15     3 P-4   O-3
</code>```

答:
You can use nesting instead with syms and !!! :

```<code>library(tidyr)
library(rlang)

data %>% complete(a, nesting(!!!syms(unique(nesting_variables))))
</code>```

We can confirm that both the solutions give the same output :

```<code>identical(data %>% complete(a, nesting(!!!syms(unique(nesting_variables)))),
          data %>% complete(a, nesting_(unique(nesting_variables))))
#[1] TRUE
</code>```

Title: tidyr - nesting_ alternatives

Body:
I am looking for way to replace nesting_ in my code as I saw the function is marked as Deprecated lifecycle.

Here is sample code where I used nesting_ in complete to passing a vector of columns' names and generate all possible combination between column a and pairs b & c.

library(tidyr)
library(dplyr)

data <- tibble(a = c(1, 1, 2, 2, 3),
  b = c("P-1", "P-2", "P-3", "P-2", "P-4"),
  c = c("O-1", "O-4", "O-2", "O-3", "O-3"))

#
nesting_variables <- c("b", "c", "c")
data %>%
  complete(a, nesting_(unique(nesting_variables)))

output

# A tibble: 15 x 3
       a b     c
   <dbl> <chr> <chr>
 1     1 P-1   O-1
 2     1 P-2   O-3
 3     1 P-2   O-4
 4     1 P-3   O-2
 5     1 P-4   O-3
 6     2 P-1   O-1
 7     2 P-2   O-3
 8     2 P-2   O-4
 9     2 P-3   O-2
10     2 P-4   O-3
11     3 P-1   O-1
12     3 P-2   O-3
13     3 P-2   O-4
14     3 P-3   O-2
15     3 P-4   O-3

Body:
You can use nesting instead with syms and !!! :

library(tidyr)
library(rlang)

data %>% complete(a, nesting(!!!syms(unique(nesting_variables))))

We can confirm that both the solutions give the same output :

identical(data %>% complete(a, nesting(!!!syms(unique(nesting_variables)))),
          data %>% complete(a, nesting_(unique(nesting_variables))))
#[1] TRUE