问:
I can't make the download progress bar from tqdm to show the progress
I want to add a download progress bar with tqdm. The problem is that it shows me this :

0%|                                                                           | 0/11535.92578125 [00:00<?, ?KB/s]
```

<p>And it downloads the file without showing a any progress. Here is my code:</p>

```s = requests.Session()
r = s.post(url, login_data)
response = s.get(link_to_pdf, stream=True)
total_size = int(response.headers['content-length'])
# download the pdf
print(pdf_filename)
with open(pdf_filename + '.pdf', 'wb') as f:
    for data in tqdm(iterable=response.iter_content(chunk_size=chunk_size), total=total_size/chunk_size, unit='KB'):
        f.write(response.content)
```

答:
you did not write the data you write the request in 1 time not in chunks, jsut replace response.content that you write to file in the data chink you got from tqdm</p>

```<code>  with open(pdf_filename + '.pdf', 'wb') as f:
    for data in tqdm(iterable=response.iter_content(chunk_size=chunk_size), total=total_size / chunk_size, unit='KB'):
        f.write(data)
</code>```

Body:
I want to add a download progress bar with tqdm. The problem is that it shows me this :

0%|                                                                           | 0/11535.92578125 [00:00<?, ?KB/s]

And it downloads the file without showing a any progress. Here is my code:

s = requests.Session()
r = s.post(url, login_data)
response = s.get(link_to_pdf, stream=True)
total_size = int(response.headers['content-length'])
# download the pdf
print(pdf_filename)
with open(pdf_filename + '.pdf', 'wb') as f:
    for data in tqdm(iterable=response.iter_content(chunk_size=chunk_size), total=total_size/chunk_size, unit='KB'):
        f.write(response.content)

Body:
you did not write the data you write the request in 1 time not in chunks, jsut replace response.content that you write to file in the data chink you got from tqdm

  with open(pdf_filename + '.pdf', 'wb') as f:
    for data in tqdm(iterable=response.iter_content(chunk_size=chunk_size), total=total_size / chunk_size, unit='KB'):
        f.write(data)


来源: stackexchange

问:
Average timediff of 2nd and 3rd datetimes for a group
I need to find the average time in days between a customer's second order and third order

I know that I need to use the timestampdiff but am quite at a loss for how to select the second and third dates and need some sort of nest.

```<code>SELECT CustomerID,
       OrderDate,
       diff,
       avg(timestampdiff(day, start_date, end_date)) AS average_days
    FROM () o3
   WHERE date3, date2
ORDER BY CustomerID, OrderDate;
</code>```

Table

答:
To achieve your desired result, you first need to calculate ROW_NUMBER from your data PARTITION BY CustmerId. Then keep rows only with RowNumber IN (2,3) and then get the DateDiff between two days. The following query will help getting your desired results-</p>

```<code>SELECT CustomerID,datediff(MAX(OrderDate),MIN(OrderDate))
FROM
(
    SELECT *,
    @row_num :=IF(@prev_value = concat_ws('',CsutomerID),@row_num+1,1)AS RowNumber
    , @prev_value := concat_ws('',CsutomerID)
    FROM your_table A
    ORDER BY CustomerID,OrderDate
)B
WHERE B.RowNumber IN (2,3)
GROUP BY CustomerID;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to find the average time in days between a customer's second order and third order

I know that I need to use the timestampdiff but am quite at a loss for how to select the second and third dates and need some sort of nest.

SELECT CustomerID,
       OrderDate,
       diff,
       avg(timestampdiff(day, start_date, end_date)) AS average_days
    FROM () o3
   WHERE date3, date2
ORDER BY CustomerID, OrderDate;

Table

Body:
To achieve your desired result, you first need to calculate ROW_NUMBER from your data PARTITION BY CustmerId. Then keep rows only with RowNumber IN (2,3) and then get the DateDiff between two days. The following query will help getting your desired results-

SELECT CustomerID,datediff(MAX(OrderDate),MIN(OrderDate))
FROM
(
    SELECT *,
    @row_num :=IF(@prev_value = concat_ws('',CsutomerID),@row_num+1,1)AS RowNumber
    , @prev_value := concat_ws('',CsutomerID)
    FROM your_table A
    ORDER BY CustomerID,OrderDate
)B
WHERE B.RowNumber IN (2,3)
GROUP BY CustomerID;


问:
How to load certain aspect of json file to rdd easily
I have a json file with over a million rows, so I am trying to minimize the number of times I have to run through it all to get one aspect of it into an rdd.

Right now, I load each row into a list:

```<code>with open('in/json-files/sites.json') as f:
        for line in f:
            data.append(json.loads(line))
</code>```

Then, I make another list and import the aspect into that:

```<code>for line in range(1,len(data)):
        data_companies.append(data[line]['company'])
</code>```

Then, I parallelize this into an rdd so that I can analyze it. I am worried about how much memory this will take up, so is there an easier and faster way to do this? I have tried loading the json file like this, but it wont work:

```<code>data.append(json.loads(line['company'))
</code>```

答:
As your data is structured(JSON), you can look into Spark-SQL

https://spark.apache.org/docs/2.4.0/sql-programming-guide.html

https://spark.apache.org/docs/2.4.0/sql-data-sources-json.html

You can directly load your JSON into a dataframe and look for the particular column to do your analysis

Body:
I have a json file with over a million rows, so I am trying to minimize the number of times I have to run through it all to get one aspect of it into an rdd.

Right now, I load each row into a list:

with open('in/json-files/sites.json') as f:
        for line in f:
            data.append(json.loads(line))

Then, I make another list and import the aspect into that:

for line in range(1,len(data)):
        data_companies.append(data[line]['company'])

Then, I parallelize this into an rdd so that I can analyze it. I am worried about how much memory this will take up, so is there an easier and faster way to do this? I have tried loading the json file like this, but it wont work:

data.append(json.loads(line['company'))


问:
How to add custom css in ng2-smart-table
I am using angular 2 with ng2-smart-table.

Here is my code.

```<code>settings = {
    mode:"external",
    actions:{add:false,position:'right',custom: [{ name: 'View', title: `<i class="fa fa-eye" aria-hidden="true"></i>` }]},
    edit: {
      editButtonContent: '<i class="fa fa-pencil-square" aria-hidden="true"></i>',
      saveButtonContent: '<i class="ion-checkmark"></i>',
      cancelButtonContent:'<i class="ion-close"></i>',
    },
    delete: {
      deleteButtonContent: '<i class="fa fa-trash" aria-hidden="true"></i>',
      confirmDelete: true
    },
    columns: {
       Check:{
        title: "Check",
        type: 'html',
        },
        filter: false
       },
       orderby:{
        title: "Name",
        filter: true
       },
       purchased:{
        title: "Purchased",
        type: 'html',
        },
        filter: false
       },
       shipto:{
        title: "Ship To",
        filter: true
       },
       date:{
        title: "Date",
        filter: true
       },
       total:{
        title: "Total Amount",
        filter: true
       },
       status: {
        title: "Status",
        filter: true
      }
    }
  };
</code>```

I added custom view icon in table. It works, but how to add custom css in ng2-smart-table?

I tried this

```<code> ng2-smart-table thead > tr > th { background-color: blue; }
</code>```

But it doesn't work.

答:
You should use ::ng-deep

::ng-deep ng2-smart-table thead > tr > th { background-color: blue; }

ContentLicense: CC BY-SA 3.0

Body:
I am using angular 2 with ng2-smart-table.

Here is my code.

settings = {
    mode:"external",
    actions:{add:false,position:'right',custom: [{ name: 'View', title: `<i class="fa fa-eye" aria-hidden="true"></i>` }]},
    edit: {
      editButtonContent: '',
      saveButtonContent: '',
      cancelButtonContent:'',
    },
    delete: {
      deleteButtonContent: '',
      confirmDelete: true
    },
    columns: {
       Check:{
        title: "Check",
        type: 'html',
        },
        filter: false
       },
       orderby:{
        title: "Name",
        filter: true
       },
       purchased:{
        title: "Purchased",
        type: 'html',
        },
        filter: false
       },
       shipto:{
        title: "Ship To",
        filter: true
       },
       date:{
        title: "Date",
        filter: true
       },
       total:{
        title: "Total Amount",
        filter: true
       },
       status: {
        title: "Status",
        filter: true
      }
    }
  };

I added custom view icon in table. It works, but how to add custom css in ng2-smart-table?

I tried this

 ng2-smart-table thead > tr > th { background-color: blue; }

But it doesn't work.


问:
Extracting the dimensions of a rectangle
So I'm working on an image processing project with sonar images. To be more specific, I am trying to extract the dimensions of an image of a pool taken by a sonar scanner. I was able to extract the rectangular region of the pool but I can not figure out how to get the dimensions of each edge in terms of pixels. I am working with OpenCV in Python.

I would appreciate if anyone would give me any suggestion on how this could be done.

I already tried finding the line intersections of hough lines but that did not have promising results.

Code so far.

import cv2
import numpy as np
from scipy import ndimage as ndi
from scipy.ndimage.measurements import label

def largest_component(indices):
    #this function takes a list of indices denoting
    #the white regions of the image and returns the largest
    #white object of connected indices

    return_arr = np.zeros((512,512), dtype=np.uint8)
    for index in indeces:
        return_arr[index[0]][index[1]] = 255

    return return_arr

image = cv2.imread('sonar_dataset/useful/sonarXY_5.bmp', 0)
image_gaussian = ndi.gaussian_filter(image, 4)
image_gaussian_inv = cv2.bitwise_not(image_gaussian)
kernel = np.ones((3,3),np.uint8)

# double thresholding extracting the sides of the rectangle
ret1, img1 = cv2.threshold(image_gaussian_inv, 120, 255, cv2.THRESH_BINARY)
ret2, img2 = cv2.threshold(image_gaussian_inv, 150, 255, cv2.THRESH_BINARY)

double_threshold = img1 - img2
closing = cv2.morphologyEx(double_threshold, cv2.MORPH_CLOSE, kernel1)

labeled, ncomponents = label(closing, kernel)
indices = np.indices(closing.shape).T[:,:,[1, 0]]
twos = indices[labeled == 2]
area =[np.sum(labeled==val) for val in range(ncomponents+1)]

rectangle = largest_component(twos)

cv2.imshow('rectangle', rectangle)
cv2.waitKey(0)
```

The original image and extracted object are below.

答:
There are already two good solutions, I wanted to propose a simpler one based on a different way of detecting the rectangle.

(I'm using MATLAB with DIPimage here, because that's quicker for me to toss a proof of concept together than Python, but the same exact functionality is available in Python, see at the end of the post. Disclaimer: I'm an author of DIPimage.)

Because the rectangle is a bright shape on a darker background, and is (I presume) guaranteed to surround the center of the image, we can generate a seed in the center of the image and a seed in the periphery, and use the watershed to find the rectangle. The watershed is guaranteed, in this case, to produce a single, 1-pixel thick, closed contour.

img = readim('https://i.stack.imgur.com/no8BP.png');
seeds = clone(img);
seeds(rr(seeds)<50) = 1;
seeds(rr(seeds)>250) = 2;
rect = waterseed(seeds,gaussf(img));
overlay(img,rect) % for display only
```
<p><img src="https://i.stack.imgur.com/JzgLv.png" alt="OP's image with a red rectangle drawn over the rectangle to be detected" /></p>
<p>Note that I smoothed the input image a bit. But the rectangle is still quite noisy, which will affect the size measurement we'll do later. We can smooth it using a morphological opening with a large circular structuring element. This operation will also cut off the corners, but the rounded corners will not influence the measurement result.</p>
<pre class="lang-matlab prettyprint-override"><code>rect = opening(fillholes(rect),35);
overlay(img,rect-berosion(rect)) % for display only
</code>```

Now we have a nice shape that is suitable for measurement. The Feret diameters are the lengths of the projections of a shape. We measure the length of the shortest projection (equal to the width of the rectangle) and the length of the projection perpendicular to the shortest (equal to the length of the rectangle). See this blog post of mine for a detailed description of the algorithm that computes these lengths.

msr = measure(rect,[],'feret');
sz = msr(1).feret(2:3)
```
<p>This returns <code>sz = [162.7506, 215.0775]</code>.</p>
<hr />
<p>Here is the Python equivalent of the code above (the exact same algorithm implementations are run). PyDIP, the Python bindings for the DIPlib library, is a more or less 1:1 mapping of the C++ library function names, and thus the syntax is a bit more verbose than that of the DIPimage toolbox I'm using above. Install with <code>pip install diplib</code>.</p>
<pre class="lang-py prettyprint-override"><code>import diplib as dip

img = dip.ImageRead('no8BP.png')

seeds = img.Similar()
seeds.Fill(0)
rr = dip.CreateRadiusCoordinate(seeds.Sizes())
seeds[rr < 50] = 1
seeds[rr > 250] = 2

rect = dip.SeededWatershed(dip.Gauss(img), seeds)
dip.viewer.ShowModal(dip.Overlay(img, rect))

rect = dip.Opening(dip.FillHoles(rect), 35)
dip.viewer.ShowModal(dip.Overlay(img, rect-dip.BinaryErosion(rect, 1, 1)))

msr = dip.MeasurementTool.Measure(dip.Label(rect), features=['Feret'])
sz = (msr[1]['Feret'][1], msr[1]['Feret'][2])
print(sz)
</code>```

You could likely implement this in OpenCV as well, but it might be a bit more involved. For example, the two Feret measures we compute here are equivalent to what is returned by OpenCV's minAreaRect, and the seeded watershed is included in OpenCV's watershed.

Body:
So I'm working on an image processing project with sonar images. To be more specific, I am trying to extract the dimensions of an image of a pool taken by a sonar scanner. I was able to extract the rectangular region of the pool but I can not figure out how to get the dimensions of each edge in terms of pixels. I am working with OpenCV in Python.

I would appreciate if anyone would give me any suggestion on how this could be done.

I already tried finding the line intersections of hough lines but that did not have promising results.

Code so far.

import cv2
import numpy as np
from scipy import ndimage as ndi
from scipy.ndimage.measurements import label

def largest_component(indices):
    #this function takes a list of indices denoting
    #the white regions of the image and returns the largest
    #white object of connected indices

    return_arr = np.zeros((512,512), dtype=np.uint8)
    for index in indeces:
        return_arr[index[0]][index[1]] = 255

    return return_arr

image = cv2.imread('sonar_dataset/useful/sonarXY_5.bmp', 0)
image_gaussian = ndi.gaussian_filter(image, 4)
image_gaussian_inv = cv2.bitwise_not(image_gaussian)
kernel = np.ones((3,3),np.uint8)

# double thresholding extracting the sides of the rectangle
ret1, img1 = cv2.threshold(image_gaussian_inv, 120, 255, cv2.THRESH_BINARY)
ret2, img2 = cv2.threshold(image_gaussian_inv, 150, 255, cv2.THRESH_BINARY)

double_threshold = img1 - img2
closing = cv2.morphologyEx(double_threshold, cv2.MORPH_CLOSE, kernel1)

labeled, ncomponents = label(closing, kernel)
indices = np.indices(closing.shape).T[:,:,[1, 0]]
twos = indices[labeled == 2]
area =[np.sum(labeled==val) for val in range(ncomponents+1)]

rectangle = largest_component(twos)

cv2.imshow('rectangle', rectangle)
cv2.waitKey(0)

The original image and extracted object are below.

Body:
There are already two good solutions, I wanted to propose a simpler one based on a different way of detecting the rectangle.

(I'm using MATLAB with DIPimage here, because that's quicker for me to toss a proof of concept together than Python, but the same exact functionality is available in Python, see at the end of the post. Disclaimer: I'm an author of DIPimage.)

Because the rectangle is a bright shape on a darker background, and is (I presume) guaranteed to surround the center of the image, we can generate a seed in the center of the image and a seed in the periphery, and use the watershed to find the rectangle. The watershed is guaranteed, in this case, to produce a single, 1-pixel thick, closed contour.

img = readim('https://i.stack.imgur.com/no8BP.png');
seeds = clone(img);
seeds(rr(seeds)<50) = 1;
seeds(rr(seeds)>250) = 2;
rect = waterseed(seeds,gaussf(img));
overlay(img,rect) % for display only

Note that I smoothed the input image a bit. But the rectangle is still quite noisy, which will affect the size measurement we'll do later. We can smooth it using a morphological opening with a large circular structuring element. This operation will also cut off the corners, but the rounded corners will not influence the measurement result.

rect = opening(fillholes(rect),35);
overlay(img,rect-berosion(rect)) % for display only

Now we have a nice shape that is suitable for measurement. The Feret diameters are the lengths of the projections of a shape. We measure the length of the shortest projection (equal to the width of the rectangle) and the length of the projection perpendicular to the shortest (equal to the length of the rectangle). See this blog post of mine for a detailed description of the algorithm that computes these lengths.

msr = measure(rect,[],'feret');
sz = msr(1).feret(2:3)

This returns sz = [162.7506, 215.0775].

Here is the Python equivalent of the code above (the exact same algorithm implementations are run). PyDIP, the Python bindings for the DIPlib library, is a more or less 1:1 mapping of the C++ library function names, and thus the syntax is a bit more verbose than that of the DIPimage toolbox I'm using above. Install with pip install diplib.

import diplib as dip

img = dip.ImageRead('no8BP.png')

seeds = img.Similar()
seeds.Fill(0)
rr = dip.CreateRadiusCoordinate(seeds.Sizes())
seeds[rr < 50] = 1
seeds[rr > 250] = 2

rect = dip.SeededWatershed(dip.Gauss(img), seeds)
dip.viewer.ShowModal(dip.Overlay(img, rect))

rect = dip.Opening(dip.FillHoles(rect), 35)
dip.viewer.ShowModal(dip.Overlay(img, rect-dip.BinaryErosion(rect, 1, 1)))

msr = dip.MeasurementTool.Measure(dip.Label(rect), features=['Feret'])
sz = (msr[1]['Feret'][1], msr[1]['Feret'][2])
print(sz)

You could likely implement this in OpenCV as well, but it might be a bit more involved. For example, the two Feret measures we compute here are equivalent to what is returned by OpenCV's minAreaRect, and the seeded watershed is included in OpenCV's watershed.


问:
Extracting the "n"th image out of a bmp (or other image type)
I have a bmp image that's comprised of 13 images, and each image is exactly 17x17. Aside from breaking this image down through gimp into 13 different images, what is a good way to 'extract' the nth image from this list (into a char array, preferably) so that I may then use it?
I've tried advancing the pointer forward by n*17*17 pixels, and aside from the fact that it ignores the header, thought this should work - unfortunately, it doesn't.

Suggestions?

Note that I've tagged this as C and C++ because I'm happy to see/hear of a solution in either language.

答:
Perhaps use existing tools for tile cropping

```<code>convert paged.gif  +gravity -crop 32x32  tiles_%d.gif
</code>```

Imagemagick comes with an API that is usable from many language, including C, C++, php, perl, etc etc
The relevant function would seem to be

CropImageToTiles

Body:
Perhaps use existing tools for tile cropping

convert paged.gif  +gravity -crop 32x32  tiles_%d.gif

Imagemagick comes with an API that is usable from many language, including C, C++, php, perl, etc etc
The relevant function would seem to be

CropImageToTiles


问:
Hibernate database per tenant multi-tenant connection provider is creating multiple database connections for single tenant
I want to know how hibernate's multi-tenant connection provider handles the data base connections for multiple tenants in separate database multi-tenancy approach. If I hit the API with same tenant, say 1234, then at first hit it should CONNECT to that tenant's specific database and after several hits for same tenant, will it use the same connection of database or it will open the new connection again for the same tenant?

I have used AbstractDataSourceBasedMultiTenantConnectionProviderImpl and CurrentTenantIdentifierResolver implementations in database per tenant approach

class CurrentTenantIdentifierResolver {
    // Other methods + fields
    public String resolveCurrentTenantIdentifier() {
      String tenantId = TenantContext.getCurrentTenant();
      return tenantId;
    }
}

class AbstractDataSourceBasedMultiTenantConnectionProviderImpl {
    // Other methods + fields

    @Override protected DataSource selectDataSource(String tenantIdentifier) {
      return MultiTenantInitService.getDataSourceMap().get(tenantIdentifier);
    }
}

class MultiTenantInitService {
    // Other methods + fields

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(prop.getProperty("spring.jpa.properties.hibernate.driver-class-name"));
    dataSource.setUrl(prop.getProperty("spring.datasource.url"));
    dataSource.setUsername(prop.getProperty("spring.datasource.username"));
    dataSource.setPassword(prop.getProperty("spring.datasource.password"));
    dataSourceMap.put(ApplicationConstants.DEFAULT_TENANT_ID, dataSource);
}
```

I expected multi tenant connection provider to connect to the database on first hit of API for single tenant for once only. It should not open the connections again and again for the same tenant. The new connection with data base should only be formed for new tenant. But, if it does open the connections then it should also manage the connection closing on its own.

答:
I think what you want is,

```<code>spring.datasource.max-active=1
</code>```

This property limits the maximum active connections to your database. So you can set this property to your DataSource and use it. which means you only have one connection in the connection pool. But there are pros and cons of this approach as if in any means the connection is corrupted, you will have to work on creating a different connection to work on the particular tenant again. So there are pretty good reasons to have a connection pool instead of having just one connection.
So the better solution would have a small connection pool as per your requirement.
If your application is constantly accessing the database its obvious that you need to have a connection pool. So I would suggest you have small connection pools per tenant.

```<code>spring.datasource.max-active=5
</code>```

Body:
I want to know how hibernate's multi-tenant connection provider handles the data base connections for multiple tenants in separate database multi-tenancy approach. If I hit the API with same tenant, say 1234, then at first hit it should CONNECT to that tenant's specific database and after several hits for same tenant, will it use the same connection of database or it will open the new connection again for the same tenant?

I have used AbstractDataSourceBasedMultiTenantConnectionProviderImpl and CurrentTenantIdentifierResolver implementations in database per tenant approach

class CurrentTenantIdentifierResolver {
    // Other methods + fields
    public String resolveCurrentTenantIdentifier() {
      String tenantId = TenantContext.getCurrentTenant();
      return tenantId;
    }
}

class AbstractDataSourceBasedMultiTenantConnectionProviderImpl {
    // Other methods + fields

    @Override protected DataSource selectDataSource(String tenantIdentifier) {
      return MultiTenantInitService.getDataSourceMap().get(tenantIdentifier);
    }
}

class MultiTenantInitService {
    // Other methods + fields

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(prop.getProperty("spring.jpa.properties.hibernate.driver-class-name"));
    dataSource.setUrl(prop.getProperty("spring.datasource.url"));
    dataSource.setUsername(prop.getProperty("spring.datasource.username"));
    dataSource.setPassword(prop.getProperty("spring.datasource.password"));
    dataSourceMap.put(ApplicationConstants.DEFAULT_TENANT_ID, dataSource);
}

I expected multi tenant connection provider to connect to the database on first hit of API for single tenant for once only. It should not open the connections again and again for the same tenant. The new connection with data base should only be formed for new tenant. But, if it does open the connections then it should also manage the connection closing on its own.

Body:
I think what you want is,

spring.datasource.max-active=1

This property limits the maximum active connections to your database. So you can set this property to your DataSource and use it. which means you only have one connection in the connection pool. But there are pros and cons of this approach as if in any means the connection is corrupted, you will have to work on creating a different connection to work on the particular tenant again. So there are pretty good reasons to have a connection pool instead of having just one connection.
So the better solution would have a small connection pool as per your requirement.
If your application is constantly accessing the database its obvious that you need to have a connection pool. So I would suggest you have small connection pools per tenant.

spring.datasource.max-active=5


问:
UpsetR: add numeric labels to set size on plot
Is there any way to add labels on top of the set size bars in UpsetR similar to the show.numbers for the main intersection graph?

```<code>test <- upset(grouped_hot,
              sets                = c("A", "B", "C", "N"),
              nintersects         = 8,
              mb.ratio            = c(0.6, 0.4),
              sets.x.label        = "Number of Patients",
              sets.bar.color      =  "#56B4E9",
              mainbar.y.label     = "Number of Patients",
              order.by            = "freq",
              empty.intersections = "on",
              keep.order          = FALSE,
              scale.sets          = "identity",
              att.pos             = "top",
              text.scale          = c(2.5, 2.5, 2, 1.5, 2.5, 2.5))
</code>```

Expected result is to have labels over each of the set size bars stating the size.

答:
it is possible to do that with set_size.show:

```<code>test <- upset(grouped_hot, sets= c("A", "B", "C", "N"),
        nintersects = 8,
        mb.ratio = c(0.6, 0.4),
        ...
        att.pos = "top",
        text.scale = c(2.5,2.5,2,1.5,2.5,2.5),
        set_size.show = TRUE)
</code>```

However, the current package version on Cran doesn't support this parameter, so you should work in the development mode (using devtools). The procedure is nicely written here: https://github.com/hms-dbmi/UpSetR/pull/104#issuecomment-376245215.

Make sure you load the package when already in the development mode. If you load it before, it loads the version from cran that is saved in your repository.

Best, Ana

Body:
Is there any way to add labels on top of the set size bars in UpsetR similar to the show.numbers for the main intersection graph?

test <- upset(grouped_hot,
              sets                = c("A", "B", "C", "N"),
              nintersects         = 8,
              mb.ratio            = c(0.6, 0.4),
              sets.x.label        = "Number of Patients",
              sets.bar.color      =  "#56B4E9",
              mainbar.y.label     = "Number of Patients",
              order.by            = "freq",
              empty.intersections = "on",
              keep.order          = FALSE,
              scale.sets          = "identity",
              att.pos             = "top",
              text.scale          = c(2.5, 2.5, 2, 1.5, 2.5, 2.5))

Expected result is to have labels over each of the set size bars stating the size.

Body:
it is possible to do that with set_size.show:

test <- upset(grouped_hot, sets= c("A", "B", "C", "N"),
        nintersects = 8,
        mb.ratio = c(0.6, 0.4),
        ...
        att.pos = "top",
        text.scale = c(2.5,2.5,2,1.5,2.5,2.5),
        set_size.show = TRUE)

However, the current package version on Cran doesn't support this parameter, so you should work in the development mode (using devtools). The procedure is nicely written here: https://github.com/hms-dbmi/UpSetR/pull/104#issuecomment-376245215.

Make sure you load the package when already in the development mode. If you load it before, it loads the version from cran that is saved in your repository.

Best, Ana


问:
solving the 2-sum algorithm in javascript
I'm trying to write a simple solution to the 2-Sum problem in Javascript. The problem goes: given an array of n integers and a target sum, determine what combinations of two integers will sum to the target value.

I found a few different language agnostic examples using hash tables and tried to come up with a solution in javascript:

```<code>// Integer set:
arr = [1,4,2,3,0,5];
// Target sum:
arg = 7;

// Generate hash table
hashTable = {};
arr.forEach(function(value, index){
  hashTable[value] = index;
});

// hashTable = {
//   0: 4,
//   1: 0,
//   2: 2,
//   3: 3,
//   4: 1,
//   5: 5,
// }

for (var i = 0; i < arr.length; i++) {
  if (hashTable[arg - arr[i]]) {
      console.log([hashTable[arg - arr[i]], i])
  }
}
</code>```

The solution should be 4,3 and 5,2 but i am getting 3,1 5,2 1,3 and 2,5. I can walk through the for loop with pen and paper and see that I am doing something wrong but I'm pretty sure I am following the langauge agnostic examples I found (for example here and here). Any help would be appreciated.

答:
```<code>function solution(arr, n){
var map = {};
for (var i = 0; i < arr.length; i++) {
    if (map[arr[i]] !== undefined) {
        console.log(arr[i], n - arr[i]);
    }
    map[n - arr[i]] = i;
  }
 }
</code>```

Body:
I'm trying to write a simple solution to the 2-Sum problem in Javascript. The problem goes: given an array of n integers and a target sum, determine what combinations of two integers will sum to the target value.

I found a few different language agnostic examples using hash tables and tried to come up with a solution in javascript:

// Integer set:
arr = [1,4,2,3,0,5];
// Target sum:
arg = 7;

// Generate hash table
hashTable = {};
arr.forEach(function(value, index){
  hashTable[value] = index;
});

// hashTable = {
//   0: 4,
//   1: 0,
//   2: 2,
//   3: 3,
//   4: 1,
//   5: 5,
// }

for (var i = 0; i < arr.length; i++) {
  if (hashTable[arg - arr[i]]) {
      console.log([hashTable[arg - arr[i]], i])
  }
}

The solution should be 4,3 and 5,2 but i am getting 3,1 5,2 1,3 and 2,5. I can walk through the for loop with pen and paper and see that I am doing something wrong but I'm pretty sure I am following the langauge agnostic examples I found (for example here and here). Any help would be appreciated.


问:
use params in devise signup form
My user visits an item show view and then is send to the signup-page (I use devise). On the signup page, I have the params (item_id) of the item he visited on the previous page. I want this item_id to be saved when the user makes his sign_up (like user.item_id). Here is how I tried to do it:

```<code><input value="#{params[:item_id]}" type="hidden" name="user[item_id]" id="user_item_id">
</code>```

When the user is saved, the item_id remains empty. What am I missing here?
Here is what I put into my controller:

```<code>def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:item_id])
end
</code>```

答: How you handling this in controller. Just sending a parameter won't solve your issue</p>

Title: use params in devise signup form

Body:
My user visits an item show view and then is send to the signup-page (I use devise). On the signup page, I have the params (item_id) of the item he visited on the previous page. I want this item_id to be saved when the user makes his sign_up (like user.item_id). Here is how I tried to do it:

<input value="#{params[:item_id]}" type="hidden" name="user[item_id]" id="user_item_id">

When the user is saved, the item_id remains empty. What am I missing here?
Here is what I put into my controller:

def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:item_id])
end


问:
pureconfig no manual imports of pureconfig.generic.auto._
The latest updates of pureconfig in the 0.10.* series disabled automatic configuration by default.

```<code>import pureconfig.generic.auto._
</code>```

needs to be manually imported.
But I have a class hierarchy, where I do not want to import it every time for a child class.

```<code>import pureconfig.ConfigReader
abstract class SparkBaseRunner[T <: Product](implicit A: ConfigReader[T])extends App {}
</code>```

already expects a configReader.
When using this base class:

```<code>object MyOperation extends SparkBaseRunner[MyCaseClass] {}
</code>```

it fails with:

```<code>could not find implicit value for parameter A: pureconfig.ConfigReader[foo.bar.my.Type]
</code>```

unless the above mentioned input is specified manually at each child class. Is there a way to avoid this code duplication? Trying to specify the input in the abstract base class did not work for me as it requires already a ConfigReader object.

edit

Trying to manually get access to the config reader inside the base class also fails:

```<code>implicit val configReader = deriveReader[T]
could not find implicit value for parameter A: pureconfig.ConfigReader[T]
could not find Lazy implicit value of type pureconfig.generic.DerivedConfigReader[T]
</code>```

My Scala version is: 2.11.12

答:
I believe that the config is being read as a single operation already, and there are multiple applications, all doing the below:

```<code>object Ops extends SparkBaseRunner[MyCaseClass]
</code>```

I can't see a way to avoid duplication since the base class can't infer the configuration since all it has is a generic type T.

The best solution is to not worry about it and use auto._.

```<code>import pureconfig.generic.auto._
</code>```

Body:
The latest updates of pureconfig in the 0.10.* series disabled automatic configuration by default.

import pureconfig.generic.auto._

needs to be manually imported.
But I have a class hierarchy, where I do not want to import it every time for a child class.

import pureconfig.ConfigReader
abstract class SparkBaseRunner[T <: Product](implicit A: ConfigReader[T])extends App {}

already expects a configReader.
When using this base class:

object MyOperation extends SparkBaseRunner[MyCaseClass] {}

it fails with:

could not find implicit value for parameter A: pureconfig.ConfigReader[foo.bar.my.Type]

unless the above mentioned input is specified manually at each child class. Is there a way to avoid this code duplication? Trying to specify the input in the abstract base class did not work for me as it requires already a ConfigReader object.

edit

Trying to manually get access to the config reader inside the base class also fails:

implicit val configReader = deriveReader[T]
could not find implicit value for parameter A: pureconfig.ConfigReader[T]
could not find Lazy implicit value of type pureconfig.generic.DerivedConfigReader[T]

My Scala version is: 2.11.12

Body:
I believe that the config is being read as a single operation already, and there are multiple applications, all doing the below:

object Ops extends SparkBaseRunner[MyCaseClass]

I can't see a way to avoid duplication since the base class can't infer the configuration since all it has is a generic type T.

The best solution is to not worry about it and use auto._.

import pureconfig.generic.auto._


问:
Is there something like "Requestor Pays" with Amazon S3 but where requestor pays for storage?
Is there a cloud service where I can allow users to upload files and also pay for them at the same time?  Or is there a way to do it on S3, like "Requestor Pays" but where requestor pays for storage and uploading?

I want to have essentially public inbound storage where the person would pay say $0.01 for uploading 1MB. Perhaps the file would only be stored for a month (since they only paid a fixed amount, not for potentially infinite storage)

答: You're talking about a service offering. If you want to find the service offering so that you can show it to user, the user too can find you and avoid you from being a middleman. A good idea will be creating a bucket and then build an app to allow users to upload files. Cognito can be used for authentication. Also, you can use SAM for your portal. If you want to charge user per their usage, you should keep track of their usage too.</p>


问:
Spaces not registered when using onChange on <input>
Upon pressing of space onChange event is not getting called on my html input element.

Here's what I tried.

```<code>class FilterDropDown extends React.PureComponent {
state = {
      query: '',
    };

handleKeyPress = (evt) => {
      this.setState({ query: evt.target.value });
    };

render() {
      const { placeholder, items, id } = this.props;
      return (
        <DropDown
          placeholder={placeholder}
          open={this.state.show}
          onToggle={this.disableAppScrollAndToggleShowState}
          onSelect={this.onSelect}
          value={this.props[id]}
        >
          {
            this.props.filterable
            && (
            // eslint-disable-next-line react/jsx-no-undef
            <DropDown.Item disabled className="filters__option-text-filter">
              <div className="wrapper">
                <Label className="filter-dropdown__search-icon" />
                <input
                  type="text"
                  onChange={this.handleKeyPress}
                  size="sm"
                  placeholder={this.props.filterPlaceholder}
                  aria-label="filter-dropdown"
                  value={this.state.query}
                />
                <Button className="filter-dropdown__clear" onClick={this.resetQuery} />
              </div>
            </DropDown.Item>
            )
          }

          {
            items
              .filter(item => item.value.length > 0
                && item.value.toLowerCase().includes(this.state.query.toLowerCase()))
              .map(item => (
                <DropDown.Item
                  active={item.value === this.props[id]}
                  key={item.value}
                  eventKey={item.value}
                >
                  <span className="filter-options">{`${item.value} (${item.count})`}</span>
                </DropDown.Item>
              ))
          }
        </DropDown>
      );
    }
}
</code>```

I am not posting the whole code but just enough to understand the use.
Also this input field is within the React Bootstraps Dropdown element, which is not allowing the input to accept spaces.

Heres a link of the documentation of react Dropdown https://react-bootstrap.github.io/components/dropdowns/. If we look at the Custom Dropdown Components example the input box implemented there also doesn't allow spaces.

Is there a way I can deal with that?
Thanks.

答:
You need to pass e in the parameter of handleKeyPress function.

onChange={e => this.handleKeyPress(e)}

```<code><input
  type="text"
  onChange={e => this.handleKeyPress(e)}
  size="sm"
  placeholder={this.props.filterPlaceholder}
  aria-label="filter-dropdown"
  value={this.state.query}
/>
</code>```

Body:
Upon pressing of space onChange event is not getting called on my html input element.

Here's what I tried.

class FilterDropDown extends React.PureComponent {
state = {
      query: '',
    };

handleKeyPress = (evt) => {
      this.setState({ query: evt.target.value });
    };

render() {
      const { placeholder, items, id } = this.props;
      return (
        <DropDown
          placeholder={placeholder}
          open={this.state.show}
          onToggle={this.disableAppScrollAndToggleShowState}
          onSelect={this.onSelect}
          value={this.props[id]}
        >
          {
            this.props.filterable
            && (
            // eslint-disable-next-line react/jsx-no-undef
            <DropDown.Item disabled className="filters__option-text-filter">

                <input
                  type="text"
                  onChange={this.handleKeyPress}
                  size="sm"
                  placeholder={this.props.filterPlaceholder}
                  aria-label="filter-dropdown"
                  value={this.state.query}
                />
                <Button className="filter-dropdown__clear" onClick={this.resetQuery} />

            </DropDown.Item>
            )
          }

          {
            items
              .filter(item => item.value.length > 0
                && item.value.toLowerCase().includes(this.state.query.toLowerCase()))
              .map(item => (
                <DropDown.Item
                  active={item.value === this.props[id]}
                  key={item.value}
                  eventKey={item.value}
                >
                  {`${item.value} (${item.count})`}
                </DropDown.Item>
              ))
          }
        </DropDown>
      );
    }
}

I am not posting the whole code but just enough to understand the use.
Also this input field is within the React Bootstraps Dropdown element, which is not allowing the input to accept spaces.

Heres a link of the documentation of react Dropdown https://react-bootstrap.github.io/components/dropdowns/. If we look at the Custom Dropdown Components example the input box implemented there also doesn't allow spaces.

Is there a way I can deal with that?
Thanks.

Body:
You need to pass e in the parameter of handleKeyPress function.

onChange={e => this.handleKeyPress(e)}

<input
  type="text"
  onChange={e => this.handleKeyPress(e)}
  size="sm"
  placeholder={this.props.filterPlaceholder}
  aria-label="filter-dropdown"
  value={this.state.query}
/>


问:
How to deprecate A CustomView and show the deprecation at the XML Layout
Is it possible to deprecate a CustomView and also make the xml layout reflect the deprecation?

So for example I deprecated my custom view as such:

```<code>@Deprecated
class SomeCustomView()
</code>```

then I want the xml layout using this customview to have an indication that it is deprecated, maybe something like:

<<s>com.sample.directory.SomeCustomView</s>
    android:layout_width="match_parent"
    android:layout_height="0dp"/>

is this possible?

答:
Add this in front of all the constructors and class name of your custom view.</p>

```<code>/** @deprecated */
    @Deprecated
</code>```

Body:
Is it possible to deprecate a CustomView and also make the xml layout reflect the deprecation?

So for example I deprecated my custom view as such:

@Deprecated
class SomeCustomView()

then I want the xml layout using this customview to have an indication that it is deprecated, maybe something like:

<<s>com.sample.directory.SomeCustomView</s>
    android:layout_width="match_parent"
    android:layout_height="0dp"/>

is this possible?

Body:
Add this in front of all the constructors and class name of your custom view.

/** @deprecated */
    @Deprecated


问:
How to set semi-random name for S3 bucket using cloud formation
I want to create a cloud formation template that creates an S3 bucket with a human readable name, but which can be run many times automatically.
Below is a bucket with predefined name.

What can I do to make the name contain a human readable portion in addition to a random unique id? Something like: MyBucket-abcdabcd, MyBucket-efghefgh, MyBucket-ijklijkl.

```<code>"S3Bucket" : {
  "Type" : "AWS::S3::Bucket",
  "Properties" : {
    "BucketName": "MyBucket",
    "PublicAccessBlockConfiguration" : {
      "BlockPublicAcls" : true,
      "BlockPublicPolicy" : true
    }
  }
}
</code>```

答:
You have two options.

First option - you can just leave your BucketName property blank. When you leave it blank, it'll yield a name of:
<stackname>-<template logical name>-<random suffix>

So, if you have stack name and template logical name that make sense, it should give you a unique bucket name every time.

Second option - use the Stack ARN suffix, which is a random guid:
arn:aws:cloudformation:us-west-2:123456789012:stack/teststack/51af3dc0-da77-11e4-872e-1234567db123

```<code>!Select [2, !Split [/, !Ref AWS::StackId ]]
</code>```

That would yield you '51af3dc0-da77-11e4-872e-1234567db123'
You can further split that again and select a portion if you want.

```<code>!Select [0, !Split[-, !Select [2, !Split [/, !Ref AWS::StackId ]]]]
</code>```

Gives you 51af3dc0

Body:
I want to create a cloud formation template that creates an S3 bucket with a human readable name, but which can be run many times automatically.
Below is a bucket with predefined name.

What can I do to make the name contain a human readable portion in addition to a random unique id? Something like: MyBucket-abcdabcd, MyBucket-efghefgh, MyBucket-ijklijkl.

"S3Bucket" : {
  "Type" : "AWS::S3::Bucket",
  "Properties" : {
    "BucketName": "MyBucket",
    "PublicAccessBlockConfiguration" : {
      "BlockPublicAcls" : true,
      "BlockPublicPolicy" : true
    }
  }
}

Body:
You have two options.

First option - you can just leave your BucketName property blank. When you leave it blank, it'll yield a name of:
<stackname>-<template logical name>-<random suffix>

So, if you have stack name and template logical name that make sense, it should give you a unique bucket name every time.

Second option - use the Stack ARN suffix, which is a random guid:
arn:aws:cloudformation:us-west-2:123456789012:stack/teststack/51af3dc0-da77-11e4-872e-1234567db123

!Select [2, !Split [/, !Ref AWS::StackId ]]

That would yield you '51af3dc0-da77-11e4-872e-1234567db123'
You can further split that again and select a portion if you want.

!Select [0, !Split[-, !Select [2, !Split [/, !Ref AWS::StackId ]]]]

Gives you 51af3dc0


问:
sIFR text stretched/blurry in Google Chrome
Answered

The best answer below was good for the bounty, but user Aaron's answer is the correct answer. Setting:

```<code>.sIFR-flash {
width:100%;
}
</code>```

corrects the issue in Chrome. Sadly, I cannot change my best answer as I guess that's how bounties work.

Answered

I seem to be having some issues with Chrome specifically rendering sIFR replaced text stretched out (and blurry) in it's flash container. No other browser does this (looks good in IE6,7,8, FF, Safari, Opera). Is this a known bug/does anyone have a workaround?

Here's an example you can look at on this site: http://uvph.com/

And here's the replace code:

```<code>// -- configure sifr
var futura = { src: '/swf/bfuturah.swf' };

sIFR.activate(futura);

sIFR.replace(futura, {
    css: [
        '.sIFR-root { background-color:transparent; color: #999999; font-size:24px; text-transform:uppercase; }'
    ],
    fitExactly      : true,
    forceClear      : true,
    forceSingleLine : true,
    selector        : 'h2',
    transparent     : true
});
</code>```

答:
I can't use @font-face as my font embeds poorly and I need selectable text. To fix the vertical stretching for my sIFR in IE9 I added
display:block;
height:1.45em;
to the .sIFR-flash
which seemed to match up to IE8 and Firefox
I also used a body font-size of 70%
It gives an extra little flicker while loading but the stretching has stopped.</p>

ContentLicense: CC BY-SA 2.5

Body:
Answered

The best answer below was good for the bounty, but user Aaron's answer is the correct answer. Setting:

.sIFR-flash {
width:100%;
}

corrects the issue in Chrome. Sadly, I cannot change my best answer as I guess that's how bounties work.

Answered

I seem to be having some issues with Chrome specifically rendering sIFR replaced text stretched out (and blurry) in it's flash container. No other browser does this (looks good in IE6,7,8, FF, Safari, Opera). Is this a known bug/does anyone have a workaround?

Here's an example you can look at on this site: http://uvph.com/

And here's the replace code:

// -- configure sifr
var futura = { src: '/swf/bfuturah.swf' };

sIFR.activate(futura);

sIFR.replace(futura, {
    css: [
        '.sIFR-root { background-color:transparent; color: #999999; font-size:24px; text-transform:uppercase; }'
    ],
    fitExactly      : true,
    forceClear      : true,
    forceSingleLine : true,
    selector        : 'h2',
    transparent     : true
});


问:
React Axios: Sometimes State Doesn't Pass onClick event
I'm working on some code. Basically When button 1 (id=1) is clicked, it display its value (where id===1). When button 2 is clicked, it display the value of button "2", etc The code are working fine.

```<code>    constructor(props) {
        super(props);
        this.state = {
            collections: [],
            collection: [],
            initialVal: [],
    };

    choseSeason = event => {
        // console.log(event.target.id);
        this.setState({
            initialVal: event.target.id,
        }, () => console.log('initialVal: '+this.state.initialVal));
    }

    componentDidMount() {
    axios.get(`https://myapi`)
      .then(res => {
        const collections = res.data;
        this.setState({
            collections,
        collection: collections.map(collection=>(collection)),
        //this is console log line 29
        initialVal: collections[0].id,
         });
      })
  }
render() {
    const { collections = [] } = this.state;
    const collection = this.state;
    const nowId = collections.filter(collection => collection.id === this.state.initialVal);
    console.log(nowId); //this is console log line 56
    return (
        <Container className="collection">

                <div className="">
                    {collections.length ? collections.map(c=>(
                            <div className="nav"><NavLink activeClassName={"active3"} onClick={this.choseSeason}><span id={c.id}>{'SS'+c.name.slice(7, 9)}</span></NavLink></div>
                        ))
                    :
                    <React.Fragment/>
                    }
                </div>

           {nowId.length ?

            <div className="wrapper">

                <div className="item1 flex">

                <div className="flex right">
                    <div className="title vBot">
                        {nowId[0].collection_titles[0].title}
                    </div>
                </div>
...
</code>```

Flow:

ComponentDidMount get value from first data from my api, and put it in state (InitialVal)

in Render, nowId filtered the id where id === this.state.initialVal and display it

in Render, on NavLink Click, it changes the value of initialVal (choseSeason function)

Everything works fine, but sometimes when clicking (can be after 2nd click, or 100th click) the button passes '' to initialValue which made my component render nothing. (in below picture, on the 10th click, it passes nothing)

Does this have anything to do with my logic / syntax? please help! thank you!

答:
You can pass id in choseSeason method and update the state </p>

```<code>        constructor(props) {
      super(props);
      this.state = {
          collections: [],
          collection: [],
          initialVal: [],
    };

    choseSeason = id => {
      // console.log(id);
      this.setState({
          initialVal: id,
      }, () => console.log('initialVal: '+this.state.initialVal));
    }

    componentDidMount() {
    axios.get(`https://myapi`)
    .then(res => {
      const collections = res.data;
      this.setState({
          collections,
      collection: collections.map(collection=>(collection)),
      //this is console log line 29
      initialVal: collections[0].id,
      });
    })
    }
    render() {
    const { collections = [] } = this.state;
    const collection = this.state;
    const nowId = collections.filter(collection => collection.id ===
    this.state.initialVal);
    console.log(nowId); //this is console log line 56
    return (
      <Container className="collection">

              <div className="">
                  {collections.length ? collections.map(c=>(
                          <div className="nav"><NavLink activeClassName={"active3"} onClick={()=>this.choseSeason(c.id)}><span id={c.id}>{'SS'+c.name.slice(7, 9)}</span></NavLink></div>
                      ))
                  :
                  <React.Fragment/>
                  }
              </div>

        {nowId.length ?

          <div className="wrapper">

              <div className="item1 flex">

              <div className="flex right">
                  <div className="title vBot">
                      {nowId[0].collection_titles[0].title}
                  </div>
              </div>
    ...
</code>```

Body:
I'm working on some code. Basically When button 1 (id=1) is clicked, it display its value (where id===1). When button 2 is clicked, it display the value of button "2", etc The code are working fine.

    constructor(props) {
        super(props);
        this.state = {
            collections: [],
            collection: [],
            initialVal: [],
    };

    choseSeason = event => {
        // console.log(event.target.id);
        this.setState({
            initialVal: event.target.id,
        }, () => console.log('initialVal: '+this.state.initialVal));
    }

    componentDidMount() {
    axios.get(`https://myapi`)
      .then(res => {
        const collections = res.data;
        this.setState({
            collections,
        collection: collections.map(collection=>(collection)),
        //this is console log line 29
        initialVal: collections[0].id,
         });
      })
  }
render() {
    const { collections = [] } = this.state;
    const collection = this.state;
    const nowId = collections.filter(collection => collection.id === this.state.initialVal);
    console.log(nowId); //this is console log line 56
    return (
        <Container className="collection">

                    {collections.length ? collections.map(c=>(

<NavLink activeClassName={"active3"} onClick={this.choseSeason}>{'SS'+c.name.slice(7, 9)}</NavLink>

                        ))
                    :
                    <React.Fragment/>
                    }

           {nowId.length ?

                        {nowId[0].collection_titles[0].title}

...

Flow:

ComponentDidMount get value from first data from my api, and put it in state (InitialVal)

in Render, nowId filtered the id where id === this.state.initialVal and display it

in Render, on NavLink Click, it changes the value of initialVal (choseSeason function)

Everything works fine, but sometimes when clicking (can be after 2nd click, or 100th click) the button passes '' to initialValue which made my component render nothing. (in below picture, on the 10th click, it passes nothing)

Does this have anything to do with my logic / syntax? please help! thank you!

Body:
You can pass id in choseSeason method and update the state

        constructor(props) {
      super(props);
      this.state = {
          collections: [],
          collection: [],
          initialVal: [],
    };

    choseSeason = id => {
      // console.log(id);
      this.setState({
          initialVal: id,
      }, () => console.log('initialVal: '+this.state.initialVal));
    }

    componentDidMount() {
    axios.get(`https://myapi`)
    .then(res => {
      const collections = res.data;
      this.setState({
          collections,
      collection: collections.map(collection=>(collection)),
      //this is console log line 29
      initialVal: collections[0].id,
      });
    })
    }
    render() {
    const { collections = [] } = this.state;
    const collection = this.state;
    const nowId = collections.filter(collection => collection.id ===
    this.state.initialVal);
    console.log(nowId); //this is console log line 56
    return (
      <Container className="collection">

              <div className="">
                  {collections.length ? collections.map(c=>(
                          <div className="nav"><NavLink activeClassName={"active3"} onClick={()=>this.choseSeason(c.id)}><span id={c.id}>{'SS'+c.name.slice(7, 9)}</span></NavLink></div>
                      ))
                  :
                  <React.Fragment/>
                  }
              </div>

        {nowId.length ?

          <div className="wrapper">

              <div className="item1 flex">

              <div className="flex right">
                  <div className="title vBot">
                      {nowId[0].collection_titles[0].title}
                  </div>
              </div>
    ...


问:
Open new form in dialogbox from view
I have a form called PCBatchInfo. In this form, there only have 4 field which is BatchNo, Inspector, Start date, and End Date. I will then open this form and insert the information.

On other side, I have Computer form with many field which is use to show all document in view.

PCBatchInfo and Computer form have same field which is PBatchNo. So, what I will do is, I insert BatchNo in PCBatchInfo. Then when I save it, it will also change BatchNo for all Computer document.

I want to open new PCBatchInfo form in dialogbox in view. As I do some research, dialogbox only can open existing document using Queryopendocument.

Let's say, I click button in view then it will show dialogbox with PCBatchInfo form. I insert all information required, then save. Can I open this form using dialogbox from view using a button?

UPDATE

I have found a way to use dialogbox but couldn't get to save the form. Code is as below.

```<code>varResult = ws.DialogBox("PCBatchInfo", True, True, False, False, True, False, "Please insert all information below", dialogDoc, False, False, True)
    If varResult Then
        batchValue = dialogDoc.BBatchNo(0)
        inspectorValue = dialogDoc.BInspector(0)
        dateValue1 = dialogDoc.BStart(0)
        dateValue2 = dialogDoc.Bend(0)
    End If
</code>```

Can anyone help me how can I save form from dialogBox? Thanks in advance!

答:
In pseudo code:

```<code>Set dbdoc= New NotesDocument(db)
Rv= ws.DialogBox(....., dbdoc, ...)
If user clicked Ok then
    Dbdoc.Form= "YourFormName"
    Dbdoc.Save
Fi
</code>```

So you create a new NotesDocument before calling DialogBox, you can initialize fields there if you want, then the DialogBox opens, and when it is closed you have to check the return value. If the user clicked Ok, you have to complete the document yourself, by setting Form explicitly, and maybe some other things, and then you can save the document.

Title: Open new form in dialogbox from view

Body:
I have a form called PCBatchInfo. In this form, there only have 4 field which is BatchNo, Inspector, Start date, and End Date. I will then open this form and insert the information.

On other side, I have Computer form with many field which is use to show all document in view.

PCBatchInfo and Computer form have same field which is PBatchNo. So, what I will do is, I insert BatchNo in PCBatchInfo. Then when I save it, it will also change BatchNo for all Computer document.

I want to open new PCBatchInfo form in dialogbox in view. As I do some research, dialogbox only can open existing document using Queryopendocument.

Let's say, I click button in view then it will show dialogbox with PCBatchInfo form. I insert all information required, then save. Can I open this form using dialogbox from view using a button?

UPDATE

I have found a way to use dialogbox but couldn't get to save the form. Code is as below.

varResult = ws.DialogBox("PCBatchInfo", True, True, False, False, True, False, "Please insert all information below", dialogDoc, False, False, True)
    If varResult Then
        batchValue = dialogDoc.BBatchNo(0)
        inspectorValue = dialogDoc.BInspector(0)
        dateValue1 = dialogDoc.BStart(0)
        dateValue2 = dialogDoc.Bend(0)
    End If

Can anyone help me how can I save form from dialogBox? Thanks in advance!

Body:
In pseudo code:

Set dbdoc= New NotesDocument(db)
Rv= ws.DialogBox(....., dbdoc, ...)
If user clicked Ok then
    Dbdoc.Form= "YourFormName"
    Dbdoc.Save
Fi

So you create a new NotesDocument before calling DialogBox, you can initialize fields there if you want, then the DialogBox opens, and when it is closed you have to check the return value. If the user clicked Ok, you have to complete the document yourself, by setting Form explicitly, and maybe some other things, and then you can save the document.


问:
embedded jquery script not executing with html
I have a jquery embedded in my html page which takes the value of cgstPct and price fields and calculates the value of the final amount on the change event of cgstPct field.
On the web page this does not work.

I tried running on jsfiddle and it worked there so I assume there might be a problem with how I'm using it in my HTML file.

```<code><html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    <head>
        <title>Create Product</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
        $('#cgstPct').change(function() {
            var pct = parseFloat($(this).val());
            var price = parseFloat($('#price').val());
            var total = (price) * (pct/100);
            $('#finalAmount').val(total.toFixed(2));
        });
        </script>
    </head>
    <body>
        <div layout:fragment="content" class="row">
            <div class="col-xs-8 col-md-8">
                <h3>
                    <a href="/product" class="btn btn-lg btn-primary"><span class="glyphicon glyphicon-list"></span> Product</a>
                </h3>
                <h2>Create Product</h2>
                <form action="/save">
                    <div class="form-group">
                        <label for="email">Product Name:</label>
                        <input type="text" class="form-control" name="prodName" />
                    </div>
                    <div class="form-group">
                        <label for="email">Product Description</label>
                        <textarea class="form-control" name="prodDesc" cols="60" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="email">Product Price</label>
                        <input type="number" id="price" class="form-control" name="prodPrice" />

                    <label for="cgstPct">CGST PCT</label>
                    <input type="number" id="cgstPct" class="form-control" name="cgstPct" />

                    <label for="finalAmount">Amount after GST</label>
                    <input type="number" readonly="readonly" id="finalAmount" class="form-control" name="finalAmount" />

                    <button type="submit" class="btn btn-success">Save</button>
                </form>
            </div>
        </div>
    </body>
</html>
</code>```

答:
You can't have code inside a script tag that has a src.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
  $('#cgstPct').change(function() {
    var pct = parseFloat($(this).val());
    var price = parseFloat($('#price').val());
    var total = (price) * (pct/100);
    $('#finalAmount').val(total.toFixed(2));
  });
</script>
</code>```

It should be

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
  $('#cgstPct').change(function() {
    var pct = parseFloat($(this).val());
    var price = parseFloat($('#price').val());
    var total = (price) * (pct/100);
    $('#finalAmount').val(total.toFixed(2));
  });
</script>
</code>```

Body:
I have a jquery embedded in my html page which takes the value of cgstPct and price fields and calculates the value of the final amount on the change event of cgstPct field.
On the web page this does not work.

I tried running on jsfiddle and it worked there so I assume there might be a problem with how I'm using it in my HTML file.

        <title>Create Product</title>

                     Product

Create Product

                <form action="/save">

                        Product Name:
                        <input type="text" class="form-control" name="prodName" />

                        Product Description
                        <textarea class="form-control" name="prodDesc" cols="60" rows="3"></textarea>

                        Product Price
                        <input type="number" id="price" class="form-control" name="prodPrice" />

                    CGST PCT
                    <input type="number" id="cgstPct" class="form-control" name="cgstPct" />

                    Amount after GST
                    <input type="number" readonly="readonly" id="finalAmount" class="form-control" name="finalAmount" />

                    <button type="submit" class="btn btn-success">Save</button>
                </form>

Body:
You can't have code inside a script tag that has a src.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
  $('#cgstPct').change(function() {
    var pct = parseFloat($(this).val());
    var price = parseFloat($('#price').val());
    var total = (price) * (pct/100);
    $('#finalAmount').val(total.toFixed(2));
  });
</script>

It should be

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
  $('#cgstPct').change(function() {
    var pct = parseFloat($(this).val());
    var price = parseFloat($('#price').val());
    var total = (price) * (pct/100);
    $('#finalAmount').val(total.toFixed(2));
  });
</script>


问:
CAS authentification with front end Angular
I have to create a CAS authentification for my Angular app (front) and PHP/Symfony (backend).

I tried to do it with the front by using http.get(cas_url) but when I try to validate my token, the CORS would not allow me to go further.

Since I cannot change the CORS settings of the server, I have to do it an another way.

So I tried using phpCAS and it works fine alone on an apache server but how can I put it together with my front with a specific url or action.

答:
I wrapped my compiled front-end index.html inside a index.php (include) and used phpCAS which does everything.

Then once the front is loaded, I call the function phpCAS::getUser() in onInit(), then do my authentification by looking for the user in the database.


问:
Extracting styles in React + material-ui
I am using React + material-ui. I would like to extract the styles defined in each component into a common file.

if the followings are put in a single file, every works well:-

```<code>import { withStyles } from '@material-ui/core/styles';
...

const styles = theme => ({
    createButton: {
        [theme.breakpoints.up('md')]: {
            borderRadius: '10px',
            display: 'block',
            margin: '0 auto',
            marginTop: '10px',
            marginBottom: '10px',
            width: '360px',
        },
        [theme.breakpoints.down('sm')]: {
            borderRadius: '0px',
            bottom: '0px',
            position: 'relative',
            width: '100%',
            height: '60px',
            fontSize: '20px',
        },
        backgroundColor: theme.palette.secondary.main,
        color: 'white',
        '&:hover': {
            backgroundColor: theme.palette.secondary.main,
        },
    }
});
...

class Home extends Component {
...
<Button className={this.props.classes.createButton}>Hello</Button>
...
}

export default (withStyles(styles)(Home));
</code>```

now, I wish to extract the following into another file, e.g. common.js, then in future, I can import it in other components so that I can reuse the style:-

```<code>const styles = theme => ({
    createButton: {
        [theme.breakpoints.up('md')]: {
            borderRadius: '10px',
            display: 'block',
            margin: '0 auto',
            marginTop: '10px',
            marginBottom: '10px',
            width: '360px',
        },
        [theme.breakpoints.down('sm')]: {
            borderRadius: '0px',
            bottom: '0px',
            position: 'relative',
            width: '100%',
            height: '60px',
            fontSize: '20px',
        },
        backgroundColor: theme.palette.secondary.main,
        color: 'white',
        '&:hover': {
            backgroundColor: theme.palette.secondary.main,
        },
    }
});
</code>```

then, when I

```<code>import { styles } from './somewhere/common';
</code>```

the createButton style is not working anymore.

it mentioned

```<code>Attempted import error: 'styles' is not exported from './somewhere/common'.
</code>```

答:
You need to export styles from './somewhere/common', add this to the end of the file:

```<code>export default styles;
</code>```

And import it using:

```<code>import styles from './somewhere/common'
</code>```

Body:
I am using React + material-ui. I would like to extract the styles defined in each component into a common file.

if the followings are put in a single file, every works well:-

import { withStyles } from '@material-ui/core/styles';
...

const styles = theme => ({
    createButton: {
        [theme.breakpoints.up('md')]: {
            borderRadius: '10px',
            display: 'block',
            margin: '0 auto',
            marginTop: '10px',
            marginBottom: '10px',
            width: '360px',
        },
        [theme.breakpoints.down('sm')]: {
            borderRadius: '0px',
            bottom: '0px',
            position: 'relative',
            width: '100%',
            height: '60px',
            fontSize: '20px',
        },
        backgroundColor: theme.palette.secondary.main,
        color: 'white',
        '&:hover': {
            backgroundColor: theme.palette.secondary.main,
        },
    }
});
...

class Home extends Component {
...
<Button className={this.props.classes.createButton}>Hello</Button>
...
}

export default (withStyles(styles)(Home));

now, I wish to extract the following into another file, e.g. common.js, then in future, I can import it in other components so that I can reuse the style:-

const styles = theme => ({
    createButton: {
        [theme.breakpoints.up('md')]: {
            borderRadius: '10px',
            display: 'block',
            margin: '0 auto',
            marginTop: '10px',
            marginBottom: '10px',
            width: '360px',
        },
        [theme.breakpoints.down('sm')]: {
            borderRadius: '0px',
            bottom: '0px',
            position: 'relative',
            width: '100%',
            height: '60px',
            fontSize: '20px',
        },
        backgroundColor: theme.palette.secondary.main,
        color: 'white',
        '&:hover': {
            backgroundColor: theme.palette.secondary.main,
        },
    }
});

then, when I

import { styles } from './somewhere/common';

the createButton style is not working anymore.

it mentioned

Attempted import error: 'styles' is not exported from './somewhere/common'.

Body:
You need to export styles from './somewhere/common', add this to the end of the file:

export default styles;

And import it using:

import styles from './somewhere/common'


问:
Oppo firebase notification in background
Code for permission oppo cannot load app. Oppo phone cannot handle notification in background,
but when I use these code it work well:

```<code>val POWERMANAGER_INTENTS = arrayOf(
        Intent().setComponent(
            ComponentName(
                "com.coloros.safecenter",
                "com.coloros.safecenter.permission.startup.StartupAppListActivity"
            )
        ),
        Intent().setComponent(
            ComponentName(
                "com.coloros.safecenter",
                "com.coloros.safecenter.startupapp.StartupAppListActivity"
            )
        )
    )
</code>```

But this code cause my app cannnot load. it's make error like that:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.firebasesms.hong/com.firebasesms.hong.MainActivity}: java.lang.SecurityException: Permission Denial: starting Intent.......

Caused by: java.lang.SecurityException: Permission Denial: starting Intent ..... requires oppo.permission.OPPO_COMPONENT_SAFE
</code>```

AndroidManifest

Code: Kotlin

Error: requires oppo.permission.OPPO_COMPONENT_SAFE

答:
You need "OPPO_COMPONENT_SAFE" permission into your manifest to start Intent.

```<code>    <!--for OPPO-->
<uses-permission android:name="oppo.permission.OPPO_COMPONENT_SAFE" />
</code>```

Reference: Denial permission OPPO_COMPONENT_SAFE

Body:
Code for permission oppo cannot load app. Oppo phone cannot handle notification in background,
but when I use these code it work well:

val POWERMANAGER_INTENTS = arrayOf(
        Intent().setComponent(
            ComponentName(
                "com.coloros.safecenter",
                "com.coloros.safecenter.permission.startup.StartupAppListActivity"
            )
        ),
        Intent().setComponent(
            ComponentName(
                "com.coloros.safecenter",
                "com.coloros.safecenter.startupapp.StartupAppListActivity"
            )
        )
    )

But this code cause my app cannnot load. it's make error like that:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.firebasesms.hong/com.firebasesms.hong.MainActivity}: java.lang.SecurityException: Permission Denial: starting Intent.......

Caused by: java.lang.SecurityException: Permission Denial: starting Intent ..... requires oppo.permission.OPPO_COMPONENT_SAFE

AndroidManifest

Code: Kotlin

Error: requires oppo.permission.OPPO_COMPONENT_SAFE

Body:
You need "OPPO_COMPONENT_SAFE" permission into your manifest to start Intent.

    <!--for OPPO-->
<uses-permission android:name="oppo.permission.OPPO_COMPONENT_SAFE" />

Reference: Denial permission OPPO_COMPONENT_SAFE


问:
Avoiding local dependencies for MSBuild Community Tasks within Visual Studio 2010
I'm trying to start taking advantage of the MSBuild Community Tasks so right after installing the .msi package I've imported MSBuild.Community.targets within the <Project> element this way:

```<code><Import Project="lib\MSBuild.Community.Tasks.targets" />
</code>```

Interestingly I've noticed such file have a reference to the local installation path in MSBuildExtensionsPath and given that in lieu of keeping code dependencies as clean as possible I'm willing to pay the overhead of distributing/versioning them with every project, I was wondering if is it possible to sort of override the default/installation location with a project-relative one in the .cproj file?

The actual layout would be like:

```<code>Dotnet.Samples.Foobar
\src
     Foobar.cs
\lib
     MSBuild.Community.Tasks.targets
     MSBuild.Community.Tasks.dll
</code>```

Any guidance will be sincerely appreciated. Thanks much in advace for any suggestion you might want to share.

答:
In MSBuild.Community.Tasks.targets specified the path to the dll.

```<code><PropertyGroup>
  <MSBuildCommunityTasksPath Condition="'$(MSBuildCommunityTasksPath)' == ''">$(MSBuildExtensionsPath)\MSBuildCommunityTasks</MSBuildCommunityTasksPath>
  <MSBuildCommunityTasksLib>$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.dll</MSBuildCommunityTasksLib>
</PropertyGroup>
</code>```

You can override the path in the project.

```<code><PropertyGroup>
   <MSBuildCommunityTasksPath>lib</MSBuildCommunityTasksPath>
</PropertyGroup>
</code>```

And leave import the same:

```<code><Import Project="lib\MSBuild.Community.Tasks.targets" />
</code>```

Body:
I'm trying to start taking advantage of the MSBuild Community Tasks so right after installing the .msi package I've imported MSBuild.Community.targets within the <Project> element this way:

<Import Project="lib\MSBuild.Community.Tasks.targets" />

Interestingly I've noticed such file have a reference to the local installation path in MSBuildExtensionsPath and given that in lieu of keeping code dependencies as clean as possible I'm willing to pay the overhead of distributing/versioning them with every project, I was wondering if is it possible to sort of override the default/installation location with a project-relative one in the .cproj file?

The actual layout would be like:

Dotnet.Samples.Foobar
\src
     Foobar.cs
\lib
     MSBuild.Community.Tasks.targets
     MSBuild.Community.Tasks.dll

Any guidance will be sincerely appreciated. Thanks much in advace for any suggestion you might want to share.

Body:
In MSBuild.Community.Tasks.targets specified the path to the dll.

<PropertyGroup>
  <MSBuildCommunityTasksPath Condition="'$(MSBuildCommunityTasksPath)' == ''">$(MSBuildExtensionsPath)\MSBuildCommunityTasks</MSBuildCommunityTasksPath>
  <MSBuildCommunityTasksLib>$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.dll</MSBuildCommunityTasksLib>
</PropertyGroup>

You can override the path in the project.

<PropertyGroup>
   <MSBuildCommunityTasksPath>lib</MSBuildCommunityTasksPath>
</PropertyGroup>

And leave import the same:

<Import Project="lib\MSBuild.Community.Tasks.targets" />


问:
How to merge two "ar" static libraries into one?
I have 2 static Linux libraries, created by ar cr, libabc.a and libxyz.a.

I want to merge them into one static library libaz.a.

How can I do this.

I want to create a merged static library,  not to give both libraries to final link of applications.

答:
```<code>ar -x libx264.a
mkdir sub && cd sub
ar -m ../libx264.a `ar -t ../libx264.a |sort|uniq|grep "\.o"`
ar -x ../libx264.a
</code>```

now you have two version of "macroblock-10.o"

Body:
ar -x libx264.a
mkdir sub && cd sub
ar -m ../libx264.a `ar -t ../libx264.a |sort|uniq|grep "\.o"`
ar -x ../libx264.a

now you have two version of "macroblock-10.o"


问:
How to filter a List using Java 8 stream and startwith array of values
I have 2 Lists, the one contains a list of numbers and the other a list of names. I have prefixed the names with a number from the first list, followed by an underscore. I want to filter the second list based on all the numbers found in the first list.

What I have tried.

```<code>List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

List<String> filteredList = Stream.of(numberList.toArray(new String[0]))
                .filter(str -> nameList.stream().anyMatch(str::startsWith))
                .collect(Collectors.toList());
</code>```

The code above runs with no error, but the filteredList is empty. Clearly I am doing something wrong.

The filteredList should contain only:

1_John

9_Susan

答:
As an alternate to Eran's solution, you can also use a combination of removeIf and noneMatch as follows:

```<code>List<String> filteredList = new ArrayList<>(nameList);
filteredList.removeIf(str -> numberList.stream().noneMatch(str::startsWith));
</code>```

Body:
I have 2 Lists, the one contains a list of numbers and the other a list of names. I have prefixed the names with a number from the first list, followed by an underscore. I want to filter the second list based on all the numbers found in the first list.

What I have tried.

List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

List<String> filteredList = Stream.of(numberList.toArray(new String[0]))
                .filter(str -> nameList.stream().anyMatch(str::startsWith))
                .collect(Collectors.toList());

The code above runs with no error, but the filteredList is empty. Clearly I am doing something wrong.

The filteredList should contain only:

1_John

9_Susan

Body:
As an alternate to Eran's solution, you can also use a combination of removeIf and noneMatch as follows:

List<String> filteredList = new ArrayList<>(nameList);
filteredList.removeIf(str -> numberList.stream().noneMatch(str::startsWith));


问:
How to get an close event when the window is closed?
I'm integrating My application with Microsoft office 365 using Microsoft Graph API's.

Currently i am using upload/share/delete file API's.

i want to edit document online with office 365,
what i have done is using graph API's i'm uploading document to one drive creating link to share that document and opening the share url obtained from microsoft in new window to edit the document.

I am opening new window with share URL received from microsoft and once the user edit in new window closes that window i want to capture it and save the changes from cloud to my application

```<code>var new_window  = window.open('file_share_url_from_microsoft', '_blank','location=yes,height=780,width=1100,scrollbars=yes,status=yes');

//i want to capture close event when new_window is closed
</code>```

is there anyway i can allow users to edit document in my application without opening in new tab..?(tried iframe but due to x-frame-options restricted to same-origin, it is not rendering in iframe)

is there anyway i can get the event when the edit window is closed by an user.?

答:
Using _parent will open in the same window, rather than a new one.</p>

```<code>window.open('file_share_url_from_microsoft', '_parent','location=yes,height=780,width=1100,scrollbars=yes,status=yes');
</code>```

Body:
I'm integrating My application with Microsoft office 365 using Microsoft Graph API's.

Currently i am using upload/share/delete file API's.

i want to edit document online with office 365,
what i have done is using graph API's i'm uploading document to one drive creating link to share that document and opening the share url obtained from microsoft in new window to edit the document.

I am opening new window with share URL received from microsoft and once the user edit in new window closes that window i want to capture it and save the changes from cloud to my application

var new_window  = window.open('file_share_url_from_microsoft', '_blank','location=yes,height=780,width=1100,scrollbars=yes,status=yes');

//i want to capture close event when new_window is closed

is there anyway i can allow users to edit document in my application without opening in new tab..?(tried iframe but due to x-frame-options restricted to same-origin, it is not rendering in iframe)

is there anyway i can get the event when the edit window is closed by an user.?

Body:
Using _parent will open in the same window, rather than a new one.

window.open('file_share_url_from_microsoft', '_parent','location=yes,height=780,width=1100,scrollbars=yes,status=yes');


问:
What is Moq's equivalent of LastCall in RhinoMocks?
I'm upgrading to .Net Core which involves converting a number of unit tests from RhinoMocks to Moq since it supports .Net Standard.

I've been converting LastCall by repeating the most recent mocked call, but I'm confused because I have a unit test where LastCall.Throw(Exception); occurs before any mocked calls do.

As I understand LastCall, it allows you to do something additional to the last call that was added, but I know I don't understand something because in my mind LastCall can't come before at least one mocked call.

The unit test looks something like:

```<code>MockRepository mock = new MockRepository();
 ...
using (mocks.Record())
{
    nonMockedObject.DoSomething();
    LastCall.Throw(Exception);
    Expect.Call(mockedObject.Stuff()).Return(true).Repeat.Any();
    ...
}
</code>```

Any help on understanding RhinoMocks's LastCall or how to convert it to Moq would be appreciated.

答:
From the link, https://www.codeproject.com/Articles/11294/Rhino-Mocks-2-2#Capabilities,
Below are some important points to be noted.

We use the Expect.Call() for methods that has return values, and
  LastCall for methods that return void to get the IMethodOptions
  interface. I find the Expect.Call() syntax a bit clearer, but there is
  no practical difference between the two.

I would recommend using Expect wherever possible (anything that return
  a value). For properties setters, or methods returning void, the
  Expect syntax is not applicable, since there is no return value.

Thus, the need for the LastCall. The idea of Last Call is pervasive in
  the record state, you can only set the method options for the last
  call  - even Expect.Call() syntax is merely a wrapper around LastCall.

Conclusion : Do not use LastCall inside record state. As you are migrating from RhinoMocks to Moq, You can Ignore LastCall.

Coming to the code which you have shared, You can mock functions which returns a value using moq as below,

```<code>Mock<IYourRepository> mockRepository = new Mock<IYourRepository>();
mockRepository.Setup(m=> m.YourMethodName(It.IsAny<int>())).Returns(new List<string>());
mockRepository.Setup(m=> m.YourMethodName(It.Is<int>(x=> x == 0)).Throws<ArgumentException>();
</code>```

For Methods which do not return anything, You can set like below,

```<code>Mock<IYourRepository> mockRepository = new Mock<IYourRepository>();
mockRepository.Setup(m=> m.YourVoidMethodName(It.IsAny<int>())).Verifiable();;
mockRepository.Setup(m=> m.YourVoidMethodName(It.IsAny<int>())).Throws<Exception>();
mockRepository.Setup(m=> m.YourAsyncVoidMethodName(It.IsAny<int>())).Returns(Task.Completed); // public async Task YourAsyncVoidMethodName(){}
</code>```

To address the comment,

LastCall.Repeat.AtLeastOnce(); would be converted to Moq as

```<code>Mock<IYourRepository> mockRepository = new Mock<IYourRepository>();
mockRepository.Verify(m=> m.NotVoidMethodName(It.IsAny<int>()), Times.AtLeastOnce());
</code>```

Body:
I'm upgrading to .Net Core which involves converting a number of unit tests from RhinoMocks to Moq since it supports .Net Standard.

I've been converting LastCall by repeating the most recent mocked call, but I'm confused because I have a unit test where LastCall.Throw(Exception); occurs before any mocked calls do.

As I understand LastCall, it allows you to do something additional to the last call that was added, but I know I don't understand something because in my mind LastCall can't come before at least one mocked call.

The unit test looks something like:

MockRepository mock = new MockRepository();
 ...
using (mocks.Record())
{
    nonMockedObject.DoSomething();
    LastCall.Throw(Exception);
    Expect.Call(mockedObject.Stuff()).Return(true).Repeat.Any();
    ...
}

Any help on understanding RhinoMocks's LastCall or how to convert it to Moq would be appreciated.

Body:
From the link, https://www.codeproject.com/Articles/11294/Rhino-Mocks-2-2#Capabilities,
Below are some important points to be noted.

We use the Expect.Call() for methods that has return values, and
  LastCall for methods that return void to get the IMethodOptions
  interface. I find the Expect.Call() syntax a bit clearer, but there is
  no practical difference between the two.

I would recommend using Expect wherever possible (anything that return
  a value). For properties setters, or methods returning void, the
  Expect syntax is not applicable, since there is no return value.

Thus, the need for the LastCall. The idea of Last Call is pervasive in
  the record state, you can only set the method options for the last
  call  - even Expect.Call() syntax is merely a wrapper around LastCall.

Conclusion : Do not use LastCall inside record state. As you are migrating from RhinoMocks to Moq, You can Ignore LastCall.

Coming to the code which you have shared, You can mock functions which returns a value using moq as below,

Mock<IYourRepository> mockRepository = new Mock<IYourRepository>();
mockRepository.Setup(m=> m.YourMethodName(It.IsAny<int>())).Returns(new List<string>());
mockRepository.Setup(m=> m.YourMethodName(It.Is<int>(x=> x == 0)).Throws<ArgumentException>();

For Methods which do not return anything, You can set like below,

Mock<IYourRepository> mockRepository = new Mock<IYourRepository>();
mockRepository.Setup(m=> m.YourVoidMethodName(It.IsAny<int>())).Verifiable();;
mockRepository.Setup(m=> m.YourVoidMethodName(It.IsAny<int>())).Throws<Exception>();
mockRepository.Setup(m=> m.YourAsyncVoidMethodName(It.IsAny<int>())).Returns(Task.Completed); // public async Task YourAsyncVoidMethodName(){}

To address the comment,

LastCall.Repeat.AtLeastOnce(); would be converted to Moq as

Mock<IYourRepository> mockRepository = new Mock<IYourRepository>();
mockRepository.Verify(m=> m.NotVoidMethodName(It.IsAny<int>()), Times.AtLeastOnce());


问:
How to select a selectbox an option value with JS?
This may sound easy but I'm been having a heck of a time to get this to work. Somebody please help. My select box is like below. How do i select the value 3 from the list?

```<code>        if(!empty($listeDoc))
        {
            $iGroups = 0;
            while($iGroups < count($listeDoc))
            {
            ?>
            <tr>
                <td>
                    <input type="checkbox" name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['product_id']" id="productSelectCreation_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" onchange="setValueToOne(this)"  ><?php echo $listeDoc[$iGroups]->DOC_CLIENT_NOM; ?>
                </td>

                <td>
                    <select name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['quantity']" id="productQty_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" class="form-control1" value="<?php echo $qty; ?>" style="width:100%; height:25px; border : #62270c solid 1px;" tabindex="1">
                        <option value=""/></option>
                        <option value="1"<?php if ($qty == 1) echo 'selected="selected"'; ?>>1</option>
                        <option value="2"<?php if ($qty == 2) echo 'selected="selected"'; ?>>2</option>
                        <option value="3"<?php if ($qty == 3) echo 'selected="selected"'; ?>>3</option>
                        <option value="4"<?php if ($qty == 4) echo 'selected="selected"'; ?>>4</option>
                        <option value="5"<?php if ($qty == 5) echo 'selected="selected"'; ?>>5</option>
                    </select>
                <td>
            </tr>

            <?php
            $iGroups++;
            }
        }
</code>```

here's is what i tried:

function setValueToOne(value)
{
    checkbox = document.getElementById('productSelectCreation');

```<code>if (checkbox.checked == true)
{
    document.getElementById("productQtyCreation").value = 1;
}
else
    document.getElementById("productQtyCreation").value = '0';
</code>```

}

答:
If I understand correctly you want to change the select box selected option using vanilla javascript. You will need to loop the selectbox and compare values. </p>

```<code> document.getElementById('productSelectCreation').onclick = function() {
    var val;
    var checkbox = document.getElementById('productSelectCreation');
    var sel = document.getElementById('productQtyCreation');
if (checkbox.checked)
{
    val = "3";
}
else
    val = "0";
}

      var opts = sel.options;
      for (var opt, j = 0; opt = opts[j]; j++) {
        if (opt.value == val) {
          sel.selectedIndex = j;
          break;
        }
      }
    }
</code>```

Body:
This may sound easy but I'm been having a heck of a time to get this to work. Somebody please help. My select box is like below. How do i select the value 3 from the list?

        if(!empty($listeDoc))
        {
            $iGroups = 0;
            while($iGroups < count($listeDoc))
            {
            ?>

                    <input type="checkbox" name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['product_id']" id="productSelectCreation_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" onchange="setValueToOne(this)"  ><?php echo $listeDoc[$iGroups]->DOC_CLIENT_NOM; ?>

                    <select name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['quantity']" id="productQty_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" class="form-control1" value="<?php echo $qty; ?>" style="width:100%; height:25px; border : #62270c solid 1px;" tabindex="1">
                        <option value=""/></option>
                        <option value="1"<?php if ($qty == 1) echo 'selected="selected"'; ?>>1</option>
                        <option value="2"<?php if ($qty == 2) echo 'selected="selected"'; ?>>2</option>
                        <option value="3"<?php if ($qty == 3) echo 'selected="selected"'; ?>>3</option>
                        <option value="4"<?php if ($qty == 4) echo 'selected="selected"'; ?>>4</option>
                        <option value="5"<?php if ($qty == 5) echo 'selected="selected"'; ?>>5</option>
                    </select>

            <?php
            $iGroups++;
            }
        }

here's is what i tried:

function setValueToOne(value)
{
    checkbox = document.getElementById('productSelectCreation');

if (checkbox.checked == true)
{
    document.getElementById("productQtyCreation").value = 1;
}
else
    document.getElementById("productQtyCreation").value = '0';

}

Body:
If I understand correctly you want to change the select box selected option using vanilla javascript. You will need to loop the selectbox and compare values.

 document.getElementById('productSelectCreation').onclick = function() {
    var val;
    var checkbox = document.getElementById('productSelectCreation');
    var sel = document.getElementById('productQtyCreation');
if (checkbox.checked)
{
    val = "3";
}
else
    val = "0";
}

      var opts = sel.options;
      for (var opt, j = 0; opt = opts[j]; j++) {
        if (opt.value == val) {
          sel.selectedIndex = j;
          break;
        }
      }
    }


问:
How to do action on Flowable
Hello I am new to RxJava, I have a class that receives Flowable<Item> f2, I need to get values from it, without any data changed (saves values to local cache). Then concatenate it with other Flowable f1 and send it to higher level class. Is it possible to emit values only once from f2?

Also how can I do action on all Items coming from Flowable f1, but after n Items create new Flowable f2 from f1.

答:
For your first question, doOnNext() is probably what you are looking for (http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html#doOnNext-io.reactivex.functions.Consumer-).

 private static void main() {
    Flowable<String> f2 = Flowable.just("a", "b", "c", "d", "e");
    Flowable<String> f1 = Flowable.just("z", "x", "y");

    f2.doOnNext(n -> System.out.println("saving " + n))
      .concatWith(f1)
      .subscribe(System.out::println);

    Flowable.timer(10, SECONDS) // Just to block the main thread for a while
            .blockingSubscribe();
}
```

<p>For your second question, it depends if you want to get rid of the items after the nth one. If so, you can use <code>take()</code>, if not you may have look at <code>buffer()</code>. </p>

<pre class="lang-java prettyprint-override"><code>    public static void main(String[] args) {
    Flowable<String> f1 = Flowable.just("a", "b", "c", "d", "e");
    Flowable<String> f2 = Flowable.just("z", "x", "y");

    f1.doOnNext(n -> System.out.println("action on " + n))
      .take(3)
      .subscribe(System.out::println);

    System.out.println("------------------------");
    System.out.println("Other possible use case:");
    System.out.println("------------------------");

    f1.doOnNext(n -> System.out.println("another action on " + n))
      .buffer(3)
      .flatMap(l -> Flowable.fromIterable(l).map(s -> "Hello " + s))
      .subscribe(System.out::println);

    Flowable.timer(10, SECONDS) // Just to block the main thread for a while
            .blockingSubscribe();
}
</code>```

You can have a look at the RxJava javadoc of Flowable (http://reactivex.io/RxJava/2.x/javadoc/index.html?io/reactivex/Flowable.html). It has lots of operators and marble diagrams explains very well what each operator does.

Title: How to do action on Flowable

Body:
For your first question, doOnNext() is probably what you are looking for (http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html#doOnNext-io.reactivex.functions.Consumer-).

 private static void main() {
    Flowable<String> f2 = Flowable.just("a", "b", "c", "d", "e");
    Flowable<String> f1 = Flowable.just("z", "x", "y");

    f2.doOnNext(n -> System.out.println("saving " + n))
      .concatWith(f1)
      .subscribe(System.out::println);

    Flowable.timer(10, SECONDS) // Just to block the main thread for a while
            .blockingSubscribe();
}

For your second question, it depends if you want to get rid of the items after the nth one. If so, you can use take(), if not you may have look at buffer().

    public static void main(String[] args) {
    Flowable<String> f1 = Flowable.just("a", "b", "c", "d", "e");
    Flowable<String> f2 = Flowable.just("z", "x", "y");

    f1.doOnNext(n -> System.out.println("action on " + n))
      .take(3)
      .subscribe(System.out::println);

    System.out.println("------------------------");
    System.out.println("Other possible use case:");
    System.out.println("------------------------");

    f1.doOnNext(n -> System.out.println("another action on " + n))
      .buffer(3)
      .flatMap(l -> Flowable.fromIterable(l).map(s -> "Hello " + s))
      .subscribe(System.out::println);

    Flowable.timer(10, SECONDS) // Just to block the main thread for a while
            .blockingSubscribe();
}

You can have a look at the RxJava javadoc of Flowable (http://reactivex.io/RxJava/2.x/javadoc/index.html?io/reactivex/Flowable.html). It has lots of operators and marble diagrams explains very well what each operator does.