问:
Switch from PHP to Java or .Net
I currently run a website on LAMP, I am currently in the process of refactoring my code from normal php to Zend framework with Doctrine. I am happy with setup but often find function not found errors on live site cause I have renamed function. Which is frustrating as most of time is wasted is patching these errors.
So I have decided to switch from php to java as the code gets compiled, so just error will not go to live site. With java netbeans will work better.

But as I have not been in touch to j2ee for many years. What is the best replacement for my above setup in java?

Option 1. Jsf 2 with Hibernate

Option 2. Seam

Option 3. Spring

Option 4. Struts with Hibernate

My server has 24 gig ram and 2 core i7 processor and ssd drive on raid 0

Will my server handle the same amount of visitors if java was used without any performance issues?

I like the way I can update my site without losing live sessions(logged-in users). Can I do the same in Java? from my experience each update to site will redeploy the App which resets all the Active Sessions.

I love to consider .Net but from what I have read on most forums, no one recommends it?

Kind regards

Zerone

答:
if you dont use ajax, i prefer 4 (struts + hibernate):

jsf needs an little bit of expiriences on such heavy load (getter-methods must be fast and so on).

if you use ajax, i prefer an combination of 3 and 1

regards
peter

Title: Switch from PHP to Java or .Net


来源: stackexchange

问:
Stop cmd windows from closing after running a . py file using PuTTY (Plink)
I have a Python script which is called to download certain data from database. I have a download button, when pressed a cmd window uses Plink opens up and show the progress and status inside this cmd window. After sometime the cmd window closes off very quickly automatically. How to stop it from closing (want this cmd window to be open until we close it) so that we can see the current status of download operation.

答:
Run something in the console window that pauses at the end.

Most trivial approach is to replace the direct plink call with cmd call that runs plink and pause:

```<code>cmd /c plink user@host command & pause
</code>```

For ultimate control, do run your own Python script in the new console window. That way you can implement any kind of pause you want. You can even replace the plink call with native SSH Python code:

Perform commands over ssh with Python

ContentLicense: CC BY-SA 4.0

Body:
Run something in the console window that pauses at the end.

Most trivial approach is to replace the direct plink call with cmd call that runs plink and pause:

cmd /c plink user@host command & pause

For ultimate control, do run your own Python script in the new console window. That way you can implement any kind of pause you want. You can even replace the plink call with native SSH Python code:

Perform commands over ssh with Python


问:
PHPMyAdmin gives "Host "xxx.xxx.xxx.xxx" is not allowed to connect to this MySQL server" error
I am working on Centos 7, trying to get everything to work in Docker.
I've set up Nginx and PHP-FPM successfully - both of them work and display everything like they are supposed to. I made so I can open them up with Docker-compose.
After that, I made this paragraph in Docker-compose:

```<code>  mysql:
    image: "mysql:latest"
    container_name: mysql
    ports:
      - "3306:3306"
    environment:
      TZ: Europe/Myregion
      MYSQL_ROOT_PASSWORD: 123123
    volumes:
      - ./data:/var/lib/mysql
</code>```

I set up TZ to my region, no worries here.
As you see, I specifically requested for an example that MySQL's password is set to "123123". But when I try to log into it with "mysql -u root -p", it denies - says the password the incorrect. But when I leave it empty, I can log into it - for an unknown reason the password is empty.
I thought it might work and did set up PHPMyAdmin in Docker-compose:

```<code>phpmyadmin:
    image: "phpmyadmin:latest"
    container_name: phpmyadmin
    ports:
      - "8080:80"
    environment:
      - TZ=Europe/Myreqion
      - PMA_ARBITRARY=1
      - PMA_HOST=mysql
    depends_on:
      - mysql
</code>```

And after that I get PHPMyAdmin window in browser and I can't log in! At all!
Sometimes it gives the "Host "xxx.xxx.xxx.xxx" is not allowed to connect to this MySQL server" error, sometimes it gives the error "Login without a password is forbidden by configuration (see AllowNoPassword)".
I can't add a new user, I can't grant myself privileges or edit tables (because MySQL suddenly says that I don't have access to do so, but I am in the wheel permissions group) and I can't do anything at all.
This has stopped me for a week. Any ideas?

Solution: grant yourself administrator privileges while installing this VM.

答:
Can you make sure that the running mysql in Docker? My guess that the mysql is not in Docker. I remembered installing mysql from yum, and able to login without password with user root.

PS: I tried your docker-compose script exactly (except TZ of course), my ip is 192.168.0.3, and I was able to login to that IP from phpmyadmin.

Body:
I am working on Centos 7, trying to get everything to work in Docker.
I've set up Nginx and PHP-FPM successfully - both of them work and display everything like they are supposed to. I made so I can open them up with Docker-compose.
After that, I made this paragraph in Docker-compose:

  mysql:
    image: "mysql:latest"
    container_name: mysql
    ports:
      - "3306:3306"
    environment:
      TZ: Europe/Myregion
      MYSQL_ROOT_PASSWORD: 123123
    volumes:
      - ./data:/var/lib/mysql

I set up TZ to my region, no worries here.
As you see, I specifically requested for an example that MySQL's password is set to "123123". But when I try to log into it with "mysql -u root -p", it denies - says the password the incorrect. But when I leave it empty, I can log into it - for an unknown reason the password is empty.
I thought it might work and did set up PHPMyAdmin in Docker-compose:

phpmyadmin:
    image: "phpmyadmin:latest"
    container_name: phpmyadmin
    ports:
      - "8080:80"
    environment:
      - TZ=Europe/Myreqion
      - PMA_ARBITRARY=1
      - PMA_HOST=mysql
    depends_on:
      - mysql

And after that I get PHPMyAdmin window in browser and I can't log in! At all!
Sometimes it gives the "Host "xxx.xxx.xxx.xxx" is not allowed to connect to this MySQL server" error, sometimes it gives the error "Login without a password is forbidden by configuration (see AllowNoPassword)".
I can't add a new user, I can't grant myself privileges or edit tables (because MySQL suddenly says that I don't have access to do so, but I am in the wheel permissions group) and I can't do anything at all.
This has stopped me for a week. Any ideas?

Solution: grant yourself administrator privileges while installing this VM.


问:
How to georeference an unreferenced aerial image using ground control points in python
I have a series of unreferenced aerial images that I would like to georeference using python. The images are identical spatially (they are actually frames extracted from a video), and I obtained ground control points for them by manually georeferencing one frame in ArcMap. I would like to apply the ground control points I obtained to all the subsequent images, and as a result obtain a geo-tiff or a jpeg file with a corresponding world file (.jgw) for each processed image. I know this is possible to do using arcpy, but I do not have access to arcpy, and would really like to use a free open source module if possible.

My coordinate system is NZGD2000 (epsg 2193), and here is the table of control points I wish to apply to my images:

176.412984, -310.977264, 1681255.524654, 6120217.357425

160.386905, -141.487145, 1681158.424227, 6120406.821253

433.204947, -310.547238, 1681556.948690, 6120335.658359

Here is an example image: https://imgur.com/a/9ThHtOz

I've read a lot of information on GDAL and rasterio, but I don't have any experience with them, and am failing to adapt bits of code I found to my particular situation.

Rasterio attempt:

```<code>import cv2
from rasterio.warp import reproject
from rasterio.control import GroundControlPoint
from fiona.crs import from_epsg

img = cv2.imread("Example_image.jpg")

# Creating ground control points (not sure if I got the order of variables right):
points = [(GroundControlPoint(176.412984, -310.977264, 1681255.524654, 6120217.357425)),
          (GroundControlPoint(160.386905, -141.487145, 1681158.424227, 6120406.821253)),
          (GroundControlPoint(433.204947, -310.547238, 1681556.948690, 6120335.658359))]

# The function requires a parameter "destination", but I'm not sure what to put there.
#   I'm guessing this may not be the right function to use
reproject(img, destination, src_transform=None, gcps=points, src_crs=from_epsg(2193),
                        src_nodata=None, dst_transform=None, dst_crs=from_epsg(2193), dst_nodata=None,
                        src_alpha=0, dst_alpha=0, init_dest_nodata=True, warp_mem_limit=0)
</code>```

GDAL attempt:

```<code>from osgeo import gdal
import osr

inputImage = "Example_image.jpg"
outputImage = "image_gdal.jpg"

dataset = gdal.Open(inputImage)
I = dataset.ReadAsArray(0,0,dataset.RasterXSize,dataset.RasterYSize)

outdataset = gdal.GetDriverByName('GTiff')
output_SRS = osr.SpatialReference()
output_SRS.ImportFromEPSG(2193)
outdataset = outdataset.Create(outputImage,dataset.RasterXSize,dataset.RasterYSize,I.shape[0])
for nb_band in range(I.shape[0]):
    outdataset.GetRasterBand(nb_band+1).WriteArray(I[nb_band,:,:])

# Creating ground control points (not sure if I got the order of variables right):
gcp_list = []
gcp_list.append(gdal.GCP(176.412984, -310.977264, 1681255.524654, 6120217.357425))
gcp_list.append(gdal.GCP(160.386905, -141.487145, 1681158.424227, 6120406.821253))
gcp_list.append(gdal.GCP(433.204947, -310.547238, 1681556.948690, 6120335.658359))

outdataset.SetProjection(srs.ExportToWkt())
wkt = outdataset.GetProjection()
outdataset.SetGCPs(gcp_list,wkt)

outdataset = None
</code>```

I don't quite know how to make the above code work, and I would really appreciate any help with this.

答:
As an addition to @Kat's answer, to avoid quality loss of the original image file and set the nodata-value to 0, the following can be used.</p>
```<code>#Load the original file
src_ds = gdal.Open(orig_fn)

#Create tmp dataset saved in memory
driver = gdal.GetDriverByName('MEM')
tmp_ds = driver.CreateCopy('', src_ds, strict=0)

#
# ... setting GCP....
#

# Setting no data for all bands
for i in range(1, tmp_ds.RasterCount + 1):
    f = tmp_ds.GetRasterBand(i).SetNoDataValue(0)

# Saving as file
driver = gdal.GetDriverByName('GTiff')
ds = driver.CreateCopy(output_fn, tmp_ds, strict=0)
</code>```

Body:
I have a series of unreferenced aerial images that I would like to georeference using python. The images are identical spatially (they are actually frames extracted from a video), and I obtained ground control points for them by manually georeferencing one frame in ArcMap. I would like to apply the ground control points I obtained to all the subsequent images, and as a result obtain a geo-tiff or a jpeg file with a corresponding world file (.jgw) for each processed image. I know this is possible to do using arcpy, but I do not have access to arcpy, and would really like to use a free open source module if possible.

My coordinate system is NZGD2000 (epsg 2193), and here is the table of control points I wish to apply to my images:

176.412984, -310.977264, 1681255.524654, 6120217.357425

160.386905, -141.487145, 1681158.424227, 6120406.821253

433.204947, -310.547238, 1681556.948690, 6120335.658359

Here is an example image: https://imgur.com/a/9ThHtOz

I've read a lot of information on GDAL and rasterio, but I don't have any experience with them, and am failing to adapt bits of code I found to my particular situation.

Rasterio attempt:

import cv2
from rasterio.warp import reproject
from rasterio.control import GroundControlPoint
from fiona.crs import from_epsg

img = cv2.imread("Example_image.jpg")

# Creating ground control points (not sure if I got the order of variables right):
points = [(GroundControlPoint(176.412984, -310.977264, 1681255.524654, 6120217.357425)),
          (GroundControlPoint(160.386905, -141.487145, 1681158.424227, 6120406.821253)),
          (GroundControlPoint(433.204947, -310.547238, 1681556.948690, 6120335.658359))]

# The function requires a parameter "destination", but I'm not sure what to put there.
#   I'm guessing this may not be the right function to use
reproject(img, destination, src_transform=None, gcps=points, src_crs=from_epsg(2193),
                        src_nodata=None, dst_transform=None, dst_crs=from_epsg(2193), dst_nodata=None,
                        src_alpha=0, dst_alpha=0, init_dest_nodata=True, warp_mem_limit=0)

GDAL attempt:

from osgeo import gdal
import osr

inputImage = "Example_image.jpg"
outputImage = "image_gdal.jpg"

dataset = gdal.Open(inputImage)
I = dataset.ReadAsArray(0,0,dataset.RasterXSize,dataset.RasterYSize)

outdataset = gdal.GetDriverByName('GTiff')
output_SRS = osr.SpatialReference()
output_SRS.ImportFromEPSG(2193)
outdataset = outdataset.Create(outputImage,dataset.RasterXSize,dataset.RasterYSize,I.shape[0])
for nb_band in range(I.shape[0]):
    outdataset.GetRasterBand(nb_band+1).WriteArray(I[nb_band,:,:])

# Creating ground control points (not sure if I got the order of variables right):
gcp_list = []
gcp_list.append(gdal.GCP(176.412984, -310.977264, 1681255.524654, 6120217.357425))
gcp_list.append(gdal.GCP(160.386905, -141.487145, 1681158.424227, 6120406.821253))
gcp_list.append(gdal.GCP(433.204947, -310.547238, 1681556.948690, 6120335.658359))

outdataset.SetProjection(srs.ExportToWkt())
wkt = outdataset.GetProjection()
outdataset.SetGCPs(gcp_list,wkt)

outdataset = None

I don't quite know how to make the above code work, and I would really appreciate any help with this.

Body:
As an addition to @Kat's answer, to avoid quality loss of the original image file and set the nodata-value to 0, the following can be used.

#Load the original file
src_ds = gdal.Open(orig_fn)

#Create tmp dataset saved in memory
driver = gdal.GetDriverByName('MEM')
tmp_ds = driver.CreateCopy('', src_ds, strict=0)

#
# ... setting GCP....
#

# Setting no data for all bands
for i in range(1, tmp_ds.RasterCount + 1):
    f = tmp_ds.GetRasterBand(i).SetNoDataValue(0)

# Saving as file
driver = gdal.GetDriverByName('GTiff')
ds = driver.CreateCopy(output_fn, tmp_ds, strict=0)


问:
LINQ not checking for null
The following code is supposed to take a simple average of Tuition rates if present for each row, but the requirement dictates the imported data set allow null values.

The line below is not properly checking value and I am getting the error: "ArgumentNullException was unhandled by user code, Value cannot be null."

```<code>TUITIONCurr = g
    .Where(p => !object.Equals(p.Field<double>("TUITION"),null))
    .DefaultIfEmpty()
    .Average(p => p.Field<double>("TUITION")),
</code>```

答:
You should be comparing to DBNull.Value, not null:

```<code>TUITIONCurr = g
    .Where(p => !object.Equals(p.Field<double>("TUITION"), DBNull.Value))
    .Average(p => p.Field<double>("TUITION"));
</code>```

Once you've filtered out nulls, you don't need the DefaultIfEmpty() call.

ContentLicense: CC BY-SA 3.0

Title: LINQ not checking for null

Body:
The following code is supposed to take a simple average of Tuition rates if present for each row, but the requirement dictates the imported data set allow null values.

The line below is not properly checking value and I am getting the error: "ArgumentNullException was unhandled by user code, Value cannot be null."

TUITIONCurr = g
    .Where(p => !object.Equals(p.Field<double>("TUITION"),null))
    .DefaultIfEmpty()
    .Average(p => p.Field<double>("TUITION")),

Body:
You should be comparing to DBNull.Value, not null:

TUITIONCurr = g
    .Where(p => !object.Equals(p.Field<double>("TUITION"), DBNull.Value))
    .Average(p => p.Field<double>("TUITION"));

Once you've filtered out nulls, you don't need the DefaultIfEmpty() call.


问:
How to check the specific element in string are equal in python?
There is a two input first input represent the index of the second input.I need to find the 'X' position of second input are same or not?

input:

```<code>123X56XX
Ahjutruu

Output:
  True
</code>```

Example:
X in input one at 4,7,8

position of 4,7,8 in second input is 'u' all are same so i need to print "true"

I tried using enumerate function but not came:

```<code>a="123X56XX"
b="Ahjutruu"
xi=[]

for i,val in enumerate(a):
  if val=='X':
    xi.append(i)
print(xi)
#next step only i dont know how to doo please help
</code>```

Next i dont know how to check

答:
Put all values of given indexes of xi in set, the length of this set must equal to 1:

xi = [i for i, c in enumerate(a) if c == 'X']
len(set([b[i] for i in xi])) == 1
```

Body:
There is a two input first input represent the index of the second input.I need to find the 'X' position of second input are same or not?

input:

123X56XX
Ahjutruu

Output:
  True

Example:
X in input one at 4,7,8

position of 4,7,8 in second input is 'u' all are same so i need to print "true"

I tried using enumerate function but not came:

a="123X56XX"
b="Ahjutruu"
xi=[]

for i,val in enumerate(a):
  if val=='X':
    xi.append(i)
print(xi)
#next step only i dont know how to doo please help

Next i dont know how to check


问:
Page background Images are not changing on scroll
I am trying to change the background image when the user scrolls the page. The code I have written is not working. I am running this code on a WordPress website. Below Is my code.

```<code> <script type="text/javascript">
jQuery(document).ready(function( jQuery ) {
    jQuery(window).on('scroll touchmove', function() {

        if (jQuery(document).scrollTop() >= jQuery('#one').position().top) {
            jQuery('body').css('background', jQuery('#one').attr('data-src'));
        }

        if (jQuery(document).scrollTop() > jQuery('#two').position().top) {
            jQuery('body').css('background', jQuery('#two').attr('data-src'));
        }

        if (jQuery(document).scrollTop() > jQuery('#three').position().top) {
            jQuery('body').css('background', jQuery('#three').attr('data-src'));
        }

        if (jQuery(document).scrollTop() > jQuery('#four').position().top) {
            jQuery('body').css('background', jQuery('#four').attr('data-src'));
        }

        if (jQuery(document).scrollTop() > jQuery('#five').position().top) {
            jQuery('body').css('background', jQuery('#five').attr('data-src'));
        }

    });
})(jQuery);
</script>
</code>```

Here I have five sections and I gave an ID to my section as I define on the code. Below is how I added the 'data-src' attribute to the particular section through the elementor data attribute option.

data-src|http://www.kasundev.xyz/design/wp-content/uploads/2022/02/WhatsApp-Image-2022-02-10-at-11.00.38.jpeg

This is the CSS I am using when the page loads first. This code applies to the whole page.

```<code>body {
  background:#333333;
  transition: all 1200ms ease-out;
  will-change: background;
}
</code>```

My question is nothing is changing when I scroll. Instead of an image If I give a color like this
data-color|#000000 will change.

How I change my background image when scrolling. Can anyone help me out?

Thanks

答: You need to add url('image path') around the image.</p>

Body:
I am trying to change the background image when the user scrolls the page. The code I have written is not working. I am running this code on a WordPress website. Below Is my code.

Here I have five sections and I gave an ID to my section as I define on the code. Below is how I added the 'data-src' attribute to the particular section through the elementor data attribute option.

data-src|http://www.kasundev.xyz/design/wp-content/uploads/2022/02/WhatsApp-Image-2022-02-10-at-11.00.38.jpeg

This is the CSS I am using when the page loads first. This code applies to the whole page.

body {
  background:#333333;
  transition: all 1200ms ease-out;
  will-change: background;
}

My question is nothing is changing when I scroll. Instead of an image If I give a color like this
data-color|#000000 will change.

How I change my background image when scrolling. Can anyone help me out?

Thanks


问:
What is the meaning of T D P S S S C I when I get output of usb-devices on terminal?
I want to get USB bus port details (which have USB serial ID number, USB type, USB name, port type, port name, and many other data points) in Ubuntu.

I typed usb-devices where I got a certain no of rows starting with T, D, P, S, etc.

Someone help me in identifying these terminologies.

答:
According to source code: https://github.com/gregkh/usbutils/blob/master/usb-devices

T: Transport

D: Device class

P: Product vendor id

S: String

C: Configuration

E: Endpoint

I: Interface


答:
the logic is added for matching the X places in a</p>
```<code>a = "123X56XX"
b = "Ahjutruu"
xi = []
allSame = True
for i, val in enumerate(a):
    if val == 'X':
        xi.append(i)#saving the indices
allSame = len(a) == len(b)  # length must be same
prev = None
for v in xi:
    if not allSame:
        break
    if prev is None:
        prev = b[v]  # if previous value is not set setting it
    else:
        allSame = prev == b[v]  # matching with previous value in b's list

print(allSame)
</code>```

Title: How to check the specific element in string are equal in python?

Body:
the logic is added for matching the X places in a

a = "123X56XX"
b = "Ahjutruu"
xi = []
allSame = True
for i, val in enumerate(a):
    if val == 'X':
        xi.append(i)#saving the indices
allSame = len(a) == len(b)  # length must be same
prev = None
for v in xi:
    if not allSame:
        break
    if prev is None:
        prev = b[v]  # if previous value is not set setting it
    else:
        allSame = prev == b[v]  # matching with previous value in b's list

print(allSame)


问:
Won't let me find average of the dictionary
I need to have a dictionary created by what the user inputs. I then need to allow them to input a name and time length which I have managed successfully. I also think I got it to tell me the shortest and longest length correctly. However, for some reason it won't let me calculate an average. I have spent hours researching it on youtube and trying different things, so my hypothesis is that something is incorrect at the top of my code which isn't allowing the calculation of an average.</p>
```<code>n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=input("What is length?")
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

average = sum(my_dict.values())/ len(v)

print("Your average length is", average)
</code>```

答:
If you don't wanna change your inputs type

u can change dictionary values to float

like:

```<code>n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=int(input("What is length?"))
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest," minutes long.")
print("Your longest video is", longest," minutes long.")

for v in my_dict.keys():
    my_dict[v] = float(my_dict[v])

avg = sum(my_dict.values()) / len(my_dict)
print (avg)```
```

Body:
I need to have a dictionary created by what the user inputs. I then need to allow them to input a name and time length which I have managed successfully. I also think I got it to tell me the shortest and longest length correctly. However, for some reason it won't let me calculate an average. I have spent hours researching it on youtube and trying different things, so my hypothesis is that something is incorrect at the top of my code which isn't allowing the calculation of an average.

n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=input("What is length?")
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

average = sum(my_dict.values())/ len(v)

print("Your average length is", average)

Body:
If you don't wanna change your inputs type

u can change dictionary values to float

like:

n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=int(input("What is length?"))
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest," minutes long.")
print("Your longest video is", longest," minutes long.")

for v in my_dict.keys():
    my_dict[v] = float(my_dict[v])

avg = sum(my_dict.values()) / len(my_dict)
print (avg)```


答:
you can do like this</p>
```<code>a = "123X56XX"
b = "Ahjutruu"

status = len({j for i,j in zip(a,b) if i=='X'}) == 1
print(status)
</code>```

Body:
you can do like this

a = "123X56XX"
b = "Ahjutruu"

status = len({j for i,j in zip(a,b) if i=='X'}) == 1
print(status)


问:
Why it is appropriate to use `std::uniform_real_distribution`?
I'm trying to write Metropolis Monte Carlo simulation code.
Since the simulation will be very long, I'd like to think seriously about the performance for generating random numbers in [0, 1].

So I decided to check the performance of two methods by the following code:

#include <cfloat>
#include <chrono>
#include <iostream>
#include <random>

int main()
{
    constexpr auto Ntry = 5000000;

    std::mt19937 mt(123);
    std::uniform_real_distribution<double> dist(0.0, std::nextafter(1.0, DBL_MAX));
    double test1, test2;

    // method 1
    auto start1 = std::chrono::system_clock::now();
    for (int i=0; i<Ntry; i++) {
        test1 = dist(mt);
    }
    auto end1 = std::chrono::system_clock::now();
    auto elapsed1 = std::chrono::duration_cast<std::chrono::microseconds>(end1-start1).count();
    std::cout << elapsed1 << std::endl;

    // method 2
    auto start2 = std::chrono::system_clock::now();
    for (int i=0; i<Ntry; i++) {
        test2 = 1.0*mt() / mt.max();
    }
    auto end2 = std::chrono::system_clock::now();
    auto elapsed2 = std::chrono::duration_cast<std::chrono::microseconds>(end2-start2).count();
    std::cout << elapsed2 << std::endl;
}
```

Then the result is

295489 micro sec for method 1

79884 micro sec for method 2

I understand that there are many posts that recommend to use std::uniform_real_distribution.
But performance-wise, it is tempting to use the latter as this result shows.

Would you tell me what is the point of using std::uniform_real_distribution?
What is the disadvantage of using 1.0*mt() / mt.max()?
And in the current purpose, is it acceptable to use 1.0*mt() / mt.max() instead?

Edit:

I compiled this code with g++-11 test.cpp.
When I compile with -O3 flag, the result is qualitatively same (the method 1 is approx. 1.8 times slower).
I would like to discuss what is the advantage of the widely-used method.
I do concern the trend of performances, but specific performance comparison is out of my scope.

答:
You use the standard random library because it is extremely difficult to do numerical calculations correctly and you don't want the burden of proving and maintaining your own random library.

Case in point, your random distribution is wrong. std::mt19937 produces 32-bit integers, yet you're expecting a double, which has a 53-bit significand (usually). There are values in the range [0, 1] that you will never obtain from 1.0*mt() / mt::max().

Body:
I'm trying to write Metropolis Monte Carlo simulation code.
Since the simulation will be very long, I'd like to think seriously about the performance for generating random numbers in [0, 1].

So I decided to check the performance of two methods by the following code:

#include <cfloat>
#include <chrono>
#include <iostream>
#include <random>

int main()
{
    constexpr auto Ntry = 5000000;

    std::mt19937 mt(123);
    std::uniform_real_distribution<double> dist(0.0, std::nextafter(1.0, DBL_MAX));
    double test1, test2;

    // method 1
    auto start1 = std::chrono::system_clock::now();
    for (int i=0; i<Ntry; i++) {
        test1 = dist(mt);
    }
    auto end1 = std::chrono::system_clock::now();
    auto elapsed1 = std::chrono::duration_cast<std::chrono::microseconds>(end1-start1).count();
    std::cout << elapsed1 << std::endl;

    // method 2
    auto start2 = std::chrono::system_clock::now();
    for (int i=0; i<Ntry; i++) {
        test2 = 1.0*mt() / mt.max();
    }
    auto end2 = std::chrono::system_clock::now();
    auto elapsed2 = std::chrono::duration_cast<std::chrono::microseconds>(end2-start2).count();
    std::cout << elapsed2 << std::endl;
}

Then the result is

295489 micro sec for method 1

79884 micro sec for method 2

I understand that there are many posts that recommend to use std::uniform_real_distribution.
But performance-wise, it is tempting to use the latter as this result shows.

Would you tell me what is the point of using std::uniform_real_distribution?
What is the disadvantage of using 1.0*mt() / mt.max()?
And in the current purpose, is it acceptable to use 1.0*mt() / mt.max() instead?

Edit:

I compiled this code with g++-11 test.cpp.
When I compile with -O3 flag, the result is qualitatively same (the method 1 is approx. 1.8 times slower).
I would like to discuss what is the advantage of the widely-used method.
I do concern the trend of performances, but specific performance comparison is out of my scope.


问:
variable decimal places in .Net string formatters?
Fixed decimal places is easy

```<code>String.Format("{0:F1}", 654.321);
</code>```

gives

```<code>654.3
</code>```

How do I feed the number of decimal places in as a parameter like you can in C?
So

```<code>String.Format("{0:F?}", 654.321, 2);
</code>```

gives

```<code>654.32
</code>```

I can't find what should replace the ?

答:
Use the custom numeric format string Link</p>

```<code>var value = 654.321;
var s = value.ToString("0.##");
</code>```

Body:
Fixed decimal places is easy

String.Format("{0:F1}", 654.321);

gives

654.3

How do I feed the number of decimal places in as a parameter like you can in C?
So

String.Format("{0:F?}", 654.321, 2);

gives

654.32

I can't find what should replace the ?

Body:
Use the custom numeric format string Link

var value = 654.321;
var s = value.ToString("0.##");


问:
Why am I receiving a type error for Python?
"Write a program with total change amount as an integer input that outputs the change using the fewest coins, one coin type per line. The coin types are dollars, quarters, dimes, nickels, and pennies. Use singular and plural coin names as appropriate, like 1 penny vs. 2 pennies. Your program must define and call the following function. The function exact_change() should return num_dollars, num_quarters, num_dimes, num_nickels, and num_pennies."

The line "num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change(input_val)" is what's giving me trouble but its a required line in the assignment.

The error says:
File "main.py", line 36, in
num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change(input_val)
TypeError: 'NoneType' object is not iterable

if __name__ == '__main__':
    input_val = int(input())

num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change(input_val)

    num_dollars = input_val // 100
    input_val %= 100
    num_quarters = input_val // 25
    input_val %= 25
    num_dimes = input_val // 10
    input_val %= 10
    num_nickels = input_val // 5
    input_val %= 5
    num_pennies = input_val

    if num_dollars >1:
        print('%d dollars' % num_dollars)
    elif num_dollars ==1:
        print('%d dollar' % num_dollars)
    if num_quarters > 1:
        print('%d quarters' % num_quarters)
    elif num_quarters ==1:
        print('%d quarter' % num_quarters)
    if num_dimes >1:
        print('%d dimes' % num_dimes)
    elif num_dimes ==1:
        print('%d dime' % num_dimes)
    if num_nickels >1:
        print('%d nickels' % num_nickels)
    elif num_nickels ==1:
        print('%d nickel' % num_nickels)
    if num_pennies >1:
        print('%d pennies' % num_pennies)
    elif num_pennies ==1:
        print('%d penny' % num_pennies)
if input_val <= 0:
    print('no change')
```

The error says:

File "main.py", line 36, in
num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change(input_val)
TypeError: 'NoneType' object is not iterable

答:
Here's my solution using a while loop. . .</p>
```<code>def exact_change(user_total):
        dollar,quarter,dime,nickel,penny = 100,25,10,5,1
        dollar_out, quarter_out, dime_out,nickel_out, penny_out = 0,0,0,0,0

while user_total > 0:
    if user_total >= dollar:
        dollar_out = dollar_out + 1
        user_total = user_total - dollar

    elif user_total >= quarter:
        quarter_out = quarter_out + 1
        user_total = user_total - quarter

    elif user_total >= dime:
        dime_out = dime_out + 1
        user_total = user_total - dime

    elif user_total >= nickel:
        nickel_out = nickel_out + 1
        user_total = user_total - nickel

    else:
        penny_out = user_total
        user_total = 0

return {"dollars" if (dollar_out > 1) else "dollar": dollar_out,
       "quarters" if (quarter_out > 1) else "quarter": quarter_out,
       "dimes" if (dime_out > 1) else "dime": dime_out,
       "nickels" if (nickel_out > 1) else "nickel": nickel_out,
       "pennies" if (penny_out > 1) else "penny": penny_out,}

if __name__=="__main__":
    input_val = int(input())

if input_val == 0:
    print("no change")

else:
    res = exact_change(input_val)
    for key, value in res.items():
        if value > 0:
            print(value, key)
</code>```

Body:
"Write a program with total change amount as an integer input that outputs the change using the fewest coins, one coin type per line. The coin types are dollars, quarters, dimes, nickels, and pennies. Use singular and plural coin names as appropriate, like 1 penny vs. 2 pennies. Your program must define and call the following function. The function exact_change() should return num_dollars, num_quarters, num_dimes, num_nickels, and num_pennies."

The line "num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change(input_val)" is what's giving me trouble but its a required line in the assignment.

The error says:
File "main.py", line 36, in
num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change(input_val)
TypeError: 'NoneType' object is not iterable

if __name__ == '__main__':
    input_val = int(input())

num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change(input_val)

    num_dollars = input_val // 100
    input_val %= 100
    num_quarters = input_val // 25
    input_val %= 25
    num_dimes = input_val // 10
    input_val %= 10
    num_nickels = input_val // 5
    input_val %= 5
    num_pennies = input_val

    if num_dollars >1:
        print('%d dollars' % num_dollars)
    elif num_dollars ==1:
        print('%d dollar' % num_dollars)
    if num_quarters > 1:
        print('%d quarters' % num_quarters)
    elif num_quarters ==1:
        print('%d quarter' % num_quarters)
    if num_dimes >1:
        print('%d dimes' % num_dimes)
    elif num_dimes ==1:
        print('%d dime' % num_dimes)
    if num_nickels >1:
        print('%d nickels' % num_nickels)
    elif num_nickels ==1:
        print('%d nickel' % num_nickels)
    if num_pennies >1:
        print('%d pennies' % num_pennies)
    elif num_pennies ==1:
        print('%d penny' % num_pennies)
if input_val <= 0:
    print('no change')

The error says:

File "main.py", line 36, in
num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change(input_val)
TypeError: 'NoneType' object is not iterable

Body:
Here's my solution using a while loop. . .

def exact_change(user_total):
        dollar,quarter,dime,nickel,penny = 100,25,10,5,1
        dollar_out, quarter_out, dime_out,nickel_out, penny_out = 0,0,0,0,0

while user_total > 0:
    if user_total >= dollar:
        dollar_out = dollar_out + 1
        user_total = user_total - dollar

    elif user_total >= quarter:
        quarter_out = quarter_out + 1
        user_total = user_total - quarter

    elif user_total >= dime:
        dime_out = dime_out + 1
        user_total = user_total - dime

    elif user_total >= nickel:
        nickel_out = nickel_out + 1
        user_total = user_total - nickel

    else:
        penny_out = user_total
        user_total = 0

return {"dollars" if (dollar_out > 1) else "dollar": dollar_out,
       "quarters" if (quarter_out > 1) else "quarter": quarter_out,
       "dimes" if (dime_out > 1) else "dime": dime_out,
       "nickels" if (nickel_out > 1) else "nickel": nickel_out,
       "pennies" if (penny_out > 1) else "penny": penny_out,}

if __name__=="__main__":
    input_val = int(input())

if input_val == 0:
    print("no change")

else:
    res = exact_change(input_val)
    for key, value in res.items():
        if value > 0:
            print(value, key)


问:
Determine complete Django url configuration
Is there a way to get the complete django url configuration?

For example Django's debugging 404 page does not show included url configs, so this is not the complete configuration.

答:
If you want a list of all the urls in your project, first you need to install django-extensions

You can simply install using command.

```<code>pip install django-extensions
</code>```

For more information related to package goto django-extensions

After that, add django_extensions in INSTALLED_APPS in your settings.py file like this:

```<code>INSTALLED_APPS = (
...
'django_extensions',
...
)
</code>```

urls.py example:

```<code>from django.urls import path, include
from . import views
from . import health_views

urlpatterns = [
    path('get_url_info', views.get_url_func),
    path('health', health_views.service_health_check),
    path('service-session/status', views.service_session_status)
]

</code>```

And then, run any of the command in your terminal

```<code>python manage.py show_urls
</code>```

or

```<code>./manage.py show_urls
</code>```

Sample output example based on config urls.py:

```<code>/get_url_info             django_app.views.get_url_func
/health                   django_app.health_views.service_health_check
/service-session/status   django_app.views.service_session_status
</code>```

For more information you can check the documentation.

ContentLicense: CC BY-SA 2.5

Body:
If you want a list of all the urls in your project, first you need to install django-extensions

You can simply install using command.

pip install django-extensions

For more information related to package goto django-extensions

After that, add django_extensions in INSTALLED_APPS in your settings.py file like this:

INSTALLED_APPS = (
...
'django_extensions',
...
)

urls.py example:

from django.urls import path, include
from . import views
from . import health_views

urlpatterns = [
    path('get_url_info', views.get_url_func),
    path('health', health_views.service_health_check),
    path('service-session/status', views.service_session_status)
]

And then, run any of the command in your terminal

python manage.py show_urls

or

./manage.py show_urls

Sample output example based on config urls.py:

/get_url_info             django_app.views.get_url_func
/health                   django_app.health_views.service_health_check
/service-session/status   django_app.views.service_session_status

For more information you can check the documentation.


问:
convert random string to datetime in python
I have extracted data with date formatted 28-12-2019 19:13 +07:00  and it was not recognize as datetime by Pandas. how can I create new column with column name creation_date  and add the correct datetime format.

i tried this but error

```<code>
data = 'data.xlsx'
df = pd.read_excel(data)

df['creation_date'] = pd.to_datetime(df['date'].str[:2] + '-' + df['date'].str[4:2] + '-' + df['date'].str[7:4])

print(df)
</code>```

i want the format to be recognized in excel which is 12/28/2019  08:13:00 PM. +1 hour since my GMT is +8

答:
I've written the below solution for a single string. In your case, you'll need to adapt it for your whole data frame column.

First of all, you need to convert the string containing date and time to a datetime object.

You can do this using following code:

```<code>import datetime
Date = "28-12-2019 19:13 +07:00"
datetimeObj = datetime.datetime.strptime(Date, "%d-%m-%Y %H:%M %z")
</code>```

Which will give you a datetime object like this:

```<code>datetime.datetime(2019, 12, 28, 19, 13, tzinfo=datetime.timezone(datetime.timedelta(seconds=25200)))
</code>```

The next thing you'll need to do is, convert this datetime object to your preferred timezone.

For that you can use the following code:

```<code>datetimeObj.astimezone(ZoneInfo('Europe/London'))
</code>```

Note:

I've considered London for the sake of demonstration. You'll need to choose it accordingly.

The above solution will work only if you have Python 3.9+ installed. If you have any other version installed, check this answer.

The next thing you'll need to do is formatting the datetime object so that it represents date and time in a way you want.

```<code>datetimeObj = datetime.datetime.strftime(datetimeObj, "%m/%d/%Y %H:%M")
</code>```

This will produce the following output:

```<code>'12/28/2019 12:13'
</code>```

Body:
I have extracted data with date formatted 28-12-2019 19:13 +07:00  and it was not recognize as datetime by Pandas. how can I create new column with column name creation_date  and add the correct datetime format.

i tried this but error

data = 'data.xlsx'
df = pd.read_excel(data)

df['creation_date'] = pd.to_datetime(df['date'].str[:2] + '-' + df['date'].str[4:2] + '-' + df['date'].str[7:4])

print(df)

i want the format to be recognized in excel which is 12/28/2019  08:13:00 PM. +1 hour since my GMT is +8

Body:
I've written the below solution for a single string. In your case, you'll need to adapt it for your whole data frame column.

First of all, you need to convert the string containing date and time to a datetime object.

You can do this using following code:

import datetime
Date = "28-12-2019 19:13 +07:00"
datetimeObj = datetime.datetime.strptime(Date, "%d-%m-%Y %H:%M %z")

Which will give you a datetime object like this:

datetime.datetime(2019, 12, 28, 19, 13, tzinfo=datetime.timezone(datetime.timedelta(seconds=25200)))

The next thing you'll need to do is, convert this datetime object to your preferred timezone.

For that you can use the following code:

datetimeObj.astimezone(ZoneInfo('Europe/London'))

Note:

I've considered London for the sake of demonstration. You'll need to choose it accordingly.

The above solution will work only if you have Python 3.9+ installed. If you have any other version installed, check this answer.

The next thing you'll need to do is formatting the datetime object so that it represents date and time in a way you want.

datetimeObj = datetime.datetime.strftime(datetimeObj, "%m/%d/%Y %H:%M")

This will produce the following output:

'12/28/2019 12:13'


问:
Angular TinyMCE open Angular Material Dialog
I have an Angular application and I am using Tiny-MCE editor.

I want to click on the new button I have added to the editor to open Angular Material Dialog.

When opening a dialog inside the new custom plugin that I have created I get the following error.

```<code>Cannot read properties of undefined (reading 'open')
</code>```

to make sure that the dialog component is working fine I have added a button outside the editor and it is working fine.

please find the code sample here:

https://stackblitz.com/edit/angular-ivy-k3nguv?file=src/app/app.component.ts

答:
Use () => {} instead function() {}.

Example:

```<code>onAction: () => {
   ...
}
</code>```

Body:
I have an Angular application and I am using Tiny-MCE editor.

I want to click on the new button I have added to the editor to open Angular Material Dialog.

When opening a dialog inside the new custom plugin that I have created I get the following error.

Cannot read properties of undefined (reading 'open')

to make sure that the dialog component is working fine I have added a button outside the editor and it is working fine.

please find the code sample here:

https://stackblitz.com/edit/angular-ivy-k3nguv?file=src/app/app.component.ts

Body:
Use () => {} instead function() {}.

Example:

onAction: () => {
   ...
}


问:
Add a conditional error and success message on a panel based on required input fields are filled or not. If all fields are filled,"Done" should did
I want to add a Conditional message on a panel as "Required" if the user has not filled all the required input fields, and "Done" if the user has filled all the required input fields.

Assume that there are 4 required input fields that use formik and yup for validation.

答:
```<code>
const myComp =()=>{
 const [obj,setObj]= useState()
 const [error,setError] = useState()

 // this function is used to added
 // error to error state from there
 // it will be check that error occures
 // or not
 const addError =(value)=>{
   // if it doesn't satisfies required condition
   // add error
   }

 // this function can be called on click
 // or when you want to show error or success
 const checkSuccess = ()=>{
   // if no erorr
   // show success
   // or show error
 }
 return (
  <>

  </>
 )
}
</code>```


问:
Is it possible to flatten list of lists in Ansible?
Need to flatten the array list FROM

[
    [
        [
            "10.11.33.11"
        ]
    ],
    [
        [
            "10.11.88.88"
        ]
    ]
]
```
<p>TO</p>
<pre class="lang-yaml prettyprint-override"><code>[ "10.11.33.11", "10.11.88.88" ]
</code>```

答:
I understand your question as "How to manage list variables?

Since you have list of lists,

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:
    LIST: [ [ ['10.11.33.11'] ],[ ['10.11.88.88'] ] ]

  tasks:

  - name: Show LIST flattened
    debug:
      msg: "{{ LIST | flatten(levels=2) }}"
```
<p>you need need to address the level. Resulting into an output of</p>
```TASK [Show LIST flattened] *******
ok: [localhost] =>
  msg:
  - 10.11.33.11
  - 10.11.88.88
```

Background Information

How to make a flat list out of a list of lists?

How do I flatten a list of lists/nested lists?

if someone may be interested.

Body:
Need to flatten the array list FROM

[
    [
        [
            "10.11.33.11"
        ]
    ],
    [
        [
            "10.11.88.88"
        ]
    ]
]

TO

[ "10.11.33.11", "10.11.88.88" ]

Body:
I understand your question as "How to manage list variables?

Since you have list of lists,

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:
    LIST: [ [ ['10.11.33.11'] ],[ ['10.11.88.88'] ] ]

  tasks:

  - name: Show LIST flattened
    debug:
      msg: "{{ LIST | flatten(levels=2) }}"

you need need to address the level. Resulting into an output of

TASK [Show LIST flattened] *******
ok: [localhost] =>
  msg:
  - 10.11.33.11
  - 10.11.88.88

Background Information

How to make a flat list out of a list of lists?

How do I flatten a list of lists/nested lists?

if someone may be interested.


问:
Dynamically building WHERE clauses in SQL statements
I have a question regarding SQL. I have the following SQL statement:

```<code>SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;
</code>```

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks

答:
No. Variables in SQL can refer to data, but not to object names (columns, functions or other database objects).

If you are building the SQL query, you'll need to use string operations to build your query.

Body:
I have a question regarding SQL. I have the following SQL statement:

SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks


问:
How to animate line clamp
I have a box with text. It shows only 2 lines by default and shows the whole text when the user hovers over it.
However, I have a problem animating it. The display property seems to be not animatable.

How can I animate it?

If it helps, I'm also using "framer-motion" and it's okay if you have a workaround using it.

.box {
  transition: all 0.3s ease-in-out; /* doesn't work */
}

.title {
  color: green;
  font-weight: bold;
}

.text {
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   overflow: hidden;

   transition: all 0.3s ease-in-out; /* doesn't work */
}

.box:hover .text {
   display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <span class="title">Title</span>
  <div class="text">
  Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
</div></code>```

Why it's not a duplicate question:

I want to specifically use the line-clamp (or if there's a similar property) to limit the number of lines by the number I want. I don't want to use guesses or probability!

答:
You can use opacity instead of display. and a span tag for a portion of text that you want:

.title {
  color: green;
  font-weight: bold;
}

.box {
  background: lightblue;
}

.show {
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.box:hover .show {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <span class="title">Title</span>
  <div class="text">
    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et
     <span class="show">
        suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
     </span>
  </div>
</div></code>```

Title: How to animate line clamp

Body:
I have a box with text. It shows only 2 lines by default and shows the whole text when the user hovers over it.
However, I have a problem animating it. The display property seems to be not animatable.

How can I animate it?

If it helps, I'm also using "framer-motion" and it's okay if you have a workaround using it.

.box {
  transition: all 0.3s ease-in-out; /* doesn't work */
}

.title {
  color: green;
  font-weight: bold;
}

.text {
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   overflow: hidden;

   transition: all 0.3s ease-in-out; /* doesn't work */
}

.box:hover .text {
   display: block;
}

  Title

  Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.

Why it's not a duplicate question:

I want to specifically use the line-clamp (or if there's a similar property) to limit the number of lines by the number I want. I don't want to use guesses or probability!

Body:
You can use opacity instead of display. and a span tag for a portion of text that you want:

.title {
  color: green;
  font-weight: bold;
}

.box {
  background: lightblue;
}

.show {
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.box:hover .show {
  opacity: 1;
}

<div class="box">
  <span class="title">Title</span>
  <div class="text">
    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et
     <span class="show">
        suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
     </span>
  </div>
</div>


答:
Your testing methodology is flawed. You don't use the result that you produce, so a smart optimiser may simply skip producing a result.

Would you tell me what is the point of using std::uniform_real_distribution?

The clue is in the name. It produces a uniform distribution.

Furthermore, it allows you to specify the minimum and maximum between which you want the distribution to lie.

What is the disadvantage of using 1.0*mt() / mt.max()?

You cannot specify a minimum and a maximum.

It produces a less uniform distribution.

It produces less randomness.

is it acceptable to use 1.0*mt() / mt.max() instead?

In some use cases, it could be acceptable. In some other cases, it isn't acceptable. In the rest, it won't matter.

Title: Why it is appropriate to use `std::uniform_real_distribution`?


问:
Adding a new column next to each existing column that matches a certain column name pattern in R / tidyverse
In a dataframe I want to add a new column next each column whose name matches a certain pattern, for example whose name starts with "ip_" and is followed by a number. The name of the new columns should follow the pattern "newCol_" suffixed by that number again. The values of the new columns should be NA's.

So this dataframe:

should be transformed to that dataframe:

A tidiverse solution with use of regex is much appreciated!

Sample data:

```<code>df <- data.frame(
  ID = c("1", "2"),
  ip_1 = c(2,3),
  ip_9 = c(5,7),
  ip_39 = c(11,13),
  in_1 = c("B", "D"),
  in_2 = c("A", "H"),
  in_3 = c("D", "A")
)
</code>```

答:
To add the new NA columns :

```<code>df[, sub("^ip", "newCol", grep("^ip", names(df), value = TRUE))] <- NA
</code>```

To reorder them :

```<code>df <- df[, order(c(grep("newCol", names(df), invert = TRUE), grep("^ip", names(df))))]
</code>```

edit :

If it's something you (or whoever stumble here) plan on doing often, you can use this function :

```<code>insertCol <- function(x, ind, col.names = ncol(df) + seq_along(colIndex), data = NA){
  out <- x
  out[, col.names] <- data
  out[, order(c(col(x)[1,], ind))]
}
</code>```

Body:
In a dataframe I want to add a new column next each column whose name matches a certain pattern, for example whose name starts with "ip_" and is followed by a number. The name of the new columns should follow the pattern "newCol_" suffixed by that number again. The values of the new columns should be NA's.

So this dataframe:

should be transformed to that dataframe:

A tidiverse solution with use of regex is much appreciated!

Sample data:

df <- data.frame(
  ID = c("1", "2"),
  ip_1 = c(2,3),
  ip_9 = c(5,7),
  ip_39 = c(11,13),
  in_1 = c("B", "D"),
  in_2 = c("A", "H"),
  in_3 = c("D", "A")
)

Body:
To add the new NA columns :

df[, sub("^ip", "newCol", grep("^ip", names(df), value = TRUE))] <- NA

To reorder them :

df <- df[, order(c(grep("newCol", names(df), invert = TRUE), grep("^ip", names(df))))]

edit :

If it's something you (or whoever stumble here) plan on doing often, you can use this function :

insertCol <- function(x, ind, col.names = ncol(df) + seq_along(colIndex), data = NA){
  out <- x
  out[, col.names] <- data
  out[, order(c(col(x)[1,], ind))]
}


答:
An optional solution:</p>
```<code>a="123X56XX"
b="Ahjutruu"

c = list([b[i] for i in range(len(a)) if a[i] == "X"]) # a sublist of the characters from b that correspond to "X" in a
s = set(c) # a set with the elements of c; a set has no duplicated elements, so if all of c's items are the same, s will only have one element
print(len(s) == 1)
</code>```

Body:
There is a two input first input represent the index of the second input.I need to find the 'X' position of second input are same or not?

input:

123X56XX
Ahjutruu

Output:
  True

Example:
X in input one at 4,7,8

position of 4,7,8 in second input is 'u' all are same so i need to print "true"

I tried using enumerate function but not came:

a="123X56XX"
b="Ahjutruu"
xi=[]

for i,val in enumerate(a):
  if val=='X':
    xi.append(i)
print(xi)
#next step only i dont know how to doo please help

Next i dont know how to check

Body:
An optional solution:

a="123X56XX"
b="Ahjutruu"

c = list([b[i] for i in range(len(a)) if a[i] == "X"]) # a sublist of the characters from b that correspond to "X" in a
s = set(c) # a set with the elements of c; a set has no duplicated elements, so if all of c's items are the same, s will only have one element
print(len(s) == 1)


问:
Splitting an array into sequential groups
I have an array with elements [2, 3, 4, 5, 6, 7, 8, 9, 10, ...]. I wish to split this up as follows: [[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], ...]. I am not sure how to do this because the elements in each split must be repeated, and I am unsure of how to create these repeated elements. Any help will be much appreciated.

答:
You can use zip() to create 3-tuples, and then use list() to transform the resulting tuples into lists.

data = [2, 3, 4, 5, 6, 7, 8, 9, 10]

# Prints [[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]
print(list(list(item) for item in zip(data, data[1:], data[2:])))
```


问:
Exiftool::ExiftoolNotInstalled (Exiftool::ExiftoolNotInstalled) after being installed
I'm trying to run a ruby script where I used the exiftool gem, and everytime I'm trying to run it I keep getting this error even after installed it. Also, after running bundler as well.

```<code>Traceback (most recent call last):
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/exiftool-1.2.4/lib/exiftool.rb:60:in `initialize': Exiftool::ExiftoolNotInstalled (Exiftool::ExiftoolNotInstalled)
</code>```

Also, it is running on my cmd. I tried testing it using the irb and the Exiftool isn't being recognized by ruby.

答:
I'm maintainer of the exiftool.rb and exiftool_vendored.rb repos. @Zeragamba is correct that gem doesn't support Windows environments. The need for running it on Windows hasn't been brought up to our attention in the past 10 years. I've looked at the issue and cut a separate branch that should work with Windows, however I'm not planning to fully support Windows unless there is an overwhelming demand. There are a few gotchas related to implementing Windows support and I'm not sure if it's worth the time and effort to solve them at this point.

Couple of things that you would need to do to get it working:

If installed, remove exiftool_vendored.rb gem from your Windows system - it installs perl version of the exiftool from Phil Harvey.

Make sure that you are able to run git client commands in your PowerShell prompt

I've tested the following setup on Windows 10 and ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x64-mingw32]

Download and install Windows executable from Phil Harvey's Exiftool site make sure that exiftool is in your PATH and can be executed in the PowerShell

Create following Gemfile:

```<code>source 'https://rubygems.org'
gem 'exiftool', github: 'exiftool-rb/exiftool.rb', branch: 'win_support'
</code>```

Run bundle install to get exiftool from that branch.

Create a test.rb file to test test the installation:

```<code>require 'exiftool'

puts "Exiftool command: #{Exiftool.command}"
puts "Is Exiftool Installed?: #{Exiftool.exiftool_installed?}"
puts "Exiftool version: #{Exiftool.exiftool_version}"

</code>```

After running it you should get something along these lines:

```<code>PS C:\Users\sergey>ruby .\test.rb
Exiftool command: exiftool
Is Exiftool Installed?: true
Exiftool version: 12.40
</code>```

Once again please keep in mind that this isn't an official version that supports Windows environment. Feel free to open an issue on the github if you strongly feel that gem needs to support Windows environments, PRs are always welcome as well.

Thanks.

Body:
I'm trying to run a ruby script where I used the exiftool gem, and everytime I'm trying to run it I keep getting this error even after installed it. Also, after running bundler as well.

Traceback (most recent call last):
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/exiftool-1.2.4/lib/exiftool.rb:60:in `initialize': Exiftool::ExiftoolNotInstalled (Exiftool::ExiftoolNotInstalled)

Also, it is running on my cmd. I tried testing it using the irb and the Exiftool isn't being recognized by ruby.

Body:
I'm maintainer of the exiftool.rb and exiftool_vendored.rb repos. @Zeragamba is correct that gem doesn't support Windows environments. The need for running it on Windows hasn't been brought up to our attention in the past 10 years. I've looked at the issue and cut a separate branch that should work with Windows, however I'm not planning to fully support Windows unless there is an overwhelming demand. There are a few gotchas related to implementing Windows support and I'm not sure if it's worth the time and effort to solve them at this point.

Couple of things that you would need to do to get it working:

If installed, remove exiftool_vendored.rb gem from your Windows system - it installs perl version of the exiftool from Phil Harvey.

Make sure that you are able to run git client commands in your PowerShell prompt

I've tested the following setup on Windows 10 and ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x64-mingw32]

Download and install Windows executable from Phil Harvey's Exiftool site make sure that exiftool is in your PATH and can be executed in the PowerShell

Create following Gemfile:

source 'https://rubygems.org'
gem 'exiftool', github: 'exiftool-rb/exiftool.rb', branch: 'win_support'

Run bundle install to get exiftool from that branch.

Create a test.rb file to test test the installation:

require 'exiftool'

puts "Exiftool command: #{Exiftool.command}"
puts "Is Exiftool Installed?: #{Exiftool.exiftool_installed?}"
puts "Exiftool version: #{Exiftool.exiftool_version}"

After running it you should get something along these lines:

PS C:\Users\sergey>ruby .\test.rb
Exiftool command: exiftool
Is Exiftool Installed?: true
Exiftool version: 12.40

Once again please keep in mind that this isn't an official version that supports Windows environment. Feel free to open an issue on the github if you strongly feel that gem needs to support Windows environments, PRs are always welcome as well.

Thanks.


问:
It is difficult to understand the debugging step over of eclipse
Why can't the variable hallLamp be displayed?</p>

答: Always add breakpoint on a next line after initialization of an object. In your case either step over to the next line or add breakpoint at line number 22.</p>


问:
How to change excel timestamp format ? Format change but date is not correct
```<code>$my = '13/02/2022 21:29:30';
$converted = date('d M Y h.i.s A', strtotime($my));
$reversed = date('d-m-Y H:i:s', strtotime($converted));
echo $reversed;
</code>```

// output
01-01-1970 00:00:00

but I want a correct date

答:
you can use several solution .

solution #1

```<code>$var = '20/04/2012 21:29:30';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));
</code>```

solution #2

```<code>$old_date = explode('/', '5/4/2010');
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];
</code>```

solution #3

```<code>$var = '20/04/2012';
echo implode("-", array_reverse(explode("/", $var)));
</code>```

Body:
$my = '13/02/2022 21:29:30';
$converted = date('d M Y h.i.s A', strtotime($my));
$reversed = date('d-m-Y H:i:s', strtotime($converted));
echo $reversed;

// output
01-01-1970 00:00:00

but I want a correct date

Body:
you can use several solution .

solution #1

$var = '20/04/2012 21:29:30';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));

solution #2

$old_date = explode('/', '5/4/2010');
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];

solution #3

$var = '20/04/2012';
echo implode("-", array_reverse(explode("/", $var)));


问:
Laravel - Middleware custom typed Request parameter
I want to use VacancyListRequest to pass through middleware parameters and use its rules to validate them before controller action. I know that middleware acts Pipeline pattern, but does anybody know how to use any custom type except default \Illuminate\Http\Request?

Middleware

```<code>public function handle(VacancyListRequest $request, Closure $next)
{
    $request = $this->analizeQuery($request);
    $request = $this->formatValues($request);
    $request = $this->prepareParams($request);

    return $next($request);
}
</code>```

Controller

```<code> public function index(VacancyListRequest $request, bool $asQuery = false)
</code>```

Error

App\Http\Middleware\Vacancy\BeforeVacancyIndexRequestMiddleware::handle():
Argument #1 ($request) must be of type
App\Http\Requests\Vacancy\VacancyListRequest, Illuminate\Http\Request
given,

答:
You are getting that error because you are passing the $request as argument of the handle method of you middleware which is typed as VacancyListRequest instead of being of type Illuminate\Http\Request.

You should change the middleware to be like this

```<code>use Illuminate\Http\Request;
use Closure;

class VacancyListRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $request = $this->analizeQuery($request);
        $request = $this->formatValues($request);
        $request = $this->prepareParams($request);

        return $next($request);
    }
}
</code>```

But in your controller It should be like this

```<code>// At the top of you controller file you add this
use App\Http\Requests\Vacancy\VacancyListRequest;

// And define the controller method like this
public function index(VacancyListRequest $request, bool $asQuery = false)
</code>```

It's a must for the first parameter of the handle method to be of type \Illuminate\Http\Request like it defined in the docs # Defining Middleware

Body:
I want to use VacancyListRequest to pass through middleware parameters and use its rules to validate them before controller action. I know that middleware acts Pipeline pattern, but does anybody know how to use any custom type except default \Illuminate\Http\Request?

Middleware

public function handle(VacancyListRequest $request, Closure $next)
{
    $request = $this->analizeQuery($request);
    $request = $this->formatValues($request);
    $request = $this->prepareParams($request);

    return $next($request);
}

Controller

 public function index(VacancyListRequest $request, bool $asQuery = false)

Error

App\Http\Middleware\Vacancy\BeforeVacancyIndexRequestMiddleware::handle():
Argument #1 ($request) must be of type
App\Http\Requests\Vacancy\VacancyListRequest, Illuminate\Http\Request
given,

Body:
You are getting that error because you are passing the $request as argument of the handle method of you middleware which is typed as VacancyListRequest instead of being of type Illuminate\Http\Request.

You should change the middleware to be like this

use Illuminate\Http\Request;
use Closure;

class VacancyListRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $request = $this->analizeQuery($request);
        $request = $this->formatValues($request);
        $request = $this->prepareParams($request);

        return $next($request);
    }
}

But in your controller It should be like this

// At the top of you controller file you add this
use App\Http\Requests\Vacancy\VacancyListRequest;

// And define the controller method like this
public function index(VacancyListRequest $request, bool $asQuery = false)

It's a must for the first parameter of the handle method to be of type \Illuminate\Http\Request like it defined in the docs # Defining Middleware


问:
API for username password keychain dialog in Mac
Is there an API that we can use that displays the usual username field, password field, and  remember checkbox? This dialog can be usually seen when connecting to a server via Finder or when Safari requests for proxy information.

I am currently implementing this via CFUserNotification API to save myself from creating a window, etc. but I have to specify the fields and checkbox and retrieve them. What would really save time is an API that will abstract developers from having to worry about it. Does such API exist?

答:
I don't think so. Actually I don't have an idea why apple should deploy an api for such a small task.

That's only a NSSecureTextField and a NSTextField. There are plenty of classes that help you add a password properly to the keychain.


问:
How to add extra key in created object in Django Rest Framework?
I'm new to Django

Currently I'm trying to add a simple extra key on my returned json in the serializer. Here's the create() override of my serializer:

```<code>    def create(self, validated_data):
        available_dates = validated_data.pop("available_dates")

        # Default expiry time is 3 days
        expiry = datetime.datetime.now() + datetime.timedelta(days=3)
        event = Events.objects.create(**validated_data, expiry=expiry)
        for selectedTime in available_dates:
            AvailableDates.objects.create(
                event=event,
                **selectedTime,
            )

        signer = Signer()
        signedObject = signer.sign_object(
            {"expiry": expiry.isoformat(), "id": event.id}
        )

        return {**event, "signed_url": signedObject}

</code>```

As you can see, I don't want to only return event, but I want to add a signed url.

This gave me an error:
'Events' object is not a mapping

So then how do I add extra key? What do I return in the create function? Can I create Response() as the return of create function in DRF?

答:
The .create() method of serializers need to return the instance that was created. After a successful create, it is used as the instance for the serializer when accessing serializer.data (Like how its used in a retrieve api)

As for adding a signed_url, you can add it in a field in your serializer, like:

```<code>class EventSerializer(ModelSerializer):
   # other fields ...
   signed_url = SerializerMethodField()

   class Meta:
       model = Event
       fields = [
           # other fields ...
           "signed_url",
       ]

   def create(self, validated_data):
        available_dates = validated_data.pop("available_dates")

        # Default expiry time is 3 days
        expiry = datetime.datetime.now() + datetime.timedelta(days=3)
        event = Events.objects.create(**validated_data, expiry=expiry)
        for selectedTime in available_dates:
            AvailableDates.objects.create(
                event=event,
                **selectedTime,
            )

        signer = Signer()
        signedObject = signer.sign_object(
            {"expiry": expiry.isoformat(), "id": event.id}
        )
        event.signedObject = signedObject

        return event
    def get_signed_url(self,obj):
         if not hasattr(obj, "signedObject"):
             return None
         # you can add other code here if you need to do something else with signedObject
         return obj.signedObject

</code>```

There are other ways to do it. But the one above might do it based on the code provided.

Body:
I'm new to Django

Currently I'm trying to add a simple extra key on my returned json in the serializer. Here's the create() override of my serializer:

    def create(self, validated_data):
        available_dates = validated_data.pop("available_dates")

        # Default expiry time is 3 days
        expiry = datetime.datetime.now() + datetime.timedelta(days=3)
        event = Events.objects.create(**validated_data, expiry=expiry)
        for selectedTime in available_dates:
            AvailableDates.objects.create(
                event=event,
                **selectedTime,
            )

        signer = Signer()
        signedObject = signer.sign_object(
            {"expiry": expiry.isoformat(), "id": event.id}
        )

        return {**event, "signed_url": signedObject}

As you can see, I don't want to only return event, but I want to add a signed url.

This gave me an error:
'Events' object is not a mapping

So then how do I add extra key? What do I return in the create function? Can I create Response() as the return of create function in DRF?

Body:
The .create() method of serializers need to return the instance that was created. After a successful create, it is used as the instance for the serializer when accessing serializer.data (Like how its used in a retrieve api)

As for adding a signed_url, you can add it in a field in your serializer, like:

class EventSerializer(ModelSerializer):
   # other fields ...
   signed_url = SerializerMethodField()

   class Meta:
       model = Event
       fields = [
           # other fields ...
           "signed_url",
       ]

   def create(self, validated_data):
        available_dates = validated_data.pop("available_dates")

        # Default expiry time is 3 days
        expiry = datetime.datetime.now() + datetime.timedelta(days=3)
        event = Events.objects.create(**validated_data, expiry=expiry)
        for selectedTime in available_dates:
            AvailableDates.objects.create(
                event=event,
                **selectedTime,
            )

        signer = Signer()
        signedObject = signer.sign_object(
            {"expiry": expiry.isoformat(), "id": event.id}
        )
        event.signedObject = signedObject

        return event
    def get_signed_url(self,obj):
         if not hasattr(obj, "signedObject"):
             return None
         # you can add other code here if you need to do something else with signedObject
         return obj.signedObject

There are other ways to do it. But the one above might do it based on the code provided.


问:
Discord JS stop collector when ephemeral message is dismissed
I have a message component collector that waits for an input from a MessageButton within an interaction reply, but the message is ephemeral so if the message is dismissed the collector stays open, despite there being no buttons for the user to press.

```<code>const abConfirmRow = new Discord.MessageActionRow()
.addComponents([
  new Discord.MessageButton()
    .setCustomId(abConfirmID)
    .setLabel('Yes')
    .setStyle('SUCCESS'),
  new Discord.MessageButton()
    .setCustomId(abCancelID)
    .setLabel('No')
    .setStyle('DANGER'),
]);

await interaction.reply({ content: confirmMessage, embeds: [{
  description: msgEmbed.description,
  image: msgEmbed.image,
}], components: [abConfirmRow], ephemeral: true });

const filter = button => (button.customId === abConfirmID || button.customId === abCancelID) && button.user.id === interaction.member.id;
const collector = interaction.channel.createMessageComponentCollector({ filter, time: 30000 });
</code>```

I have looked through the documentation and on various sites and can't seem to find any sort of "on dismissed" event listener.

答:
Actually, the collector will still timeout if the user dismisses the message/interaction. One thing that may help (as I am struggling with this exact problem), is to use idle instead of time. time is absolute; starting at the beginning of the interaction, regardless of how much time is spent with each interaction. idle, however is interaction to interaction.

So, my workaround for this is to set idle to 10-15 seconds (or whatever suits you). At least then, the collector will time out faster than waiting for the full time to run out. It's not ideal, some kind of event on dismissal would be nice, but it is workable. I don't use time at all.

For example:

const collector = interaction.channel.createMessageComponentCollector({ filter, idle: 10000 });

Then, just catch the idle reason in the end event:

```<code>collector.on('end', (collected, reason) => {
    if (reason === 'complete') {
        // ...
    } else if (reason === 'idle') {
        // ...
    }
});
</code>```

Hope this helps until we can find a better answer.

Body:
I have a message component collector that waits for an input from a MessageButton within an interaction reply, but the message is ephemeral so if the message is dismissed the collector stays open, despite there being no buttons for the user to press.

const abConfirmRow = new Discord.MessageActionRow()
.addComponents([
  new Discord.MessageButton()
    .setCustomId(abConfirmID)
    .setLabel('Yes')
    .setStyle('SUCCESS'),
  new Discord.MessageButton()
    .setCustomId(abCancelID)
    .setLabel('No')
    .setStyle('DANGER'),
]);

await interaction.reply({ content: confirmMessage, embeds: [{
  description: msgEmbed.description,
  image: msgEmbed.image,
}], components: [abConfirmRow], ephemeral: true });

const filter = button => (button.customId === abConfirmID || button.customId === abCancelID) && button.user.id === interaction.member.id;
const collector = interaction.channel.createMessageComponentCollector({ filter, time: 30000 });

I have looked through the documentation and on various sites and can't seem to find any sort of "on dismissed" event listener.

Body:
Actually, the collector will still timeout if the user dismisses the message/interaction. One thing that may help (as I am struggling with this exact problem), is to use idle instead of time. time is absolute; starting at the beginning of the interaction, regardless of how much time is spent with each interaction. idle, however is interaction to interaction.

So, my workaround for this is to set idle to 10-15 seconds (or whatever suits you). At least then, the collector will time out faster than waiting for the full time to run out. It's not ideal, some kind of event on dismissal would be nice, but it is workable. I don't use time at all.

For example:

const collector = interaction.channel.createMessageComponentCollector({ filter, idle: 10000 });

Then, just catch the idle reason in the end event:

collector.on('end', (collected, reason) => {
    if (reason === 'complete') {
        // ...
    } else if (reason === 'idle') {
        // ...
    }
});

Hope this helps until we can find a better answer.


Title: Splitting an array into sequential groups

Body: I have an array with elements [2, 3, 4, 5, 6, 7, 8, 9, 10, ...]. I wish to split this up as follows: [[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], ...]. I am not sure how to do this because the elements in each split must be repeated, and I am unsure of how to create these repeated elements. Any help will be much appreciated.

Body:
Use a comprehension:

N = 3
l = [2, 3, 4, 5, 6, 7, 8, 9, 10]

ll = [l[i:i+N] for i in range(len(l)-N+1)]

Output:

>>> ll
[[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]


问:
Scrape URL's beyond the first page of search results using R
Please note, I am aware that there are many web-scraping questions and answers already posted, but I have not been able to solve my problem after reading them.

I have tried reading the following but haven't had success:

Scraping a webpage with R but 'next page' button only has event 'go to top'

Webscraping in R: How to follow a "next" button and scrape the page?

Web scraping search results using R

and several others but I have not been successful for the site I am trying to scrape.

I would like to scrape the URLs from the following search result:

http://www.vch.ca/locations-services?search_term=public,health

By analyzing the links that appear in the "Name" column, I am able to extract the URL's on the first page using the followng:

```<code>library(rvest)
webpage = read_html("http://www.vch.ca/locations-services?search_term=public,health")

> extracted_urls = webpage %>%
   rvest::html_nodes("a") %>%
   rvest::html_attr("href")
> extracted_urls = extracted_urls[grep("?ID=", extracted_urls)]
> extracted_urls
[1] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=423"
[2] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=98"
.
.
.
[50] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=493"
</code>```

The issue is there is a next button on the bottom and I am not able to access subsequent pages of results beyond the first page.

I have tried looking for patterns in the URL's of page 1, 2, 3 etc. but that was not successful for scraping.

I have tried reading other questions and answers related to scraping using R on stack overflow, but I have not been successful.

Can someone please let me know how to scrape beyond the first page of search results from this search result please?

答:
There is pattern fir url of pages from page2 to page6 (there are total of 6 pages).

```<code>page2 =     http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A51%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D
page3 =    http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A101%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D
page4 =    http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A151%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D
page5 =      http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A201%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D
page6 =      http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A251%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D
</code>```

You can see for each page only change in A51, A100, A150 etc.. which is the starting id of search result.

We can create these url by,

```<code>len =  seq(from = 51, to = 300, by = 50)
[1]  51 101 151 201 251

url = paste0('http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A', len, '%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D')

[1] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A51%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"
[2] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A101%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"
[3] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A151%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"
[4] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A201%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"
[5] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A251%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"
</code>```

Now get links from page2 to page 6 using for loop,

```<code>#create empty vector
links = c()
#now get links
for(i in url){
webpage = read_html(i)
extracted_urls = webpage %>%
  rvest::html_nodes("a") %>%
  rvest::html_attr("href")
extracted_urls = extracted_urls[grep("?ID=", extracted_urls)]
links = c(extracted_urls, links)
}
head(links)
[1] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=423"
[2] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=98"
[3] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=399"
[4] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=400"
[5] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=398"
[6] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=700"
</code>```

Body:
Please note, I am aware that there are many web-scraping questions and answers already posted, but I have not been able to solve my problem after reading them.

I have tried reading the following but haven't had success:

Scraping a webpage with R but 'next page' button only has event 'go to top'

Webscraping in R: How to follow a "next" button and scrape the page?

Web scraping search results using R

and several others but I have not been successful for the site I am trying to scrape.

I would like to scrape the URLs from the following search result:

http://www.vch.ca/locations-services?search_term=public,health

By analyzing the links that appear in the "Name" column, I am able to extract the URL's on the first page using the followng:

library(rvest)
webpage = read_html("http://www.vch.ca/locations-services?search_term=public,health")

> extracted_urls = webpage %>%
   rvest::html_nodes("a") %>%
   rvest::html_attr("href")
> extracted_urls = extracted_urls[grep("?ID=", extracted_urls)]
> extracted_urls
[1] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=423"
[2] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=98"
.
.
.
[50] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=493"

The issue is there is a next button on the bottom and I am not able to access subsequent pages of results beyond the first page.

I have tried looking for patterns in the URL's of page 1, 2, 3 etc. but that was not successful for scraping.

I have tried reading other questions and answers related to scraping using R on stack overflow, but I have not been successful.

Can someone please let me know how to scrape beyond the first page of search results from this search result please?

Body:
There is pattern fir url of pages from page2 to page6 (there are total of 6 pages).

page2 =     http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A51%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D
page3 =    http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A101%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D
page4 =    http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A151%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D
page5 =      http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A201%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D
page6 =      http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A251%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D

You can see for each page only change in A51, A100, A150 etc.. which is the starting id of search result.

We can create these url by,

len =  seq(from = 51, to = 300, by = 50)
[1]  51 101 151 201 251

url = paste0('http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A', len, '%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D')

[1] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A51%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"
[2] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A101%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"
[3] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A151%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"
[4] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A201%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"
[5] "http://www.vch.ca/locations-services?search_term=public,health#Default=%7B%22k%22%3A%22%22%2C%22s%22%3A251%7D#05e2c815-e21d-4437-af2a-b351f72590d5=%7B%22k%22%3A%22%22%7D"

Now get links from page2 to page 6 using for loop,

#create empty vector
links = c()
#now get links
for(i in url){
webpage = read_html(i)
extracted_urls = webpage %>%
  rvest::html_nodes("a") %>%
  rvest::html_attr("href")
extracted_urls = extracted_urls[grep("?ID=", extracted_urls)]
links = c(extracted_urls, links)
}
head(links)
[1] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=423"
[2] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=98"
[3] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=399"
[4] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=400"
[5] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=398"
[6] "http://www.vch.ca/Lists/Locations and Services/DispForm.aspx?ID=700"


问:
android garbage collector, freeing objects inside objects
I'm very curious about how this thing works inside Android. I have a class with two List<> inside, instantiated at runtime and loaded with objects created while reading some data, I want to know what happens with those Lists in this situation:

Class A has List B and List C with many other initialized objects
inside.

Another different class get a reference of List C from a
method of Class A, like  public List<myObject> GetList().

Somewhere in code, Class A is no longer used and application
signals that to garbage collector, setting object to null.

What happens with my List C that is referenced by other object?  What happens with Object class A?

I've tried to track garbage collector with Logcat running apk in debugger step-by-step but no luck at all. Sometimes it frees memory, sometimes not, I couldn't pinpoint any specific behaviour.

答:
If there is any object, that still has a path to root, containing a reference to another object, the referenced object will not be garbage collected.  So if you create object A, that has a sub object A1.  Then create object B and through what ever means pass a reference to A1 to object B.  Even when object A is GC'd A1 will not be because object B still holds a reference.  (In your example, A & B will be gc'd... C will not)

You can experiment with the mechanics behind garbage collection by telling the system explicitly to perform a collection at certain times with a System.gc(); call.  Also you can override the finalize in object to see exactly when the given object is collected.:

```<code>   @Override
   protected void finalize() throws Throwable {
      try {
         Log.d("Learning about GC", "My Object has been GC'd." + this);
      } finally {
         super.finalize();
      }
   }
</code>```

You can learn a lot through experimenting with objects, references, finalize and explicit calls for gc().  I would remove the overridden finalize call when you done testing.

Body:
If there is any object, that still has a path to root, containing a reference to another object, the referenced object will not be garbage collected.  So if you create object A, that has a sub object A1.  Then create object B and through what ever means pass a reference to A1 to object B.  Even when object A is GC'd A1 will not be because object B still holds a reference.  (In your example, A & B will be gc'd... C will not)

You can experiment with the mechanics behind garbage collection by telling the system explicitly to perform a collection at certain times with a System.gc(); call.  Also you can override the finalize in object to see exactly when the given object is collected.:

   @Override
   protected void finalize() throws Throwable {
      try {
         Log.d("Learning about GC", "My Object has been GC'd." + this);
      } finally {
         super.finalize();
      }
   }

You can learn a lot through experimenting with objects, references, finalize and explicit calls for gc().  I would remove the overridden finalize call when you done testing.


问:
Missing firebase_options.dart file in course "Get to know Firebase for Flutter"
I am using the flutter course "Get to know Firebase for Flutter" from https://firebase.google.com/codelabs/firebase-get-to-know-flutter#4.

I am in step_02 and I have added the following recommended code from stage 5.

```<code>
import 'package:firebase_auth/firebase_auth.dart'; // new
import 'package:firebase_core/firebase_core.dart'; // new
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';           // new

import 'firebase_options.dart';                    // new
import 'src/authentication.dart';                  // new
import 'src/widgets.dart';
</code>```

Later in this stage there is a Test it section.  However it fails because there is no firebase_options.dart file. How do I generate this file.

Thank you.

答: Solved this by removing my existing Firebase project and creating a new one, disabling Google Analytics.</p>

Body:
I am using the flutter course "Get to know Firebase for Flutter" from https://firebase.google.com/codelabs/firebase-get-to-know-flutter#4.

I am in step_02 and I have added the following recommended code from stage 5.

import 'package:firebase_auth/firebase_auth.dart'; // new
import 'package:firebase_core/firebase_core.dart'; // new
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';           // new

import 'firebase_options.dart';                    // new
import 'src/authentication.dart';                  // new
import 'src/widgets.dart';

Later in this stage there is a Test it section.  However it fails because there is no firebase_options.dart file. How do I generate this file.

Thank you.