问:
Controlling Chrome Devtools with Selenium Webdriver
I am looking to access/use Chrome's devtools panel with Selenium Webdriver.

Specifically, I want to use the "WASP" chrome plugin, which is accessed through devtools. I've got my selenium set up to run with the WASP plugin included, and I can open DevTools (with sendKeys.F12), but I don't know how to actually use that panel now that it is open. Is there a way to do so?

The closest thing I've found to my problem is this link: Chrome Dev Tools API & Selenium WebDriver, but that hasn't been helpful at all to me.

Also, if it looks like this will be impossible (which it does) can anyone think of a workaround?

答:
In Selenium 4 alpha, there is a way to interact with DevTools API using the java-client. What you are looking for specifically is the "Profiler" domain (https://chromedevtools.github.io/devtools-protocol/tot/Profiler)

Recently, I contributed the "Network" and "Performance" domains for a better user facing API in selenium java - https://github.com/SeleniumHQ/selenium/pull/7212

I believe that "Profiler" will also be implemented soon. Of course, there is a generic API for all domains in Java client that was merged a while ago, you can use it like this:

```<code>     driver.getDevTools().createSession();

    driver.getDevTools().send(new Command("Profiler.enable", ImmutableMap.of()));
    driver.getDevTools().send(new Command("Profiler.start", ImmutableMap.of()));

    //register to profiler events
    driver.getDevTools().addListener(new Event("Profiler.consoleProfileStarted", ConsoleProfileStarted.class), new Consumer<Object>() {
        @Override
        public void accept(Object o) {
            //do something
        }
    });
</code>```

Until the Profiler domain will added to Selenium java client, you will have to supply your Mapper.

Body:
In Selenium 4 alpha, there is a way to interact with DevTools API using the java-client. What you are looking for specifically is the "Profiler" domain (https://chromedevtools.github.io/devtools-protocol/tot/Profiler)

Recently, I contributed the "Network" and "Performance" domains for a better user facing API in selenium java - https://github.com/SeleniumHQ/selenium/pull/7212

I believe that "Profiler" will also be implemented soon. Of course, there is a generic API for all domains in Java client that was merged a while ago, you can use it like this:

     driver.getDevTools().createSession();

    driver.getDevTools().send(new Command("Profiler.enable", ImmutableMap.of()));
    driver.getDevTools().send(new Command("Profiler.start", ImmutableMap.of()));

    //register to profiler events
    driver.getDevTools().addListener(new Event("Profiler.consoleProfileStarted", ConsoleProfileStarted.class), new Consumer<Object>() {
        @Override
        public void accept(Object o) {
            //do something
        }
    });

Until the Profiler domain will added to Selenium java client, you will have to supply your Mapper.


来源: stackexchange

问:
PHP timezone Asia/Yangon show the wrong timezone
I found that Asia/Yangon is running the wrong timezone. You can see below this picture.

But when I use Asia/Rangoon, it run the correct timezone that I want. Refer to this LINK, there is no Asia/Rangoon, only have Asia/Yangon. So what's the problem why I can't use Asia/Yangon, the website is write there...

*If you wonder why I will use Asia/Rangoon, I found it at here. Beside Yangon there is Rangoon.

答:
The name Asia/Yangon was introduced in September 2016 with TZDB 2016g, where it became the canonical zone name for the time in Myanmar.  At the same time, Asia/Rangoon was created as a link entry, making it an alias to preserve backwards compatibility. In other words, Asia/Rangoon is an alias for Asia/Yangon.  They both refer to the time in Myanmar.

You can see this change in the tzdb sources here.

If your PHP installation does not recognize Asia/Yangon, then it has a TZDB release earlier to 2016g.  PHP gets its TZDB information via the timezonedb PECL package.  TZDB 2016g corresponds to timezonedb 2016.7, released on 2016-09-28.

PHP itself gets the latest version of timezonedb every time it puts out a release.  Thus, your PHP installation is likely very old and simply needs to be updated.

ContentLicense: CC BY-SA 4.0


问:
White line in contour plot in cartopy on center_longitude
I'm plotting some filled contours with Cartopy and Matplotlib. The data is on a latitude/longitude grid, and when plotting on a cartopy projection, a white line runs down the middle of the figure, or wherever I set "central_longitude" into in ccrs.PlateCarree()

Here is a quick setup that shows what I'm talking about. Using the code:

    import numpy as np
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    import cartopy.feature as cfeature

    lon = np.arange(0, 360, 1)
    lat = np.arange(-90, 90, 1)

    data = np.zeros((180, 360))

    fig = plt.figure()
    ax = plt.subplot(projection=ccrs.PlateCarree())
    ax.contourf(lon, lat, data)
    ax.add_feature(cfeature.COASTLINE.with_scale('50m'))
    plt.show()
```

Which produces the image:

Is there a way to remove this white line?

答:
You should use cartopy.util.add_cyclic_point so that contourf sees the data as continuous in the x-direction and the white line will disappear:

```<code>import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.util import add_cyclic_point

lon = np.arange(0, 360, 1)
lat = np.arange(-90, 90, 1)

data = np.zeros((180, 360))

data, lon = add_cyclic_point(data, coord=lon)

fig = plt.figure()
ax = plt.subplot(projection=ccrs.PlateCarree())
ax.contourf(lon, lat, data)
ax.add_feature(cfeature.COASTLINE.with_scale('50m'))
plt.show()
</code>```

Body:
I'm plotting some filled contours with Cartopy and Matplotlib. The data is on a latitude/longitude grid, and when plotting on a cartopy projection, a white line runs down the middle of the figure, or wherever I set "central_longitude" into in ccrs.PlateCarree()

Here is a quick setup that shows what I'm talking about. Using the code:

    import numpy as np
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    import cartopy.feature as cfeature

    lon = np.arange(0, 360, 1)
    lat = np.arange(-90, 90, 1)

    data = np.zeros((180, 360))

    fig = plt.figure()
    ax = plt.subplot(projection=ccrs.PlateCarree())
    ax.contourf(lon, lat, data)
    ax.add_feature(cfeature.COASTLINE.with_scale('50m'))
    plt.show()

Which produces the image:

Is there a way to remove this white line?

Body:
You should use cartopy.util.add_cyclic_point so that contourf sees the data as continuous in the x-direction and the white line will disappear:

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.util import add_cyclic_point

lon = np.arange(0, 360, 1)
lat = np.arange(-90, 90, 1)

data = np.zeros((180, 360))

data, lon = add_cyclic_point(data, coord=lon)

fig = plt.figure()
ax = plt.subplot(projection=ccrs.PlateCarree())
ax.contourf(lon, lat, data)
ax.add_feature(cfeature.COASTLINE.with_scale('50m'))
plt.show()


问:
ggplot2: Add secondary x label (year below months)
My Problem is related to: Axis labels on two lines with nested x variables (year below months)

However, my data looks a little different.

```<code>library(dplyr)

set.seed(122)
df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))

df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
      "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)
</code>```

I would like my line graph too look like this, but without the vertical line if possible:

答:
library(tidyverse)

#data:
set.seed(122)
df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))
#> Warning: Calling `as_tibble()` on a vector is discouraged,
#> because the behavior is likely to change in the future.
#> Use `tibble::enframe(name = NULL)` instead.

df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
                  "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)

#solution:
month_lab <- rep(unique(df$month), length(unique(df$year)))

year_lab <- unique(df$year)

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = year)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = month_lab, expand = c(0,0)) +
  facet_grid(~year, space="free_x", scales="free_x", switch="x") +
  theme(strip.placement = "outside",
        strip.background = element_rect(fill=NA,colour="grey50"),
        panel.spacing=unit(0,"cm"))
```

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

Body:
My Problem is related to: Axis labels on two lines with nested x variables (year below months)

However, my data looks a little different.

library(dplyr)

set.seed(122)
df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))

df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
      "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)

I would like my line graph too look like this, but without the vertical line if possible:

Body:
library(tidyverse)

#data:
set.seed(122)
df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))
#> Warning: Calling `as_tibble()` on a vector is discouraged,
#> because the behavior is likely to change in the future.
#> Use `tibble::enframe(name = NULL)` instead.

df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
                  "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)

#solution:
month_lab <- rep(unique(df$month), length(unique(df$year)))

year_lab <- unique(df$year)

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = year)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = month_lab, expand = c(0,0)) +
  facet_grid(~year, space="free_x", scales="free_x", switch="x") +
  theme(strip.placement = "outside",
        strip.background = element_rect(fill=NA,colour="grey50"),
        panel.spacing=unit(0,"cm"))

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


问:
Laravel same view with different Options depending on the way to get there
I have a Laravel Web-Application and a view in it that shows all the cars from the database. (It's a booking system for cars)

Now I want to have a button in that view, that allows a user to add and delete cars , but I only want this button to appear when the view is accessed over a certain button. When the view is accessed in any other way (other button or typing the link manually,) the button (to add/delete cars) should not be seen.

How can I realize that in a nice and clean way?

Best regards,

Alex

答:
You can put those buttons in if conditions

Here I used $show_button variable just for an example

You can use your conditional data as per your requirements

In controller:

Here I used my_index.blade.php just for an example

```<code>public function index(){
   $show_button == 1; //set value as per your requirement

   return view('my_index', compact('show_button'));
}
</code>```

In blade file:

```<code>@if($show_button == 1)
   <button class="btn btn-primary">Button-1</button>
   <button class="btn btn-primary">Button-2</button>
@endif
</code>```

OR

If you want to display those buttons on click of another button then use jquery or javascript

```<code>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>

<div id="action_div" style="display:none;">
    <button class="btn btn-primary">Edit</button>
    <button class="btn btn-danger">Delete</button>
</div>

<button class="other_button">show action buttons</button>

<script>
    $(document).ready(function(){

        $('.other_button').on('click', function(){
            $(document).find('#action_div').show();
        });

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

Body:
You can put those buttons in if conditions

Here I used $show_button variable just for an example

You can use your conditional data as per your requirements

In controller:

Here I used my_index.blade.php just for an example

public function index(){
   $show_button == 1; //set value as per your requirement

   return view('my_index', compact('show_button'));
}

In blade file:

@if($show_button == 1)
   <button class="btn btn-primary">Button-1</button>
   <button class="btn btn-primary">Button-2</button>
@endif

OR

If you want to display those buttons on click of another button then use jquery or javascript

<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>

<div id="action_div" style="display:none;">
    <button class="btn btn-primary">Edit</button>
    <button class="btn btn-danger">Delete</button>
</div>

<button class="other_button">show action buttons</button>

<script>
    $(document).ready(function(){

        $('.other_button').on('click', function(){
            $(document).find('#action_div').show();
        });

    });
</script>


问:
Pandas - Replace values based on index and not in index
Here is the sample code.

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

df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A'))
</code>```

I have a list dl=[0,2,3,4,7]

At the index positions specified by list, I would like to have column A as "Yes".

The following code works

```<code>df.loc[dl,'A']='Yes'
</code>```

How do I fill column 'A' with 'No' for column values not in index.
Please forgive me if this is a duplicate post.

答:
First fill all rows of "A" with "No". Then update/overwrite the specific rows with "Yes".</p>

```<code>df.loc[:,'A']='No'
df.loc[dl,'A']='Yes'
</code>```

Body:
Here is the sample code.

import pandas as pd, numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A'))

I have a list dl=[0,2,3,4,7]

At the index positions specified by list, I would like to have column A as "Yes".

The following code works

df.loc[dl,'A']='Yes'

How do I fill column 'A' with 'No' for column values not in index.
Please forgive me if this is a duplicate post.

Body:
First fill all rows of "A" with "No". Then update/overwrite the specific rows with "Yes".

df.loc[:,'A']='No'
df.loc[dl,'A']='Yes'


问:
Spring Thymeleaf shortening url (form - get) parameters
Current state :

https://localhost:8443/workaround/?query=dasda&atn=s&filterSoftwareType=ANY.....

Desired state :
https://localhost:8443/workaround/?q=dasda&atn=s&fst=ANY.....

Shorten url by using q instead of query and fst instead of filterSoftwareType

My thymeleaf html looks like this, short sample :

```<code><form action="#" class="card card-sm rounded"
                  method="get"
                  th:action="@{${T(com.bisciak.workaround.util.Utils).MAPPING_INDEX}}" th:object="${search}">

     <div class="col">
           <input class="form-control form-control-lg form-control-borderless"
                               placeholder="Search here"
                               style="padding-left: 1rem"
                               th:field="${search.query}" type="search"/>
     </div> etc...
</code>```

Controller :

```<code>  @GetMapping(value = Utils.MAPPING_INDEX, params = "atn=s")
 public ModelAndView indexActionSearch(@ModelAttribute(name = "s") Optional<Search> search .....
</code>```

Search object has properties like query etc, bud I dont want to rename those for sure! It would be just horrible naming thruought the code I only want to use short versions for URL.

Anyone has idea how to do this? I have tried name attribute on input bud that didnt helped :/.

I also want to keep stuff in the form so url is automatically build.
I also want to keep this as get and not a post so user can share easily this link via copy paste etc from URL bar. With post he would not see that.

答:
The th:field attribute is to easily build a form from a Java object, and for the fields to post back using same names so the values can be auto-assigned back into a Java object, of the same type, on the server.

If you want different names, then you're not using it for it's intended purpose, so stop using it.

If you look at the documentation, i.e. chapter 7.2 Inputs, you see what th:fields does:

Let’s see now how to add an input to our form:

<input type="text" th:field="*{datePlanted}" />
```
<p>... In this case (<code>input[type=text]</code>), the above line of code is similar to:</p>
<pre class="lang-html prettyprint-override"><code><input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" />
</code>```

So, change your code to do this:

<form ... th:object="${search}">

    <input ... name="q" th:value="*{query}"/>
```

Whether you also need id="q" is up to you.

Note that if you use th:value="${search.query}", then there is no need for th:object="${search}"

Body:
Current state :

https://localhost:8443/workaround/?query=dasda&atn=s&filterSoftwareType=ANY.....

Desired state :
https://localhost:8443/workaround/?q=dasda&atn=s&fst=ANY.....

Shorten url by using q instead of query and fst instead of filterSoftwareType

My thymeleaf html looks like this, short sample :

<form action="#" class="card card-sm rounded"
                  method="get"
                  th:action="@{${T(com.bisciak.workaround.util.Utils).MAPPING_INDEX}}" th:object="${search}">

           <input class="form-control form-control-lg form-control-borderless"
                               placeholder="Search here"
                               style="padding-left: 1rem"
                               th:field="${search.query}" type="search"/>

 etc...

Controller :

  @GetMapping(value = Utils.MAPPING_INDEX, params = "atn=s")
 public ModelAndView indexActionSearch(@ModelAttribute(name = "s") Optional<Search> search .....

Search object has properties like query etc, bud I dont want to rename those for sure! It would be just horrible naming thruought the code I only want to use short versions for URL.

Anyone has idea how to do this? I have tried name attribute on input bud that didnt helped :/.

I also want to keep stuff in the form so url is automatically build.
I also want to keep this as get and not a post so user can share easily this link via copy paste etc from URL bar. With post he would not see that.

Body:
The th:field attribute is to easily build a form from a Java object, and for the fields to post back using same names so the values can be auto-assigned back into a Java object, of the same type, on the server.

If you want different names, then you're not using it for it's intended purpose, so stop using it.

If you look at the documentation, i.e. chapter 7.2 Inputs, you see what th:fields does:

Let’s see now how to add an input to our form:

<input type="text" th:field="*{datePlanted}" />

... In this case (input[type=text]), the above line of code is similar to:

<input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" />

So, change your code to do this:

<form ... th:object="${search}">

    <input ... name="q" th:value="*{query}"/>

Whether you also need id="q" is up to you.

Note that if you use th:value="${search.query}", then there is no need for th:object="${search}"


问:
Does this RegExp string need some escaping?
I was trying to use a RegExp so that I could insert a string variable at some later point. But even this first attempt without said variable won't work. What is missing?

There's a nice jsbin linked that shows the behavior.

```<code>const DOCS = [
    "My Report – March 2019.pdf",
    "My Report – May 2019.pdf",
    "My Diary - April-May 2019.pdf",
    "My Diary - February-March 2019.pdf"
]

const title_month_year = new RegExp("(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")

DOCS.forEach(
    mag = mag.replace(/–/g, "-");
//  if (title_month_year.test(mag)) {   <--- does not match
    if (/(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})/.test(mag)) {
        console.log('we have a match');
    }
</code>```

https://jsbin.com/lomolew/edit?js,console

答:
You forgot to escape the \d{2}

it should be \\d{2} inside of a RegExp string.

Body:
I was trying to use a RegExp so that I could insert a string variable at some later point. But even this first attempt without said variable won't work. What is missing?

There's a nice jsbin linked that shows the behavior.

const DOCS = [
    "My Report – March 2019.pdf",
    "My Report – May 2019.pdf",
    "My Diary - April-May 2019.pdf",
    "My Diary - February-March 2019.pdf"
]

const title_month_year = new RegExp("(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")

DOCS.forEach(
    mag = mag.replace(/–/g, "-");
//  if (title_month_year.test(mag)) {   <--- does not match
    if (/(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})/.test(mag)) {
        console.log('we have a match');
    }

https://jsbin.com/lomolew/edit?js,console


问:
Which APDU to use to read/write records on MIFARE Ultralight NFC tag?
I am creating a VBA software to read and write NFC tags. I managed to communicate with the tag to obtain basic data (for example I got its ID). But when I send an APDU for a READ RECORD command, it does not work. I suppose I need to send a SELECT FILE command before; but I think I need the correct DF for this.

I tried the "00 B2 01 05 00" for the READ RECORD command and "00 A4 00 00 00" for the SELECT FILE command.

```<code>VBA
Sub test()
Dim hContext As Long
Dim hCard As Long
Dim retval As Long
Dim readers As String * 256
Dim groups As String * 256
Dim activeprotocol As Long
Dim readerlen As Long
Dim scard_protocol_t0_or_t1 As Long
Dim scard_share_shared As Long
Dim APDU() As Byte
Dim recvbuf() As Byte
Dim recvbuff(256) As ByteArray
Dim recvlen As Long
Dim iosendreq As SCARD_IO_REQUEST
Dim iorecvreq As SCARD_IO_REQUEST
Dim bytRecvAttr As ByteArray
Dim LenAPDU As Long

scard_protocol_t0_or_t1 = 1 Or 2
scard_share_shared = 2 '2  1

retval = SCardEstablishContext(SCARD_SCOPE_USER, 0, 0, hContext)
If retval <> 0 Then
    MsgBox "erreur n." & CStr(retval)
End If

readerlen = 256

retval = SCardListReaders(hContext, groups, readers, readerlen)
If retval <> 0 Then
    MsgBox "erreur n. " & CStr(retval)
End If

Do While hCard = 0
    retval = SCardConnect(hContext, readers, scard_share_shared,         scard_protocol_t0_or_t1, hCard, activeprotocol)
    DoEvents
Loop
If retval <> 0 Then MsgBox "erreur n. " & CStr(retval)

recvlen = 256

Do While State < 2
    retval = SCardStatus(hCard, readers, readerlen, State,     scard_protocol_t0_or_t1, recvbuff(0), recvlen)
    If retval <> 0 Then MsgBox "Erreur n. " & CStr(retval)
    DoEvents
Loop

'retval = SCardGetAttrib(hCard, SCARD_ATTR_ICC_PRESENCE, bytRecvAttr, lRecLen)
'If retval <> 0 Then MsgBox "Erreur n. " & CStr(retval)

iosendreq.dwProtocol = activeprotocol
iosendreq.dwPciLength = Len(iosendreq)
iorecvreq.dwProtocol = activeprotocol
iorecvreq.dwPciLength = Len(iorecvreq)

'recherche de file
ReDim APDU(7)
APDU(0) = &H0    'cla  80
APDU(1) = &HA4  'INs  B2-read record
APDU(2) = &H4   'P1 1-PREMIER RECORD
APDU(3) = &H0   'P2   5-tous les records
APDU(4) = &H2   'longueur de data
APDU(5) = &H0   'a changer pour trouver ID du DF
APDU(6) = &H0   'a changer pour trouver ID du DF
APDU(7) = &H0   'Le

LenAPDU = (UBound(APDU) + 1)
If APDU(LenAPDU - 1) = 0 Then
    ReDim recvbuf(255)
Else
    ReDim recvbuf(APDU(LenAPDU - 1) + 2)
End If
recvlen = UBound(recvbuf) + 1

'this is a loop to test the different DFs
For x = 0 To 255
    For y = 1 To 255
        APDU(5) = x
        APDU(6) = y
        retval = SCardTransmit(hCard, iosendreq, APDU(0), LenAPDU, iorecvreq, recvbuf(0), recvlen)
        If recvbuf(4) > 0 Or recvlen > 2 Then Exit For
    Next
Next

Debug.Print Hex(recvbuf(0)) & "-" & Hex(recvbuf(1)) & "-" & Hex(recvbuf(2)) & "-" & Hex(recvbuf(3)) & "-" & Hex(recvbuf(4)) & "-" & Hex(recvbuf(5)) & "-" & Hex(recvbuf(6)) & "-" & Hex(recvbuf(7)) & " " & recvlen & " CLA:" & APDU(0) & " INS:" & APDU(1) & " P1:" & APDU(2) & " P2:" & APDU(3)

If retval <> 0 Then MsgBox "Erreur n. " & CStr(Hex(retval))

retval = SCardDisconnect(hCard, scad_leave_card)
If retval <> 0 Then MsgBox "erreur n. " & CStr(retval)

retval = SCardReleaseContext(hContext)
If retval <> 0 Then MsgBox "erreur n. " & CStr(retval)

End Sub
</code>```

答:
MIFARE Ultralight tags do not use APDU commands. Hence, you cannot send any APDUs to the tag itself and the tag does not support the notion of files (EF/DF/MF). Instead, PC/SC (contactless) smartcard readers usually provide a set of APDUs that can be sent to the reader and that the reader translates into MIFARE Ultralight commands. These APDU commands that are processed by the reader typically start with the class byte &HFF.

If the reader implements the standard PC/SC extensions for access to contactless memory cards, the reader APDU to read from Ultralight tags would look like:

```
FF B0 00XX 10
        ^^
         \-------- Block number
```

Hence, your APDU would look like this:

```<code>ReDim APDU(5)
APDU(0) = &HFF  'CLA  0xFF = PC/SC READER COMMAND
APDU(1) = &HB0  'INS  0xB0 = READ BINARY
APDU(2) = &H00  'P1   0x00
APDU(3) = &H00  'P2   block number (potentially also in P1 if more than 255)
APDU(4) = &H10  'Le   0x10 = 16 bytes (= 4 blocks) expected, which is the standard read size for the native Ultralight READ command
</code>```

Body:
I am creating a VBA software to read and write NFC tags. I managed to communicate with the tag to obtain basic data (for example I got its ID). But when I send an APDU for a READ RECORD command, it does not work. I suppose I need to send a SELECT FILE command before; but I think I need the correct DF for this.

I tried the "00 B2 01 05 00" for the READ RECORD command and "00 A4 00 00 00" for the SELECT FILE command.

VBA
Sub test()
Dim hContext As Long
Dim hCard As Long
Dim retval As Long
Dim readers As String * 256
Dim groups As String * 256
Dim activeprotocol As Long
Dim readerlen As Long
Dim scard_protocol_t0_or_t1 As Long
Dim scard_share_shared As Long
Dim APDU() As Byte
Dim recvbuf() As Byte
Dim recvbuff(256) As ByteArray
Dim recvlen As Long
Dim iosendreq As SCARD_IO_REQUEST
Dim iorecvreq As SCARD_IO_REQUEST
Dim bytRecvAttr As ByteArray
Dim LenAPDU As Long

scard_protocol_t0_or_t1 = 1 Or 2
scard_share_shared = 2 '2  1

retval = SCardEstablishContext(SCARD_SCOPE_USER, 0, 0, hContext)
If retval <> 0 Then
    MsgBox "erreur n." & CStr(retval)
End If

readerlen = 256

retval = SCardListReaders(hContext, groups, readers, readerlen)
If retval <> 0 Then
    MsgBox "erreur n. " & CStr(retval)
End If

Do While hCard = 0
    retval = SCardConnect(hContext, readers, scard_share_shared,         scard_protocol_t0_or_t1, hCard, activeprotocol)
    DoEvents
Loop
If retval <> 0 Then MsgBox "erreur n. " & CStr(retval)

recvlen = 256

Do While State < 2
    retval = SCardStatus(hCard, readers, readerlen, State,     scard_protocol_t0_or_t1, recvbuff(0), recvlen)
    If retval <> 0 Then MsgBox "Erreur n. " & CStr(retval)
    DoEvents
Loop

'retval = SCardGetAttrib(hCard, SCARD_ATTR_ICC_PRESENCE, bytRecvAttr, lRecLen)
'If retval <> 0 Then MsgBox "Erreur n. " & CStr(retval)

iosendreq.dwProtocol = activeprotocol
iosendreq.dwPciLength = Len(iosendreq)
iorecvreq.dwProtocol = activeprotocol
iorecvreq.dwPciLength = Len(iorecvreq)

'recherche de file
ReDim APDU(7)
APDU(0) = &H0    'cla  80
APDU(1) = &HA4  'INs  B2-read record
APDU(2) = &H4   'P1 1-PREMIER RECORD
APDU(3) = &H0   'P2   5-tous les records
APDU(4) = &H2   'longueur de data
APDU(5) = &H0   'a changer pour trouver ID du DF
APDU(6) = &H0   'a changer pour trouver ID du DF
APDU(7) = &H0   'Le

LenAPDU = (UBound(APDU) + 1)
If APDU(LenAPDU - 1) = 0 Then
    ReDim recvbuf(255)
Else
    ReDim recvbuf(APDU(LenAPDU - 1) + 2)
End If
recvlen = UBound(recvbuf) + 1

'this is a loop to test the different DFs
For x = 0 To 255
    For y = 1 To 255
        APDU(5) = x
        APDU(6) = y
        retval = SCardTransmit(hCard, iosendreq, APDU(0), LenAPDU, iorecvreq, recvbuf(0), recvlen)
        If recvbuf(4) > 0 Or recvlen > 2 Then Exit For
    Next
Next

Debug.Print Hex(recvbuf(0)) & "-" & Hex(recvbuf(1)) & "-" & Hex(recvbuf(2)) & "-" & Hex(recvbuf(3)) & "-" & Hex(recvbuf(4)) & "-" & Hex(recvbuf(5)) & "-" & Hex(recvbuf(6)) & "-" & Hex(recvbuf(7)) & " " & recvlen & " CLA:" & APDU(0) & " INS:" & APDU(1) & " P1:" & APDU(2) & " P2:" & APDU(3)

If retval <> 0 Then MsgBox "Erreur n. " & CStr(Hex(retval))

retval = SCardDisconnect(hCard, scad_leave_card)
If retval <> 0 Then MsgBox "erreur n. " & CStr(retval)

retval = SCardReleaseContext(hContext)
If retval <> 0 Then MsgBox "erreur n. " & CStr(retval)

End Sub

Body:
MIFARE Ultralight tags do not use APDU commands. Hence, you cannot send any APDUs to the tag itself and the tag does not support the notion of files (EF/DF/MF). Instead, PC/SC (contactless) smartcard readers usually provide a set of APDUs that can be sent to the reader and that the reader translates into MIFARE Ultralight commands. These APDU commands that are processed by the reader typically start with the class byte &HFF.

If the reader implements the standard PC/SC extensions for access to contactless memory cards, the reader APDU to read from Ultralight tags would look like:

FF B0 00XX 10
        ^^
         \-------- Block number

Hence, your APDU would look like this:

ReDim APDU(5)
APDU(0) = &HFF  'CLA  0xFF = PC/SC READER COMMAND
APDU(1) = &HB0  'INS  0xB0 = READ BINARY
APDU(2) = &H00  'P1   0x00
APDU(3) = &H00  'P2   block number (potentially also in P1 if more than 255)
APDU(4) = &H10  'Le   0x10 = 16 bytes (= 4 blocks) expected, which is the standard read size for the native Ultralight READ command


问:
submenu under menu are not displaying
I have four menus in which one menu have 2 submenus I'm using bootstrap for this but after many tries, I'm not getting any way to solve it as I'm new to it. The main menu is not displaying the submenu when clicked.

I have tried various possible ways and when I'm adding CDN to my project it's working fine. But when I'm adding the bootstrap file from my local storage it's not displaying. But other features are working fine

```<code><link rel="stylesheet" href="css/bootstrap.css">
<style>
    .header {
        height: 50px;
        background-color: black;
        margin-top: 3px;
    }

    .column {
        margin-left: 100px;
    }
</style>
<body>
    <nav class="navbar navbar-expand-sm  navbar-dark bg-dark header">
        <a href="#" class="navbar-brand">Stone</a>
        <ul class="nav navbar-nav column">
            <li class="nav-item"><a href="#" class="nav-link">Home</a></li>
            <li class="nav-item"><a href="#" class="nav-link">Add Employee</a></li>

            <li class="nav-item dropdown">
                <a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown" id="searchEmp" role="button">Search Employee</a>
                <div class="dropdown-menu" aria-labelledby="searchEmp">
                    <a href="#" class="dropdown-item">Search With ID</a>
                    <a href="#" class="dropdown-item">Search All Employee</a>
                </div>
            </li>
            <li class="nav-item"><a href="#" class="nav-link">About</a></li>
        </ul>
    </nav>

    <script src="js/bootstrap.js"></script>
    <script src="js/jquery-3.4.1.js"></script>
</body>
</code>```

In console it's not showing any error

答:
Bootstrap's Javascript is dependent on jQuery. That means that in order for it to work properly, jQuery needs to be loaded first. If you switch the following lines around it should work.</p>

```<code><script src="js/bootstrap.js"></script>
<script src="js/jquery-3.4.1.js"></script>
</code>```

Title: submenu under menu are not displaying

Body:
I have four menus in which one menu have 2 submenus I'm using bootstrap for this but after many tries, I'm not getting any way to solve it as I'm new to it. The main menu is not displaying the submenu when clicked.

I have tried various possible ways and when I'm adding CDN to my project it's working fine. But when I'm adding the bootstrap file from my local storage it's not displaying. But other features are working fine

<link rel="stylesheet" href="css/bootstrap.css">

        Stone

Home

Add Employee

                Search Employee

                    Search With ID
                    Search All Employee

About

In console it's not showing any error

Body:
Bootstrap's Javascript is dependent on jQuery. That means that in order for it to work properly, jQuery needs to be loaded first. If you switch the following lines around it should work.

<script src="js/bootstrap.js"></script>
<script src="js/jquery-3.4.1.js"></script>


问:
to validate checkbox input for table using multiple rows
i using js to add multiple row in a particular table, but when submit the form all check box having the same value, so how can i validate this checkbox using js before submit so change value to if unchecked, i trying on that but got no solution, does any one this before,

thanks in advance

答:
What are your checkboxes called? Do they all have the same name? You have two options. One is giving each checkbox an unique name, the other is giving your checkbox a name like checkboxes[]. The [] lets all the values be entered into an array so they don't overwrite eachother.

If you mean something else, you have to state more clear what you want, because it's a bit incomprehensible right now.

ContentLicense: CC BY-SA 3.0


问:
Node.js Piping the same readable stream into multiple (writable) targets
I need to run two commands in series that need to read data from the same stream.
After piping a stream into another the buffer is emptied so i can't read data from that stream again so this doesn't work:

```<code>var spawn = require('child_process').spawn;
var fs = require('fs');
var request = require('request');

var inputStream = request('http://placehold.it/640x360');
var identify = spawn('identify',['-']);

inputStream.pipe(identify.stdin);

var chunks = [];
identify.stdout.on('data',function(chunk) {
  chunks.push(chunk);
});

identify.stdout.on('end',function() {
  var size = getSize(Buffer.concat(chunks)); //width
  var convert = spawn('convert',['-','-scale',size * 0.5,'png:-']);
  inputStream.pipe(convert.stdin);
  convert.stdout.pipe(fs.createWriteStream('half.png'));
});

function getSize(buffer){
  return parseInt(buffer.toString().split(' ')[2].split('x')[0]);
}
</code>```

Request complains about this

```<code>Error: You cannot pipe after data has been emitted from the response.
</code>```

and changing the inputStream to fs.createWriteStream yields the same issue of course.
I don't want to write into a file but reuse in some way the stream that request produces (or any other for that matter).

Is there a way to reuse a readable stream once it finishes piping?
What would be the best way to accomplish something like the above example?

答:
If you have async operations on the PassThrough streams, the answers posted here won't work.
A solution that works for async operations includes buffering the stream content and then creating streams from the buffered result.

To buffer the result you can use concat-stream

```<code>const Promise = require('bluebird');
const concat = require('concat-stream');
const getBuffer = function(stream){
    return new Promise(function(resolve, reject){
        var gotBuffer = function(buffer){
            resolve(buffer);
        }
        var concatStream = concat(gotBuffer);
        stream.on('error', reject);
        stream.pipe(concatStream);
    });
}
</code>```

To create streams from the buffer you can use:

```<code>const { Readable } = require('stream');
const getBufferStream = function(buffer){
    const stream = new Readable();
    stream.push(buffer);
    stream.push(null);
    return Promise.resolve(stream);
}
</code>```

Body:
I need to run two commands in series that need to read data from the same stream.
After piping a stream into another the buffer is emptied so i can't read data from that stream again so this doesn't work:

var spawn = require('child_process').spawn;
var fs = require('fs');
var request = require('request');

var inputStream = request('http://placehold.it/640x360');
var identify = spawn('identify',['-']);

inputStream.pipe(identify.stdin);

var chunks = [];
identify.stdout.on('data',function(chunk) {
  chunks.push(chunk);
});

identify.stdout.on('end',function() {
  var size = getSize(Buffer.concat(chunks)); //width
  var convert = spawn('convert',['-','-scale',size * 0.5,'png:-']);
  inputStream.pipe(convert.stdin);
  convert.stdout.pipe(fs.createWriteStream('half.png'));
});

function getSize(buffer){
  return parseInt(buffer.toString().split(' ')[2].split('x')[0]);
}

Request complains about this

Error: You cannot pipe after data has been emitted from the response.

and changing the inputStream to fs.createWriteStream yields the same issue of course.
I don't want to write into a file but reuse in some way the stream that request produces (or any other for that matter).

Is there a way to reuse a readable stream once it finishes piping?
What would be the best way to accomplish something like the above example?

Body:
If you have async operations on the PassThrough streams, the answers posted here won't work.
A solution that works for async operations includes buffering the stream content and then creating streams from the buffered result.

To buffer the result you can use concat-stream

const Promise = require('bluebird');
const concat = require('concat-stream');
const getBuffer = function(stream){
    return new Promise(function(resolve, reject){
        var gotBuffer = function(buffer){
            resolve(buffer);
        }
        var concatStream = concat(gotBuffer);
        stream.on('error', reject);
        stream.pipe(concatStream);
    });
}

To create streams from the buffer you can use:

const { Readable } = require('stream');
const getBufferStream = function(buffer){
    const stream = new Readable();
    stream.push(buffer);
    stream.push(null);
    return Promise.resolve(stream);
}


问:
How do I query a table in SQL to produce a result where column names are stacked vertically based on a condition?
Suppose I have a SQL table titled Users with the following example data:

```<code>Description          Days
--------------------------
Healthy               10
High-blood pressure   20
Cholesterol           23
Diabetes              31
High-blood pressure   8
Healthy               12
Diabetes              18
Cholesterol           25
High-blood pressure   20
Healthy               6
</code>```

How would I produce a result that looks like the following where the columns: Less_than_20_days, 20_days and Greater_than_20_days contains counts from the table above

```<code>Description         Less_than_20_days         20_days         Greater_than_20_days
-----------------------------------------------------------------------------------
Healthy                    3                     0                     0
High-blood pressure        1                     2                     0
Cholesterol                0                     0                     2
Diabetes                   1                     0                     1
</code>```

I'm trying to get this to work in SQL Server and have tried using the union operator, temp tables and ctes but I can't seem to get the desired result.

Any help would be much appreciated!

答:
You can combine case with sum():

```<code>select
     [Description]
    ,sum(case when [Days] < 20 then 1 else 0 end) as Less_than_20_days
    ,sum(case when [Days] = 20 then 1 else 0 end) as d20_days
    ,sum(case when [Days] > 20 then 1 else 0 end) as Greater_than_20_days
from users
group by [Description]
</code>```

Body:
Suppose I have a SQL table titled Users with the following example data:

Description          Days
--------------------------
Healthy               10
High-blood pressure   20
Cholesterol           23
Diabetes              31
High-blood pressure   8
Healthy               12
Diabetes              18
Cholesterol           25
High-blood pressure   20
Healthy               6

How would I produce a result that looks like the following where the columns: Less_than_20_days, 20_days and Greater_than_20_days contains counts from the table above

Description         Less_than_20_days         20_days         Greater_than_20_days
-----------------------------------------------------------------------------------
Healthy                    3                     0                     0
High-blood pressure        1                     2                     0
Cholesterol                0                     0                     2
Diabetes                   1                     0                     1

I'm trying to get this to work in SQL Server and have tried using the union operator, temp tables and ctes but I can't seem to get the desired result.

Any help would be much appreciated!

Body:
You can combine case with sum():

select
     [Description]
    ,sum(case when [Days] < 20 then 1 else 0 end) as Less_than_20_days
    ,sum(case when [Days] = 20 then 1 else 0 end) as d20_days
    ,sum(case when [Days] > 20 then 1 else 0 end) as Greater_than_20_days
from users
group by [Description]


问:
How can I implement auto-save using time-interval with form that does an HTTP post?
I have a web application that posts a form to a Node.js webservice:

```<code>...method="post" action="/kudosapi/report"...
</code>```

Now I need to implement an auto-save feature on this form. I can work out how to detect changes, etc., but what I'm not sure about is how (or IF) I can leverage this same HTML form action.

In the current design, once the user clicks a [Save] button, the form is submitted and the Node.js service redirects them back to another, i.e., the main, screen (this page is an editor).

My first instinct was to pass a parameter in the form to let the service know that's being auto-saved so it would not do the re-direct but I'm not sure that's sufficient.

Suggestions now how I can do this w/o completely rewriting the form/API?

Thanks!

答:
What you need to know in this case is that there is a difference in how you can POST data from the client: you can do it synchronously or asynchronously. Sending a POST in an asynchronous way is what you want to do here, and you can do that with an ajax request the likes of:

```<code>$.ajax( {
  method : "POST" ,
  url    : "/kudosapi/report" ,
  [ .. ]
} );
</code>```

Body:
I have a web application that posts a form to a Node.js webservice:

...method="post" action="/kudosapi/report"...

Now I need to implement an auto-save feature on this form. I can work out how to detect changes, etc., but what I'm not sure about is how (or IF) I can leverage this same HTML form action.

In the current design, once the user clicks a [Save] button, the form is submitted and the Node.js service redirects them back to another, i.e., the main, screen (this page is an editor).

My first instinct was to pass a parameter in the form to let the service know that's being auto-saved so it would not do the re-direct but I'm not sure that's sufficient.

Suggestions now how I can do this w/o completely rewriting the form/API?

Thanks!

Body:
What you need to know in this case is that there is a difference in how you can POST data from the client: you can do it synchronously or asynchronously. Sending a POST in an asynchronous way is what you want to do here, and you can do that with an ajax request the likes of:

$.ajax( {
  method : "POST" ,
  url    : "/kudosapi/report" ,
  [ .. ]
} );


答:
Use conditional aggregation:</p>

```<code>select description,
       sum(case when days < 20 then 1 else 0 end) as num_lt_20,
       sum(case when days = 20 then 1 else 0 end) as num_eq_20,
       sum(case when days > 20 then 1 else 0 end) as num_gt_20
from t
group by description
</code>```

Title: How do I query a table in SQL to produce a result where column names are stacked vertically based on a condition?

Body:
Use conditional aggregation:

select description,
       sum(case when days < 20 then 1 else 0 end) as num_lt_20,
       sum(case when days = 20 then 1 else 0 end) as num_eq_20,
       sum(case when days > 20 then 1 else 0 end) as num_gt_20
from t
group by description


问:
OpenSSL won't create private keys?
Okay, well, this is my first time working with encryption on a project. I am using my hosting provider for SSL, but I also want to encrypt portions of the database that are sensitive. For this, I was told to use OpenSSL. I am testing it on my localhost (WAMP), and have installed OpenSSL and turned on the PHP and Apache SSL mods. Okay, so i've been following tutorials and, using several suggested methods, have been able to generate the public key and store it as a file. For some reason, I can't seem to generate the private key. I will post two versions of code that i've tried:

```<code>// generate private key
$privateKey = openssl_pkey_new(array(
    'private_key_bits' => 1024,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');
// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);
// write public key to file
file_put_contents('public.key', $publicKey['key']);
// clear key
echo $privateKey;

?>
</code>```

This generates a public.key file, but provides me the warnings "openssl_pkey_export_to_file(): cannot get key from parameter 1:" and " openssl_pkey_get_details() expects parameter 1 to be resource, boolean."

I also tried an alternative method:

```<code>$config = array(
    "config" => "E:/wamp/bin/apache/apache2.2.22/conf/openssl.cnf",
    "digest_alg" => "sha512",
    "private_key_bits" => 1024,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

// Create the private and public key
$res = openssl_pkey_new($config);

// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey, NULL);
echo "Private Key: ".$privKey;
// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];
echo "Public Key: ".$pubKey;
$data = 'plaintext data goes here';
echo "Data: ".$data;
// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);
echo "Encrypted: ".$encrypted;
// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);

echo "Decrypted: ".$decrypted;
</code>```

This was supposed to echo everything, unfortunately my result was a blank private key, a fine public key, plaintext, and encrypted text, and an error when trying to decrypt: "openssl_private_decrypt(): key parameter is not a valid private key"

Clearly, i'm having a problem with private key creation. I've searched the internet thoroughly and haven't been able to fix it, even though I've implemented simple code that seems to work for everyone else.

Thanks in advance,
Elie Zeitouni

答:
This worked for wampp/php 7.0.4</p>

```<code>$privateKey = openssl_pkey_new(array(
'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
 ));

// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');

// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);

// write public key to file
file_put_contents('public.key', $publicKey['key']);

// clear key
echo $privateKey;
</code>```

Title: OpenSSL won't create private keys?

Body:
Okay, well, this is my first time working with encryption on a project. I am using my hosting provider for SSL, but I also want to encrypt portions of the database that are sensitive. For this, I was told to use OpenSSL. I am testing it on my localhost (WAMP), and have installed OpenSSL and turned on the PHP and Apache SSL mods. Okay, so i've been following tutorials and, using several suggested methods, have been able to generate the public key and store it as a file. For some reason, I can't seem to generate the private key. I will post two versions of code that i've tried:

// generate private key
$privateKey = openssl_pkey_new(array(
    'private_key_bits' => 1024,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');
// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);
// write public key to file
file_put_contents('public.key', $publicKey['key']);
// clear key
echo $privateKey;

?>

This generates a public.key file, but provides me the warnings "openssl_pkey_export_to_file(): cannot get key from parameter 1:" and " openssl_pkey_get_details() expects parameter 1 to be resource, boolean."

I also tried an alternative method:

$config = array(
    "config" => "E:/wamp/bin/apache/apache2.2.22/conf/openssl.cnf",
    "digest_alg" => "sha512",
    "private_key_bits" => 1024,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

// Create the private and public key
$res = openssl_pkey_new($config);

// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey, NULL);
echo "Private Key: ".$privKey;
// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];
echo "Public Key: ".$pubKey;
$data = 'plaintext data goes here';
echo "Data: ".$data;
// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);
echo "Encrypted: ".$encrypted;
// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);

echo "Decrypted: ".$decrypted;

This was supposed to echo everything, unfortunately my result was a blank private key, a fine public key, plaintext, and encrypted text, and an error when trying to decrypt: "openssl_private_decrypt(): key parameter is not a valid private key"

Clearly, i'm having a problem with private key creation. I've searched the internet thoroughly and haven't been able to fix it, even though I've implemented simple code that seems to work for everyone else.

Thanks in advance,
Elie Zeitouni

Body:
This worked for wampp/php 7.0.4

$privateKey = openssl_pkey_new(array(
'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
 ));

// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');

// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);

// write public key to file
file_put_contents('public.key', $publicKey['key']);

// clear key
echo $privateKey;


问:
What is wrong with XML Serialization of a lib class with IL2CPP?
After setting the scripting backend from Mono to IL2CPP on a Unity Project, it throws an exception at runtime when it runs an XML deserialization of a lib class (from a dll library).

Google Play will soon no longer accept build which doesn't include 64bit version. That's mean in Unity we have to switch from Mono to IL2CPP. The target device is an Android device.

We tried to build the dll library with various versions of the .Net Framework. We also tried to add some instructions in the default constructor (parameterless). Then we used the constructor before the deserialization call, in case of the stripping at build time. We tried to force the stripping level to be disabled by code, but we don't know if it works.

Here is the class where the problem happens, where deserialization fails.

namespace Api.Common.Licence
{
    [XmlRoot(ElementName = "DeviceLicenceFile")]
    public class DeviceLicenceFile
    {
        public DeviceLicenceFile()
        {
            //Email = null; //tried that for an example but is usually empty
        }

        [XmlElement(ElementName = "Email")]
        public string Email { get; set; }
        [...]
    }
}
```

<p>That's my serialization function</p>

<pre class="lang-cs prettyprint-override"><code>public static T Deserialize<T>(string text)
{
    var serializer = new XmlSerializer(typeof(T));
    T obj = (T) (serializer.Deserialize(new StringReader(text)));
    return obj;
}
</code>```

Everything works with Mono but with IL2CPP, it throws the following error =>
"System.InvalidOperationException: There was an error reflecting type 'Api.Common.Licence.DeviceLicenceFile'. ---> System.InvalidOperationException: Api.Common.Licence.DeviceLicenceFile cannot be serialized because it does not have a default public constructor"
Of course, we have a parameterless constructor.

EDIT: We're on Unity 2018.4

答:
The issue here is probably that IL2CPP is removing the DeviceLicenceFile class during build as it's only used via generics / reflection. (IL2CPP does managed code stripping to reduce binary size / build times.)

You can add the whole assembly (or just that type) to a file called link.xml that has to be placed in the root of your Assets directory, which will tell Unity not to remove that class. See the documentation here for more info: https://docs.unity3d.com/Manual/IL2CPP-BytecodeStripping.html - you'll see an example there for the file contents you need in the section "How to deal with stripping when using reflection".

Body:
After setting the scripting backend from Mono to IL2CPP on a Unity Project, it throws an exception at runtime when it runs an XML deserialization of a lib class (from a dll library).

Google Play will soon no longer accept build which doesn't include 64bit version. That's mean in Unity we have to switch from Mono to IL2CPP. The target device is an Android device.

We tried to build the dll library with various versions of the .Net Framework. We also tried to add some instructions in the default constructor (parameterless). Then we used the constructor before the deserialization call, in case of the stripping at build time. We tried to force the stripping level to be disabled by code, but we don't know if it works.

Here is the class where the problem happens, where deserialization fails.

namespace Api.Common.Licence
{
    [XmlRoot(ElementName = "DeviceLicenceFile")]
    public class DeviceLicenceFile
    {
        public DeviceLicenceFile()
        {
            //Email = null; //tried that for an example but is usually empty
        }

        [XmlElement(ElementName = "Email")]
        public string Email { get; set; }
        [...]
    }
}

That's my serialization function

public static T Deserialize<T>(string text)
{
    var serializer = new XmlSerializer(typeof(T));
    T obj = (T) (serializer.Deserialize(new StringReader(text)));
    return obj;
}

Everything works with Mono but with IL2CPP, it throws the following error =>
"System.InvalidOperationException: There was an error reflecting type 'Api.Common.Licence.DeviceLicenceFile'. ---> System.InvalidOperationException: Api.Common.Licence.DeviceLicenceFile cannot be serialized because it does not have a default public constructor"
Of course, we have a parameterless constructor.

EDIT: We're on Unity 2018.4


问:
Hide option when selected by another Select
I have two select's who uses the same list. When i choose the option "Foo" from select A the same option "Foo" must be hidden on select B. Any ideia how to do it with AngularJS ? I'm trying something like this

```<code><div class="col-md-6">
    <label>
        Testemunha 1 :
    </label>
    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha1"
            ng-options="obj as obj.pessoa.nome for obj in lstTestemunha">
        <option></option>
    </select>
</div>

<div class="col-md-6">
    <label>
        Testemunha 2 :
    </label>
    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha2"
            ng-options="obj as obj.pessoa.nome for obj in lstTestemunha ">
        <option></option>
    </select>
</div>
</code>```

```<code>  $scope.esconderTestemunhaSelecionada = function(obj){
    if($scope.lstTestemunha.includes(obj)){
      $scope.lstTestemunha.style.display = "none";
      return $scope.lstTestemunha;
    }
  }
</code>```

答:
I solved this problem not the way that i'd like but works fine.

```<code><div class="col-md-6">
    <label>
        Testemunha 1 :
    </label>
    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha1"
          ng-options="obj as obj.pessoa.nome for obj in lstTestemunha">
          <option></option>
    </select>
</div>

<div class="col-md-6">
    <label>
        Testemunha 2 :
    </label>
    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha2" ng-disabled="!notificacaoOrientativa.testemunha1"
                        ng-options="obj as obj.pessoa.nome for obj in lstTestemunha | filter: {pessoa:{ id: '!' + notificacaoOrientativa.testemunha1.pessoa.id }}">
        <option></option>
    </select>
</div>
</code>```

I'm forcing the user to set the first select and filter the second according to the first.

By the way, sry my poor english.

Body:
I have two select's who uses the same list. When i choose the option "Foo" from select A the same option "Foo" must be hidden on select B. Any ideia how to do it with AngularJS ? I'm trying something like this

        Testemunha 1 :

    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha1"
            ng-options="obj as obj.pessoa.nome for obj in lstTestemunha">
        <option></option>
    </select>

        Testemunha 2 :

    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha2"
            ng-options="obj as obj.pessoa.nome for obj in lstTestemunha ">
        <option></option>
    </select>

  $scope.esconderTestemunhaSelecionada = function(obj){
    if($scope.lstTestemunha.includes(obj)){
      $scope.lstTestemunha.style.display = "none";
      return $scope.lstTestemunha;
    }
  }

Body:
I solved this problem not the way that i'd like but works fine.

<div class="col-md-6">
    <label>
        Testemunha 1 :
    </label>
    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha1"
          ng-options="obj as obj.pessoa.nome for obj in lstTestemunha">
          <option></option>
    </select>
</div>

<div class="col-md-6">
    <label>
        Testemunha 2 :
    </label>
    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha2" ng-disabled="!notificacaoOrientativa.testemunha1"
                        ng-options="obj as obj.pessoa.nome for obj in lstTestemunha | filter: {pessoa:{ id: '!' + notificacaoOrientativa.testemunha1.pessoa.id }}">
        <option></option>
    </select>
</div>

I'm forcing the user to set the first select and filter the second according to the first.

By the way, sry my poor english.


问:
ASP.NET Core throwing -4077 ECONNRESET if files total size in POST request are over 30MB
I could not figure out why Kestrel keeps closing the connection when I try uploading large files to it, as soon as it gets over 30MB, to be precise.

I am aware Kestrel has a default setting of 30MB in terms of maximum request size, and I have tried increasing the maximum request size to 100MB in the web.config file:

```<code><security>
  <requestFiltering allowDoubleEscaping="true">
    <!-- This will handle requests up to 100MB -->
    <requestLimits maxAllowedContentLength="104857600" />
  </requestFiltering>
</security>
</code>```

I have tried configuring it when bootstrapping the server as well:

```<code>WebHost.UseKestrel(options => options.Limits.MaxRequestBodySize = 104857600) // 100MB
</code>```

[...]

```<code>services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 104857600); // 100MB
</code>```

I have tried setting it in the middleware:

```<code>var maxRequestBodySizeFeature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
maxRequestBodySizeFeature.MaxRequestBodySize = 104857600;
</code>```

I have tried everything I could find, for example what is suggested here:

Increase upload file size in Asp.Net core

And here:

https://www.talkingdotnet.com/how-to-increase-file-upload-size-asp-net-core/

But as soon as my POST request containing several files that together go over the 30MB limit, when the following line executes:

```<code>foreach (var entry in httpContext.Request.Form /* Exception is thrown by Form property */)
{
}
</code>```

I get the following exception:

```<code>[Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.ConnectionResetException] - Error -4077 ECONNRESET connection reset by peer
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.PipeCompletion.ThrowFailed()
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.Pipe.GetResult(ReadResult& result)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.Pipe.Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.IReadableBufferAwaiter.GetResult()
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.ReadableBufferAwaitable.GetResult()
   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.LibuvOutputConsumer.<WriteOutputAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.WebUtilities.BufferedReadStream.<EnsureBufferedAsync>d__37.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.<ReadAsync>d__36.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.<DrainAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.WebUtilities.MultipartReader.<ReadNextSectionAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Http.Features.FormFeature.<InnerReadFormAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()
[...]
</code>```

As far as I know, this is not the browser closing the connection. In the browser, I just select a bunch of files and upload them, and immediately in Visual Studio, the exception is thrown. Everything is done in localhost.

答:
I was successful providing 11 7mb files using the following settings:

Initial setup:

WebHost.CreateDefaultBuilder(args)
    .ConfigureKestrel(options =>
    {
        options.Limits.MaxRequestBodySize = 104857600;
    })
```

<p>In <code>Startup.cs</code> set the <code>MultipartBodyLengthLimit</code>:</p>

<pre class="lang-cs prettyprint-override"><code>services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 104857600);
</code>```

In the RunExtensions.Run:

Microsoft.AspNetCore.Builder.RunExtensions.Run(app, request =>
{
    if (request.Request.Path.Value == "/test")
    {
        foreach (var file in request.Request.Form.Files)
        {
            // No exceptions
        }
    }
    return Task.CompletedTask;
});
```

Body:
I could not figure out why Kestrel keeps closing the connection when I try uploading large files to it, as soon as it gets over 30MB, to be precise.

I am aware Kestrel has a default setting of 30MB in terms of maximum request size, and I have tried increasing the maximum request size to 100MB in the web.config file:

<security>
  <requestFiltering allowDoubleEscaping="true">

    <requestLimits maxAllowedContentLength="104857600" />
  </requestFiltering>
</security>

I have tried configuring it when bootstrapping the server as well:

WebHost.UseKestrel(options => options.Limits.MaxRequestBodySize = 104857600) // 100MB

[...]

services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 104857600); // 100MB

I have tried setting it in the middleware:

var maxRequestBodySizeFeature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
maxRequestBodySizeFeature.MaxRequestBodySize = 104857600;

I have tried everything I could find, for example what is suggested here:

Increase upload file size in Asp.Net core

And here:

https://www.talkingdotnet.com/how-to-increase-file-upload-size-asp-net-core/

But as soon as my POST request containing several files that together go over the 30MB limit, when the following line executes:

foreach (var entry in httpContext.Request.Form /* Exception is thrown by Form property */)
{
}

I get the following exception:

[Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.ConnectionResetException] - Error -4077 ECONNRESET connection reset by peer
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.PipeCompletion.ThrowFailed()
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.Pipe.GetResult(ReadResult& result)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.Pipe.Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.IReadableBufferAwaiter.GetResult()
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.ReadableBufferAwaitable.GetResult()
   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.LibuvOutputConsumer.<WriteOutputAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.WebUtilities.BufferedReadStream.<EnsureBufferedAsync>d__37.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.<ReadAsync>d__36.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.<DrainAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.WebUtilities.MultipartReader.<ReadNextSectionAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Http.Features.FormFeature.<InnerReadFormAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()
[...]

As far as I know, this is not the browser closing the connection. In the browser, I just select a bunch of files and upload them, and immediately in Visual Studio, the exception is thrown. Everything is done in localhost.

Body:
I was successful providing 11 7mb files using the following settings:

Initial setup:

WebHost.CreateDefaultBuilder(args)
    .ConfigureKestrel(options =>
    {
        options.Limits.MaxRequestBodySize = 104857600;
    })

In Startup.cs set the MultipartBodyLengthLimit:

services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 104857600);

In the RunExtensions.Run:

Microsoft.AspNetCore.Builder.RunExtensions.Run(app, request =>
{
    if (request.Request.Path.Value == "/test")
    {
        foreach (var file in request.Request.Form.Files)
        {
            // No exceptions
        }
    }
    return Task.CompletedTask;
});


问:
Platform specific gems for autotest with bundler
In the rails project I'm working on I inserted support for rspec, cucumber and autotest with this Gemfile (partial)

```<code>gem 'rspec-rails'
gem 'cucumber-rails'
gem 'autotest-standalone'
gem 'autotest-rails-pure'
gem 'zentest-without-autotest'
</code>```

however in order to run tests with autotest i need to execute bundle exec autotest otherwise it fails with this message

```<code>$ autotest
loading autotest/cucumber_rails_rspec_rspec2
Error loading Autotest style autotest/cucumber_rails_rspec_rspec2 (no such file to load -- autotest/cucumber_rails_rspec_rspec2). Aborting.
</code>```

Now I'm developing on a Mac and I'd like to enable autotest-growl and autotest-fsevents gem, but if I insert those lines in my ~/.autotest

```<code>require 'autotest/growl'
require 'autotest/fsevent'
</code>```

then I need to insert the corresponding gems in the Gemfile and everything works, but it breaks builds on my CI server (which is on Linux)

How to solve this without maintaining a different Gemfile for local and CI environments?

EDIT:

For the moment I solved with these lines in Gemfile

```<code>if RUBY_PLATFORM.downcase.include?("darwin") # I'm on Mac
  gem 'autotest-fsevent'
  gem 'autotest-growl'
end
</code>```

It works both locally and on the CI server, I don't know if it mess something, for the moment it seems to work flawlessly.

Any cleaner way to do that is still welcome.

EDIT2:

I switched to groups solutions. While the previous monkeypatch works pretty well both in development and for continuous integration, it will gives you an error in production if you use capistrano bundler tasks for deployments or if you use bundle install --deployment option (which is advised in production)

When using the if RUBY_PLATFORM.downcase.include?("darwin") line you'll get this error on deploy.

```<code># bundle install --deployment --without development test
You are trying to install in deployment mode after changing
your Gemfile. Run `bundle install` elsewhere and add the
updated Gemfile.lock to version control.

You have deleted from the Gemfile:
* autotest-fsevent
* autotest-growl
</code>```

So my final solution to this problem is to include platform specific gems in a given group, say osx, and then in production and on CI server exclude it using bundle.

If you use capistrano to deploy put this in your config.rb

```<code>set :bundle_without,  [:development, :test, :osx]
# capistrano bundler task
require "bundler/capistrano"
</code>```

答:
You can handle this by taking advantage of the different Gemfile environments (testing, development, production).

Your local box can be development while the CI server is your "production" environment.

With this in mind you can edit your Gemfile to use the appropriate gems depending on the environment.

Edit: Sorry, I think I scanned your post too quickly. But you can add your ~/.autotest to .gitignore so it wont be included on your CI server.

Body:
In the rails project I'm working on I inserted support for rspec, cucumber and autotest with this Gemfile (partial)

gem 'rspec-rails'
gem 'cucumber-rails'
gem 'autotest-standalone'
gem 'autotest-rails-pure'
gem 'zentest-without-autotest'

however in order to run tests with autotest i need to execute bundle exec autotest otherwise it fails with this message

$ autotest
loading autotest/cucumber_rails_rspec_rspec2
Error loading Autotest style autotest/cucumber_rails_rspec_rspec2 (no such file to load -- autotest/cucumber_rails_rspec_rspec2). Aborting.

Now I'm developing on a Mac and I'd like to enable autotest-growl and autotest-fsevents gem, but if I insert those lines in my ~/.autotest

require 'autotest/growl'
require 'autotest/fsevent'

then I need to insert the corresponding gems in the Gemfile and everything works, but it breaks builds on my CI server (which is on Linux)

How to solve this without maintaining a different Gemfile for local and CI environments?

EDIT:

For the moment I solved with these lines in Gemfile

if RUBY_PLATFORM.downcase.include?("darwin") # I'm on Mac
  gem 'autotest-fsevent'
  gem 'autotest-growl'
end

It works both locally and on the CI server, I don't know if it mess something, for the moment it seems to work flawlessly.

Any cleaner way to do that is still welcome.

EDIT2:

I switched to groups solutions. While the previous monkeypatch works pretty well both in development and for continuous integration, it will gives you an error in production if you use capistrano bundler tasks for deployments or if you use bundle install --deployment option (which is advised in production)

When using the if RUBY_PLATFORM.downcase.include?("darwin") line you'll get this error on deploy.

# bundle install --deployment --without development test
You are trying to install in deployment mode after changing
your Gemfile. Run `bundle install` elsewhere and add the
updated Gemfile.lock to version control.

You have deleted from the Gemfile:
* autotest-fsevent
* autotest-growl

So my final solution to this problem is to include platform specific gems in a given group, say osx, and then in production and on CI server exclude it using bundle.

If you use capistrano to deploy put this in your config.rb

set :bundle_without,  [:development, :test, :osx]
# capistrano bundler task
require "bundler/capistrano"


问:
Can't inflate with C# using DeflateStream
I'm using mono to inflate/deflate bytes. Here is the code:

```<code>public static byte[] Inflate(byte[] data)
    {
        using (MemoryStream inStream = new MemoryStream(data))
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                using (DeflateStream decompressStream = new DeflateStream(inStream, CompressionMode.Decompress))
                {
                    decompressStream.CopyTo(outStream);
                }
                return outStream.ToArray();
            }
        }
    }
</code>```

The input data is : <789c3dca b9110020 0c04b196 bc9c3f7a 73f11030 281652d1 88b04195 1e742987 2f86258f acdec63d 6dcf0184 560cde> 47bytes. The algorithm is DEFLATE.

I've successfully inflate the same data on other platform, but through the code above, it throws the following exception:

```<code>System.IO.IOException: Corrupted data ReadInternal
  at System.IO.Compression.DeflateStreamNative.CheckResult (Int32 result, System.String where) [0x00000] in <filename unknown>:0
  at System.IO.Compression.DeflateStreamNative.ReadZStream (IntPtr buffer, Int32 length) [0x00000] in <filename unknown>:0
  at System.IO.Compression.DeflateStream.ReadInternal (System.Byte[] array, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
  at System.IO.Compression.DeflateStream.Read (System.Byte[] dest, Int32 dest_offset, Int32 count) [0x00000] in <filename unknown>:0
  at System.IO.Stream.CopyTo (System.IO.Stream destination, Int32 bufferSize) [0x00000] in <filename unknown>:0
  at System.IO.Stream.CopyTo (System.IO.Stream destination) [0x00000] in <filename unknown>:0
</code>```

答:
If you read my comment you will see that I encountered this problem 18 hours ago and although the answer to the problem is here in your answer it is not directly apparent. In your answer there is the variable set wantRfc1950Header = true and in your input stream the first two bytes are the RFC 1950 magic bytes 78 9c.  The System.IO.Compression.DeflateStream expects a raw RFC 1951 stream that has these two bytes omitted.  I imagine you should be able to use your initial example if you chop off these first two bytes before feeding it to the inflator.

On the downside it has taken me over 18 hours to find out that I need to remove two bytes of data.  On the upside I am much more familiar with the internals of zlib and Huffman coding.

Body:
I'm using mono to inflate/deflate bytes. Here is the code:

public static byte[] Inflate(byte[] data)
    {
        using (MemoryStream inStream = new MemoryStream(data))
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                using (DeflateStream decompressStream = new DeflateStream(inStream, CompressionMode.Decompress))
                {
                    decompressStream.CopyTo(outStream);
                }
                return outStream.ToArray();
            }
        }
    }

The input data is : <789c3dca b9110020 0c04b196 bc9c3f7a 73f11030 281652d1 88b04195 1e742987 2f86258f acdec63d 6dcf0184 560cde> 47bytes. The algorithm is DEFLATE.

I've successfully inflate the same data on other platform, but through the code above, it throws the following exception:

System.IO.IOException: Corrupted data ReadInternal
  at System.IO.Compression.DeflateStreamNative.CheckResult (Int32 result, System.String where) [0x00000] in <filename unknown>:0
  at System.IO.Compression.DeflateStreamNative.ReadZStream (IntPtr buffer, Int32 length) [0x00000] in <filename unknown>:0
  at System.IO.Compression.DeflateStream.ReadInternal (System.Byte[] array, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
  at System.IO.Compression.DeflateStream.Read (System.Byte[] dest, Int32 dest_offset, Int32 count) [0x00000] in <filename unknown>:0
  at System.IO.Stream.CopyTo (System.IO.Stream destination, Int32 bufferSize) [0x00000] in <filename unknown>:0
  at System.IO.Stream.CopyTo (System.IO.Stream destination) [0x00000] in <filename unknown>:0


答:
np.where

I'm making an assumption that there is a better way to do both 'Yes' and 'No' at the same time.  If you truly just want to fill in the 'No' after you've already got the 'Yes' then refer to Fatemehhh's answer

```<code>df.loc[:, 'A'] = np.where(df.index.isin(dl), 'Yes', 'No')
</code>```

Experimental Section

Not meant for actual suggestions

```<code>f = dl.__contains__
g = ['No', 'Yes'].__getitem__
df.loc[:, 'A'] = [*map(g, map(f, df.index))]

df

     A
0  Yes
1   No
2  Yes
3  Yes
4  Yes
5   No
6   No
7  Yes
8   No
9   No
</code>```

Title: Pandas - Replace values based on index and not in index

Body:
Here is the sample code.

import pandas as pd, numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A'))

I have a list dl=[0,2,3,4,7]

At the index positions specified by list, I would like to have column A as "Yes".

The following code works

df.loc[dl,'A']='Yes'

How do I fill column 'A' with 'No' for column values not in index.
Please forgive me if this is a duplicate post.

Body:
np.where

I'm making an assumption that there is a better way to do both 'Yes' and 'No' at the same time.  If you truly just want to fill in the 'No' after you've already got the 'Yes' then refer to Fatemehhh's answer

df.loc[:, 'A'] = np.where(df.index.isin(dl), 'Yes', 'No')

Experimental Section

Not meant for actual suggestions

f = dl.__contains__
g = ['No', 'Yes'].__getitem__
df.loc[:, 'A'] = [*map(g, map(f, df.index))]

df

     A
0  Yes
1   No
2  Yes
3  Yes
4  Yes
5   No
6   No
7  Yes
8   No
9   No


问:
Why is the assignment in a function ignored?
Consider following code:

```<code>zzz=2

function f()
{
    zzz=4
}

$(f)
echo $zzz
</code>```

Why is the assignment (zzz=4) ignored? I thought I knew what $( ) does - it takes everything written to stdout and pastes it verbatim in the place where it's used. But why would that affect assignments to a global variable?

答:
Remove the subshell around f.

Assuming you really had no use for a subshell, the code should look something like:

```<code>zzz=2

function f()
{
    zzz=4
}

f
echo $zzz
</code>```

You're telling it that function f needs to be executed in a different shell, so it won't change the varaible.

Body:
Consider following code:

zzz=2

function f()
{
    zzz=4
}

$(f)
echo $zzz

Why is the assignment (zzz=4) ignored? I thought I knew what $( ) does - it takes everything written to stdout and pastes it verbatim in the place where it's used. But why would that affect assignments to a global variable?

Body:
Remove the subshell around f.

Assuming you really had no use for a subshell, the code should look something like:

zzz=2

function f()
{
    zzz=4
}

f
echo $zzz

You're telling it that function f needs to be executed in a different shell, so it won't change the varaible.


问:
How to concatenate url with a variable everytime a login is made
The Wordpress site I'm working on:

```<code>http://www.careersroadmap.com/
</code>```

After submission of a registration form, I have to redirect to this URL:

```<code>http://careertest.edumilestones.com/access-login-api.php?
</code>```

However, during the redirect, I have to pass this variable to the URL:

```<code>category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere
</code>```

So the final destination URL will be:

```<code>http://careertest.edumilestones.com/access-login-api.php?category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere
</code>```

The access_code variable will change for each user that logs in.

I tried an AJAX call using the code below:

```<code><script>

var startButton = document.getElementById("startButton");
startButton.addEventListener("click", getApiFunction());

function getApiFunction(){
    var myRequest = new XMLHttpRequest();
    myRequest.open('GET', 'http://careertest.edumilestones.com/access-login-api.php?category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere');
    myRequest.onload= function(){
        var myData = JSON.parse(this.response);
    };
    myRequest.send();
};

</script>
</code>```

After trying the above code, I got the CORS policy error.

How do I accomplish this with Javascript or PHP??

答:
I suppose you could add hidden inputs to the registration form.

Something along those lines:

```<code><form action="http://careertest.edumilestones.com/access-login-api.php" method="GET">
    <input type="hidden" name="category" value="2123">
    <input type="hidden" name="channel_id" value="371">
    <input type="hidden" name="cd" value="89">
    <input type="hidden" name="age" value="371">
    <input type="hidden" name="access_code" value="democodesjam12474">
</form>
</code>```

A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted.

Read more about it here: https://www.w3schools.com/tags/att_input_type_hidden.asp

Body:
The Wordpress site I'm working on:

http://www.careersroadmap.com/

After submission of a registration form, I have to redirect to this URL:

http://careertest.edumilestones.com/access-login-api.php?

However, during the redirect, I have to pass this variable to the URL:

category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere

So the final destination URL will be:

http://careertest.edumilestones.com/access-login-api.php?category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere

The access_code variable will change for each user that logs in.

I tried an AJAX call using the code below:

After trying the above code, I got the CORS policy error.

How do I accomplish this with Javascript or PHP??

Body:
I suppose you could add hidden inputs to the registration form.

Something along those lines:

<form action="http://careertest.edumilestones.com/access-login-api.php" method="GET">
    <input type="hidden" name="category" value="2123">
    <input type="hidden" name="channel_id" value="371">
    <input type="hidden" name="cd" value="89">
    <input type="hidden" name="age" value="371">
    <input type="hidden" name="access_code" value="democodesjam12474">
</form>

A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted.

Read more about it here: https://www.w3schools.com/tags/att_input_type_hidden.asp


问:
How do you tell that your unit tests are correct?
I've only done minor unit testing at various points in my career.  Whenever I start diving into it again, it always troubles me how to prove that my tests are correct.  How can I tell that there isn't a bug in my unit test?  Usually I end up running the app, proving it works, then using the unit test as a sort of regression test.  What is the recommended approach and/or what is the approach you take to this problem?

Edit: I also realize that you could write small, granular unit tests that would be easy to understand. However, if you assume that small, granular code is flawless and bulletproof, you could just write small, granular programs and not need unit testing.

Edit2: For the arguments "unit testing is for making sure your changes don't break anything" and "this will only happen if the test has the exact same flaw as the code", what if the test overfits? It's possible to pass both good and bad code with a bad test.  My main question is what good is unit testing since if your tests can be flawed you can't really improve your confidence in your code, can't really prove your refactoring worked, and can't really prove that you met the specification?

答:
This is one of the advantages of TDD: the code acts as a test for the tests.

It is possible that you'll make equivalent errors, but it is uncommon in my experience.

But I have certainly had the case where I write a test that should fail only to have it pass, which told me my test was wrong.

When I was first learning unit testing, and before I was doing TDD, I would also deliberately break the code after writing the test to ensure that it failed as I expected.  When I didn't I knew the test was broken.

I really like Bob Martin's description of this as being equivalent to double entry bookkeeping.

OwnerDisplayName: Jake

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Abie

OwnerDisplayName: Jeffrey Fredrick


问:
java persistance query language limit resultset
Suppose I have following rows in a table "mytable"
id

1

2

3

...
...

500

and my query is like select m from mytable m where m.id < 300
how can I get following output in the same order?

201

202

...
...
...

299

I am using setMaxResult(100) but it returns me output like this

1

2

...
...

100

any advice?

答: You can use setFirstResult to define the start index. Together with setMaxResult you can get a specific range.


问:
Can´t get data from website using PHP and DOM
I´m trying to get data from this website: https://www.pontoslivelo.com.br/compreepontue/magazineluiza

The data I´m trying to get is this:
enter image description here

Here´s the code I have so far:

```<code>$html = new simple_html_dom();

$html->load_file('https://www.pontoslivelo.com.br/compreepontue/magazineluiza');

foreach ($html->find('div[class=pontos-1]') as $div) {
    echo $div->plaintext . "<br>";
}
</code>```

Nothing is returned.

The $html->find('div[class=pontos-1]') wasn´t suppose to get all the div from the code? Why can´t he find the one with class=pontos-1?

答:
Download and include Simple HTML DOM first in your PHP File.

Here is your required code

```<code>include_once('simple_html_dom.php');

$html = file_get_html('https://www.pontoslivelo.com.br/compreepontue/magazineluiza');

foreach($html->find('div[class=pontos-1]') as $element){
    echo $element->innertext . '<br>';
}
</code>```

Body:
I´m trying to get data from this website: https://www.pontoslivelo.com.br/compreepontue/magazineluiza

The data I´m trying to get is this:
enter image description here

Here´s the code I have so far:

$html = new simple_html_dom();

$html->load_file('https://www.pontoslivelo.com.br/compreepontue/magazineluiza');

foreach ($html->find('div[class=pontos-1]') as $div) {
    echo $div->plaintext . "
";
}

Nothing is returned.

The $html->find('div[class=pontos-1]') wasn´t suppose to get all the div from the code? Why can´t he find the one with class=pontos-1?

Body:
Download and include Simple HTML DOM first in your PHP File.

Here is your required code

include_once('simple_html_dom.php');

$html = file_get_html('https://www.pontoslivelo.com.br/compreepontue/magazineluiza');

foreach($html->find('div[class=pontos-1]') as $element){
    echo $element->innertext . '<br>';
}


问:
Requests.Get not working for API call - Yielding 401 Error and "Not Logged In" - Second Call
I have successfully connected to the target server using requests.post; however, when I try to make any request.get calls I am receiving the following error:

```<code>{"message":"Not logged in","code":401}
</code>```

I have confirmed I am logging in successfully, as when I print(response.text) I am showing info from the server. Based on the error message, it appears that I am not persisting the login.

My script:

```<code>import requests

data = {}
payload = {'j_username': 'my_username', 'j_password': 'my_password'}
response = requests.post('https://sample.com', data=payload)

getBlocks_response = requests.get('https://sample.com/api/v1/resourceBlock')
print(getBlocks_response.text)

getDataDateRange_response = requests.get('https://sample.com/api/v1/factData/getDataDateRange', data=payload)
print(getDataDateRange_response.text)
</code>```

I am expecting an output of data in the form of a JSON, but have only received two errors for both requests.get calls above. I am new to Python as well as API interaction. Any insight would be greatly appreciated. Thanks.

答:
I read the documentation regarding Session(). I was able to get my get requests to run successfully by adjusting my script to:</p>

```<code>import requests

with requests.Session() as session:
data = {}
payload = {'j_username': 'my_username', 'j_password': 'my_password'}
response = session.post('https://sample.com', data=payload)

getBlocks_response = session.get('https://sample.com/api/v1/resourceBlock')
print(getBlocks_response.text)

getDataDateRange_response = session.get('https://sample.com/api/v1/factData/getDataDateRange', data=payload)
print(getDataDateRange_response.text)
</code>```

Body:
I have successfully connected to the target server using requests.post; however, when I try to make any request.get calls I am receiving the following error:

{"message":"Not logged in","code":401}

I have confirmed I am logging in successfully, as when I print(response.text) I am showing info from the server. Based on the error message, it appears that I am not persisting the login.

My script:

import requests

data = {}
payload = {'j_username': 'my_username', 'j_password': 'my_password'}
response = requests.post('https://sample.com', data=payload)

getBlocks_response = requests.get('https://sample.com/api/v1/resourceBlock')
print(getBlocks_response.text)

getDataDateRange_response = requests.get('https://sample.com/api/v1/factData/getDataDateRange', data=payload)
print(getDataDateRange_response.text)

I am expecting an output of data in the form of a JSON, but have only received two errors for both requests.get calls above. I am new to Python as well as API interaction. Any insight would be greatly appreciated. Thanks.

Body:
I read the documentation regarding Session(). I was able to get my get requests to run successfully by adjusting my script to:

import requests

with requests.Session() as session:
data = {}
payload = {'j_username': 'my_username', 'j_password': 'my_password'}
response = session.post('https://sample.com', data=payload)

getBlocks_response = session.get('https://sample.com/api/v1/resourceBlock')
print(getBlocks_response.text)

getDataDateRange_response = session.get('https://sample.com/api/v1/factData/getDataDateRange', data=payload)
print(getDataDateRange_response.text)


问:
Android two way databinding is not working for edittext in Fragment
I am using one model for 2 fragments. First one is displaying countryName and countryCode, Second one is selecting country. When i select country i set a new value models field and going back to first fragment EditText is also setting empty text to models fields, thats why two way data binding is not working. If i change EditText to TextView, all is working fine.

Model:

```<code>public final ObservableField<String> countryName = new ObservableField<>();
public final ObservableField<String> countryCode = new ObservableField<>();

public void onCountrySelected(CountryEnum countryEnum) {
    countryName.set(countryEnum.getName());
    countryCode.set(countryEnum.getCode());
    getNavigator().onGoBack();
}
</code>```

XML:

```<code><EditText
        android:id="@+id/countryNameTextView"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_56dp"
        android:layout_margin="8dp"
        android:drawableEnd="@drawable/ic_arrow_drop_down"
        android:drawableRight="@drawable/ic_arrow_drop_down"
        android:hint="@string/country_code"
        android:textColorHint="@color/black"
        android:singleLine="true"
        android:focusable="false"
        android:gravity="center_vertical"
        android:onClick="@{()->viewModel.onCountryClick()}"
        android:text="@={viewModel.countryName}"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout"/>

    <EditText
        android:id="@+id/codeEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="@dimen/_48dp"
        android:layout_marginTop="16dp"
        android:text="@={viewModel.countryCode}"
        android:singleLine="true"
        android:gravity="center_vertical"
        tools:text="+998"
        app:layout_constraintStart_toStartOf="@+id/countryNameTextView"
        app:layout_constraintTop_toBottomOf="@+id/countryNameTextView"/>
</code>```

Edit:

Country Enum:

```<code>public enum CountryEnum {

Country_1("Afghanistan", "Афганистан", "93", "--- --- ---"),
Country_2("Albania", "Албания", "355", "-- --- ----"),
Country_3("Algeria", "Алжир", "213", "--- -- -- --"),
Country_4("American Samoa", "Американское Самоа", "1684", "--- ----"),
Country_5("Andorra", "Андорра", "376", "-- -- --"),
Country_6("Angola", "Ангола", "244", "--- --- ---"),
Country_7("Anguilla", "Ангуилла", "1264", "--- ----"),
}
</code>```

答:
For fragment, try to set lifecycleOwner

Simple example (Kotlin):

```<code>class FragmentMain : Fragment() {

private lateinit var viewDataBinding: MainFragmentBinding

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    viewDataBinding = DataBindingUtil.inflate(
        inflater,
        R.layout.main_fragment_profile,
        container,
        false
    )
    viewDataBinding.lifecycleOwner = this

    return viewDataBinding.root
}
}
</code>```

Body:
I am using one model for 2 fragments. First one is displaying countryName and countryCode, Second one is selecting country. When i select country i set a new value models field and going back to first fragment EditText is also setting empty text to models fields, thats why two way data binding is not working. If i change EditText to TextView, all is working fine.

Model:

public final ObservableField<String> countryName = new ObservableField<>();
public final ObservableField<String> countryCode = new ObservableField<>();

public void onCountrySelected(CountryEnum countryEnum) {
    countryName.set(countryEnum.getName());
    countryCode.set(countryEnum.getCode());
    getNavigator().onGoBack();
}

XML:

<EditText
        android:id="@+id/countryNameTextView"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_56dp"
        android:layout_margin="8dp"
        android:drawableEnd="@drawable/ic_arrow_drop_down"
        android:drawableRight="@drawable/ic_arrow_drop_down"
        android:hint="@string/country_code"
        android:textColorHint="@color/black"
        android:singleLine="true"
        android:focusable="false"
        android:gravity="center_vertical"
        android:onClick="@{()->viewModel.onCountryClick()}"
        android:text="@={viewModel.countryName}"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout"/>

    <EditText
        android:id="@+id/codeEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="@dimen/_48dp"
        android:layout_marginTop="16dp"
        android:text="@={viewModel.countryCode}"
        android:singleLine="true"
        android:gravity="center_vertical"
        tools:text="+998"
        app:layout_constraintStart_toStartOf="@+id/countryNameTextView"
        app:layout_constraintTop_toBottomOf="@+id/countryNameTextView"/>

Edit:

Country Enum:

public enum CountryEnum {

Country_1("Afghanistan", "Афганистан", "93", "--- --- ---"),
Country_2("Albania", "Албания", "355", "-- --- ----"),
Country_3("Algeria", "Алжир", "213", "--- -- -- --"),
Country_4("American Samoa", "Американское Самоа", "1684", "--- ----"),
Country_5("Andorra", "Андорра", "376", "-- -- --"),
Country_6("Angola", "Ангола", "244", "--- --- ---"),
Country_7("Anguilla", "Ангуилла", "1264", "--- ----"),
}

Body:
For fragment, try to set lifecycleOwner

Simple example (Kotlin):

class FragmentMain : Fragment() {

private lateinit var viewDataBinding: MainFragmentBinding

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    viewDataBinding = DataBindingUtil.inflate(
        inflater,
        R.layout.main_fragment_profile,
        container,
        false
    )
    viewDataBinding.lifecycleOwner = this

    return viewDataBinding.root
}
}