问:
Strange Base64 encode/decode problem
I'm using Grails 1.3.7. I have some code that uses the built-in base64Encode function and base64Decode function. It all works fine in simple test cases where I encode some binary data and then decode the resulting string and write it to a new file. In this case the files are identical.

But then I wrote a web service that took the base64 encoded data as a parameter in a POST call. Although the length of the base64 data is identical to the string I passed into the function, the contents of the base64 data are being modified. I spend DAYS debugging this and finally wrote a test controller that passed the data in base64 to post and also took the name of a local file with the correct base64 encoded data, as in:

```<code>data=AAA-base-64-data...&testFilename=/name/of/file/with/base64data
</code>```

Within the test function I compared every byte in the incoming data parameter with the appropriate byte in the test file. I found that somehow every "+" character in the input data parameter had been replaced with a " " (space, ordinal ascii 32). Huh? What could have done that?

To be sure I was correct, I added a line that said:

```<code>data = data.replaceAll(' ', '+')
</code>```

and sure enough the data decoded exactly right. I tried it with arbitrarily long binary files and it now works every time. But I can't figure out for the life of me what would be modifying the data parameter in the post to convert the ord(43) character to ord(32)? I know that the plus sign is one of the 2 somewhat platform dependent characters in the base64 spec, but given that I am doing the encoding and decoding on the same machine for now I am super puzzled what caused this. Sure I have a "fix" since I can make it work, but I am nervous about "fixes" that I don't understand.

The code is too big to post here, but I get the base64 encoding like so:

```<code>def inputFile = new File(inputFilename)
def rawData =  inputFile.getBytes()
def encoded = rawData.encodeBase64().toString()
</code>```

I then write that encoded string out to new a file so I can use it for testing later. If I load that file back in as so I get the same rawData:

```<code>def encodedFile = new File(encodedFilename)
String encoded = encodedFile.getText()
byte[] rawData = encoded.decodeBase64()
</code>```

So all that is good. Now assume I take the "encoded" variable and add it to a param to a POST function like so:

```<code>String queryString = "data=$encoded"
String url = "http://localhost:8080/some_web_service"

def results = urlPost(url, queryString)

def urlPost(String urlString, String queryString) {
    def url = new URL(urlString)
    def connection = url.openConnection()
    connection.setRequestMethod("POST")
    connection.doOutput = true

    def writer = new OutputStreamWriter(connection.outputStream)
    writer.write(queryString)
    writer.flush()
    writer.close()
    connection.connect()

    return (connection.responseCode == 200) ? connection.content.text : "error                         $connection.responseCode, $connection.responseMessage"
}
</code>```

on the web service side, in the controller I get the parameter like so:

```<code>String data = params?.data
println "incoming data parameter has length of ${data.size()}" //confirm right size

//unless I run the following line, the data does not decode to the same source
data = data.replaceAll(' ', '+')

//as long as I replace spaces with plus, this decodes correctly, why?
byte[] bytedata = data.decodeBase64()
</code>```

Sorry for the long rant, but I'd really love to understand why I had to do the "replace space with plus sign" to get this to decode correctly. Is there some problem with the plus sign being used in a request parameter?

答:
paraquote from the wikipedia link

The encoding used by default is based
  on a very early version of the general
  URI percent-encoding rules, with a
  number of modifications such as
  newline normalization and replacing
  spaces with "+" instead of "%20"

another hidden pitfall everyday web developers like myself know little about

Title: Strange Base64 encode/decode problem

Body:
I'm using Grails 1.3.7. I have some code that uses the built-in base64Encode function and base64Decode function. It all works fine in simple test cases where I encode some binary data and then decode the resulting string and write it to a new file. In this case the files are identical.

But then I wrote a web service that took the base64 encoded data as a parameter in a POST call. Although the length of the base64 data is identical to the string I passed into the function, the contents of the base64 data are being modified. I spend DAYS debugging this and finally wrote a test controller that passed the data in base64 to post and also took the name of a local file with the correct base64 encoded data, as in:

data=AAA-base-64-data...&testFilename=/name/of/file/with/base64data

Within the test function I compared every byte in the incoming data parameter with the appropriate byte in the test file. I found that somehow every "+" character in the input data parameter had been replaced with a " " (space, ordinal ascii 32). Huh? What could have done that?

To be sure I was correct, I added a line that said:

data = data.replaceAll(' ', '+')

and sure enough the data decoded exactly right. I tried it with arbitrarily long binary files and it now works every time. But I can't figure out for the life of me what would be modifying the data parameter in the post to convert the ord(43) character to ord(32)? I know that the plus sign is one of the 2 somewhat platform dependent characters in the base64 spec, but given that I am doing the encoding and decoding on the same machine for now I am super puzzled what caused this. Sure I have a "fix" since I can make it work, but I am nervous about "fixes" that I don't understand.

The code is too big to post here, but I get the base64 encoding like so:

def inputFile = new File(inputFilename)
def rawData =  inputFile.getBytes()
def encoded = rawData.encodeBase64().toString()

I then write that encoded string out to new a file so I can use it for testing later. If I load that file back in as so I get the same rawData:

def encodedFile = new File(encodedFilename)
String encoded = encodedFile.getText()
byte[] rawData = encoded.decodeBase64()

So all that is good. Now assume I take the "encoded" variable and add it to a param to a POST function like so:

String queryString = "data=$encoded"
String url = "http://localhost:8080/some_web_service"

def results = urlPost(url, queryString)

def urlPost(String urlString, String queryString) {
    def url = new URL(urlString)
    def connection = url.openConnection()
    connection.setRequestMethod("POST")
    connection.doOutput = true

    def writer = new OutputStreamWriter(connection.outputStream)
    writer.write(queryString)
    writer.flush()
    writer.close()
    connection.connect()

    return (connection.responseCode == 200) ? connection.content.text : "error                         $connection.responseCode, $connection.responseMessage"
}

on the web service side, in the controller I get the parameter like so:

String data = params?.data
println "incoming data parameter has length of ${data.size()}" //confirm right size

//unless I run the following line, the data does not decode to the same source
data = data.replaceAll(' ', '+')

//as long as I replace spaces with plus, this decodes correctly, why?
byte[] bytedata = data.decodeBase64()

Sorry for the long rant, but I'd really love to understand why I had to do the "replace space with plus sign" to get this to decode correctly. Is there some problem with the plus sign being used in a request parameter?


来源: stackexchange

问:
How to call a function with parameters from plsql in php?
I am trying to call a function with parameters from plsql in php and it's not working, but I don't know how.

My problem is it that I have a variable where i am trying to store the function $sqlGetGenre and i don't know how to call the function with $param parameter for example.

Also, another thing that I can't resolve is the call of a function in another function. I already Search On google, but I couldn’t Find something.

Create stored procedure:

```<code>$sqlGetGenre = "CREATE OR REPLACE FUNCTION getGenre(bookISBN IN VARCHAR2) RETURN VARCHAR2"
."AS"
."v_bookGenre VARCHAR2(100);"
."BEGIN"
."select genre into v_bookGenre from books where bookISBN=isbn;"
."return v_bookGenre;"

."EXCEPTION"
."when no_data_found then"
."return null;"
."END getGenre;";
$getGenre = oci_parse($conn, $sqlGetGenre);
oci_execute($getGenre);
</code>```

Create stored procedure:

```<code>$sqlGetTitle ="CREATE OR REPLACE FUNCTION getTitle(bookISBN IN VARCHAR2) RETURN VARCHAR2"
."AS"
."v_bookTitle VARCHAR2(100);"
."BEGIN"
."select title into v_bookTitle from books where bookISBN=isbn;"

."return v_bookTitle;"

."EXCEPTION"
."when no_data_found then"
."return null;"
."END getTitle;";
$getTitle = oci_parse($conn, $sqlgetTitle);
   oci_execute($getTitle);

</code>```

```<code>   $sqlCreateType1 = "CREATE OR REPLACE TYPE t IS TABLE OF varchar2(200);";
   $createType1 = oci_parse($conn, $sqlCreateType1);
   oci_execute($createType1);

   $sqlCreateType2 = "CREATE OR REPLACE TYPE typeRecom IS VARRAY(200) of VARCHAR2(200);";
   $createType2 = oci_parse($conn,$sqlCreateType2);
   oci_execute($createType2);
</code>```

```<code>       $sqlTopRecommandations = "CREATE OR REPLACE FUNCTION topRecommandations(idUser IN VARCHAR2)"
      ."RETURN typeRecom"
      ."AS"

     ."lastGenres t :=t();"
     ."readedBooks t:=t();"
     ."topTen typeRecom:=typeRecom();"

     ."v_i NUMBER := 1;"
     ."v_j NUMBER := 1;"

    ."verifDateBook NUMBER:=0;"
    ."verifDateLoan NUMBER:=0;"

    ."BEGIN"
    ."select count(*) into verifDateBook from books;"
   ."if(verifDateBook = 0) then"
   ."raise no_data_found;"
   ."end if;"
   ."select count(*) into verifDateLoan from loans;"
   ."if(verifDateLoan = 0) then"
   ."raise no_data_found;"
   ."end if;"

   ."lastGenres.extend();"
  ."for i in (select genre from books join loans on books.isbn=loans.bookId where loanDate>add_months(sysdate,-6) and idUser=loans.regNo order by genre desc) loop"
  ."lastGenres.extend();"
  ."lastGenres(lastGenres.count) := i.genre;"
  ."end loop;"
  ."readedBooks.extend();"
  ."for i in (select bookId from loans group by bookId order by count(bookId) desc) loop"
  ."readedBooks.extend();"
  ."readedBooks(readedBooks.count) := i.bookId;"
  ."end loop;"
  ."--select bookId into readedBooks from loan order by count(bookId) desc;"

  ."for v_i IN 1..readedBooks.count LOOP"
  ."for v_j in 1..lastGenres.count LOOP"

  ."if(lastGenres(v_j)=getGenre(readedBooks(v_i))) then"
  ."topTen.extend();"
  ."topTen(topTen.count) := getTitle(readedBooks(v_i));"
  ."end if;"
  ."EXIT WHEN topTen.count=10;"
  ."END LOOP;"
  ."EXIT WHEN topTen.count=10;"
  ."end LOOP;"
 ."return topTen;"
 ."EXCEPTION"
 ."WHEN no_data_found THEN"
 ."return null;"

."END topRecommandations;";

$topRecommandations = oci_parse($conn, $sqlTopRecommandations);
oci_execute($topRecommandations);
</code>```

execute topRecommandations

```<code>$s = oci_parse($conn, "begin :ret :=topRecommandations(:param1); end;");
oci_bind_by_name($s, ':ret', $r, 200);
oci_bind_by_name($s, ':param1', $_SESSION['RollNo']);
oci_execute($s);
echo "Result is: ".$r;
</code>```

答:
you can call a function e.g. on that way:

```<code>$s = oci_parse($c, "begin :ret :=getGenre(:param1); end;");
oci_bind_by_name($s, ':ret', $r, 200);
oci_bind_by_name($s, ':param1', $value1);
oci_execute($s);
echo "Result is: ".$r;
</code>```

if your stored procedure doesn't have parameter, so you can call it on the same way, just remove the param value

```<code>$s = oci_parse($c, "begin :ret :=recommandation(); end;");
oci_bind_array_by_name($s,":ret",$arr,100,-1,SQLT_CHR);
oci_execute($s);

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to call a function with parameters from plsql in php and it's not working, but I don't know how.

My problem is it that I have a variable where i am trying to store the function $sqlGetGenre and i don't know how to call the function with $param parameter for example.

Also, another thing that I can't resolve is the call of a function in another function. I already Search On google, but I couldn’t Find something.

Create stored procedure:

$sqlGetGenre = "CREATE OR REPLACE FUNCTION getGenre(bookISBN IN VARCHAR2) RETURN VARCHAR2"
."AS"
."v_bookGenre VARCHAR2(100);"
."BEGIN"
."select genre into v_bookGenre from books where bookISBN=isbn;"
."return v_bookGenre;"

."EXCEPTION"
."when no_data_found then"
."return null;"
."END getGenre;";
$getGenre = oci_parse($conn, $sqlGetGenre);
oci_execute($getGenre);

Create stored procedure:

$sqlGetTitle ="CREATE OR REPLACE FUNCTION getTitle(bookISBN IN VARCHAR2) RETURN VARCHAR2"
."AS"
."v_bookTitle VARCHAR2(100);"
."BEGIN"
."select title into v_bookTitle from books where bookISBN=isbn;"

."return v_bookTitle;"

."EXCEPTION"
."when no_data_found then"
."return null;"
."END getTitle;";
$getTitle = oci_parse($conn, $sqlgetTitle);
   oci_execute($getTitle);

   $sqlCreateType1 = "CREATE OR REPLACE TYPE t IS TABLE OF varchar2(200);";
   $createType1 = oci_parse($conn, $sqlCreateType1);
   oci_execute($createType1);

   $sqlCreateType2 = "CREATE OR REPLACE TYPE typeRecom IS VARRAY(200) of VARCHAR2(200);";
   $createType2 = oci_parse($conn,$sqlCreateType2);
   oci_execute($createType2);

       $sqlTopRecommandations = "CREATE OR REPLACE FUNCTION topRecommandations(idUser IN VARCHAR2)"
      ."RETURN typeRecom"
      ."AS"

     ."lastGenres t :=t();"
     ."readedBooks t:=t();"
     ."topTen typeRecom:=typeRecom();"

     ."v_i NUMBER := 1;"
     ."v_j NUMBER := 1;"

    ."verifDateBook NUMBER:=0;"
    ."verifDateLoan NUMBER:=0;"

    ."BEGIN"
    ."select count(*) into verifDateBook from books;"
   ."if(verifDateBook = 0) then"
   ."raise no_data_found;"
   ."end if;"
   ."select count(*) into verifDateLoan from loans;"
   ."if(verifDateLoan = 0) then"
   ."raise no_data_found;"
   ."end if;"

   ."lastGenres.extend();"
  ."for i in (select genre from books join loans on books.isbn=loans.bookId where loanDate>add_months(sysdate,-6) and idUser=loans.regNo order by genre desc) loop"
  ."lastGenres.extend();"
  ."lastGenres(lastGenres.count) := i.genre;"
  ."end loop;"
  ."readedBooks.extend();"
  ."for i in (select bookId from loans group by bookId order by count(bookId) desc) loop"
  ."readedBooks.extend();"
  ."readedBooks(readedBooks.count) := i.bookId;"
  ."end loop;"
  ."--select bookId into readedBooks from loan order by count(bookId) desc;"

  ."for v_i IN 1..readedBooks.count LOOP"
  ."for v_j in 1..lastGenres.count LOOP"

  ."if(lastGenres(v_j)=getGenre(readedBooks(v_i))) then"
  ."topTen.extend();"
  ."topTen(topTen.count) := getTitle(readedBooks(v_i));"
  ."end if;"
  ."EXIT WHEN topTen.count=10;"
  ."END LOOP;"
  ."EXIT WHEN topTen.count=10;"
  ."end LOOP;"
 ."return topTen;"
 ."EXCEPTION"
 ."WHEN no_data_found THEN"
 ."return null;"

."END topRecommandations;";

$topRecommandations = oci_parse($conn, $sqlTopRecommandations);
oci_execute($topRecommandations);

execute topRecommandations

$s = oci_parse($conn, "begin :ret :=topRecommandations(:param1); end;");
oci_bind_by_name($s, ':ret', $r, 200);
oci_bind_by_name($s, ':param1', $_SESSION['RollNo']);
oci_execute($s);
echo "Result is: ".$r;

Body:
you can call a function e.g. on that way:

$s = oci_parse($c, "begin :ret :=getGenre(:param1); end;");
oci_bind_by_name($s, ':ret', $r, 200);
oci_bind_by_name($s, ':param1', $value1);
oci_execute($s);
echo "Result is: ".$r;

if your stored procedure doesn't have parameter, so you can call it on the same way, just remove the param value

$s = oci_parse($c, "begin :ret :=recommandation(); end;");
oci_bind_array_by_name($s,":ret",$arr,100,-1,SQLT_CHR);
oci_execute($s);


问:
How to remove a white line in the cell of my html table?
I am making a 5x5 table which will contain images, though on some of the squares I get a white line on the bottom of the cell. (note that I put a gold background so you could notice the line easier)

image of the problem
https://i.imgur.com/un6gNhd.png

I have tried adding "vertical-align: bottom;" , cellpadding="0" cellspacing="0", but still the same problem.

css:

```<code><style>
table {
  width: 90%;
}
td {
  width: 18%;
  position: relative;
border: 2px solid black;
}
td:after {
  content: '';
  display: block;
  margin-top: 100%;
}
td .content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
background-color: gold;
}
img {
  width: 100%;
display: block;
}
</style>

</code>```

html:

```<code><table align="center">
  <tr>
    <td><div class="content"><img src="https://via.placeholder.com/90"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/90"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/90"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/90"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/90"></div></td>
  </tr>
  <tr>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/90"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
  </tr>
  <tr>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/90"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
  </tr>
<tr>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/90"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
  </tr>
<tr>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
    <td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/90"></div></td>
<td><div class="content"><img src="https://via.placeholder.com/120"></div></td>
  </tr>
</table>
</code>```

I expect to get rid of the lines in the cells.

答:
If you add height: 100%; to your image css the gold area will be covered up.

I also added overflow: hidden; to the .content area to prevent the larger images from overlapping with the new 100% fix.

All changes have been labeled 'Below is new' in the css of the fiddle below.

table {
  width: 90%;
  /* Below is new */
  border-spacing: 2px;
}

td {
  width: 18%;
  position: relative;
  border: 2px solid black;
}

td:after {
  content: '';
  display: block;
  margin-top: 100%;
}

td .content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: gold;
  /* Below is new */
  overflow: hidden;
}

img {
  width: 100%;
  display: block;
  /* Below is new */
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table align="center">
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
  </tr>
</table></code>```

Body:
I am making a 5x5 table which will contain images, though on some of the squares I get a white line on the bottom of the cell. (note that I put a gold background so you could notice the line easier)

image of the problem
https://i.imgur.com/un6gNhd.png

I have tried adding "vertical-align: bottom;" , cellpadding="0" cellspacing="0", but still the same problem.

css:

html:

I expect to get rid of the lines in the cells.

Body:
If you add height: 100%; to your image css the gold area will be covered up.

I also added overflow: hidden; to the .content area to prevent the larger images from overlapping with the new 100% fix.

All changes have been labeled 'Below is new' in the css of the fiddle below.

table {
  width: 90%;
  /* Below is new */
  border-spacing: 2px;
}

td {
  width: 18%;
  position: relative;
  border: 2px solid black;
}

td:after {
  content: '';
  display: block;
  margin-top: 100%;
}

td .content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: gold;
  /* Below is new */
  overflow: hidden;
}

img {
  width: 100%;
  display: block;
  /* Below is new */
  height: 100%;
}

<table align="center">
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/90"></div>
    </td>
    <td>
      <div class="content"><img src="https://via.placeholder.com/120"></div>
    </td>
  </tr>
</table>


问:
Scala implicit parameters are marked as unused by the compiler
In scala when compiling with -Ywarn-unused, implicit parameters are marked as never used even if they are used in implicit scope.

For example

class MyClass(implicit: ec: ExecutionContext) {
  def fun = Future.successful("hi").map(_.length)
}
```

This is problematic when running with -Xfatal-warnings as well.

Is there a way to hint to the compiler that these parameters are in fact used? If not, is there another way to ensure code won't compile with unused parameters and declarations?

答: Use the -Ywarn-macros:after flag too. It basically tells the compiler to make the unused checks after macro expansion, that usually solve the problem of unused implicits.

Body:
In scala when compiling with -Ywarn-unused, implicit parameters are marked as never used even if they are used in implicit scope.

For example

class MyClass(implicit: ec: ExecutionContext) {
  def fun = Future.successful("hi").map(_.length)
}

This is problematic when running with -Xfatal-warnings as well.

Is there a way to hint to the compiler that these parameters are in fact used? If not, is there another way to ensure code won't compile with unused parameters and declarations?


问:
I want to add a new row to UITableView with the click of a Button
when I click the add button it return the error 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update'

```<code>import UIKit

class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = [""]
    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.delegate = self
    }

    @objc @IBAction func addPointButton(_ sender: Any) {
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath:    IndexPath) -> UITableViewCell {
        let cell = addPointableview.dequeueReusableCell(withIdentifier:  "addCell", for: indexPath as IndexPath) as! AddPointCellCell
        cell.addPointTextfiedl.tag = indexPath.row
        cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: UIControl.Event.touchUpInside)
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count-1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
        return cell
    }

}
</code>```

I have checked my table and add button I don't know where the error is coming from

答:
A table view displays the contents of the data source array. If you are using insertRows you have to append an item to the data source before updating the UI.

Never call insert/deleteRows in cellForRowAt. And beginUpdates/endUpdates is pointless for a single insert operation.

```<code>class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = ["0"]

    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.delegate = self
        addPointableview.datasource = self
    }

    @objc @IBAction func addPointButton(_ sender: Any) {
       let insertionIndex = addPointTableArray.count
       let indexPath = IndexPath(row: insertionIndex, section: 0)
       addPointTableArray.append(String(insertionIndex))
       addPointableview.insertRows(at: [indexPath], with: .automatic)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return addPointTableArray.count // never hard-code the return value, return the number of item in the data source
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       let cell = addPointableview.dequeueReusableCell(withIdentifier: "addCell", for: indexPath) as! AddPointCellCell
       cell.addPointTextfiedl.tag = Int(addPointTableArray[indexPath.row])
       // assign values of the data source array to UI elements
       cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton), for: UIControl.Event.touchUpInside)
       return cell
     }
   }
</code>```

Body:
when I click the add button it return the error 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update'

import UIKit

class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = [""]
    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.delegate = self
    }

    @objc @IBAction func addPointButton(_ sender: Any) {
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath:    IndexPath) -> UITableViewCell {
        let cell = addPointableview.dequeueReusableCell(withIdentifier:  "addCell", for: indexPath as IndexPath) as! AddPointCellCell
        cell.addPointTextfiedl.tag = indexPath.row
        cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: UIControl.Event.touchUpInside)
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count-1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
        return cell
    }

}

I have checked my table and add button I don't know where the error is coming from

Body:
A table view displays the contents of the data source array. If you are using insertRows you have to append an item to the data source before updating the UI.

Never call insert/deleteRows in cellForRowAt. And beginUpdates/endUpdates is pointless for a single insert operation.

class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = ["0"]

    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.delegate = self
        addPointableview.datasource = self
    }

    @objc @IBAction func addPointButton(_ sender: Any) {
       let insertionIndex = addPointTableArray.count
       let indexPath = IndexPath(row: insertionIndex, section: 0)
       addPointTableArray.append(String(insertionIndex))
       addPointableview.insertRows(at: [indexPath], with: .automatic)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return addPointTableArray.count // never hard-code the return value, return the number of item in the data source
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       let cell = addPointableview.dequeueReusableCell(withIdentifier: "addCell", for: indexPath) as! AddPointCellCell
       cell.addPointTextfiedl.tag = Int(addPointTableArray[indexPath.row])
       // assign values of the data source array to UI elements
       cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton), for: UIControl.Event.touchUpInside)
       return cell
     }
   }


问:
What is the time complexity of this coin changing combination algorithm?
Hello I have just solved this leetcode question: https://leetcode.com/problems/coin-change-2/

The objective is to find the number of different possible combinations of coins we can use to generate an amount assuming we have an infinite number of coins from each denomination.

I know this problem has a DP solution that runs in O(amount*len(coins)) and I can add memoization to the solution below to achieve that.

However I am struggling to find the time complexity of the naïve approach below:

```<code>def change(amount, coins):
    def helper(amount, coins, id):
        if amount == 0:
            return 1
        res = 0
        for i in range(id, len(coins)):
            if coins[i] <= amount:
                res += helper(amount - coins[i], coins, i)
        return res

    res = helper(amount, coins, 0)
    return res
</code>```

So what I am actually doing is a DFS where I try to use the first coin as much as possible before backtracking and moving to the next coin. So once I start to use the next coin I can't use the first one again --> this allows me to not count permutations in my result.

I know the time complexity of this solution is O(exponential) and I also know it is O(V + E) because it is DFS.

Can someone give the exact form of the time complexity ? What is the exponential term exactly ? Or how can I count the edges and vertices in my graph ?

答:
A few things to note here

Dynamic Programming is a concept or an idea. It's not an algorithm in and of itself. It's a technique used to boost the running time of some algorithms where there is a potential for subproblems to overlap and use pre computed results. There is a possibility that none of the subproblems overlap and this is the worst case complexity that people talk about.

So let's proceed with the assumption that no subproblems overlap and we take a top down approach and you have c1, c2, ... cn as your coin denominations

I think the below would work,

Therefore a top down approach would look like this

Some paths will terminate as leaves that end in 0. (that method yielded a perfect cut up of the init amount k ). Some did not.

For the sake of complexity, let's assume all of them did.

So at any given level you have nlevel_num nodes. And you have to traverse every node of the tree.

The longest path would be where you kept removing the smallest denomination form the init amount k. i.i k/c1

Therefore the true time complexity in your case would be O(1+n1+n2+....nk/c1)

Most such problems have 1 as a valid denomination of the coin (or some other small number) to simplify this expression and make the GP easier to calculate

Body:
Hello I have just solved this leetcode question: https://leetcode.com/problems/coin-change-2/

The objective is to find the number of different possible combinations of coins we can use to generate an amount assuming we have an infinite number of coins from each denomination.

I know this problem has a DP solution that runs in O(amount*len(coins)) and I can add memoization to the solution below to achieve that.

However I am struggling to find the time complexity of the naïve approach below:

def change(amount, coins):
    def helper(amount, coins, id):
        if amount == 0:
            return 1
        res = 0
        for i in range(id, len(coins)):
            if coins[i] <= amount:
                res += helper(amount - coins[i], coins, i)
        return res

    res = helper(amount, coins, 0)
    return res

So what I am actually doing is a DFS where I try to use the first coin as much as possible before backtracking and moving to the next coin. So once I start to use the next coin I can't use the first one again --> this allows me to not count permutations in my result.

I know the time complexity of this solution is O(exponential) and I also know it is O(V + E) because it is DFS.

Can someone give the exact form of the time complexity ? What is the exponential term exactly ? Or how can I count the edges and vertices in my graph ?


问:
I can't handle a z-index with position absolute
Hhere's a codesandbox that running the code, you'll figure out that more button (3 dots) is displayed over the more-menu. Click on the 3 dots to see what i mean.

Here's the css code of more-menu:

.more-menu {
  position: absolute;
  top: 100%;
  z-index: 900;
  float: left;
  width: fit-content;
  margin-top: 29px;
  margin-left: calc(50% - 45px);
  background-color: #fff;
  border: 1px solid #ccd8e0;
  border-radius: 4px;
  box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.25);
  opacity: 0;
  -webkit-transform: translate(0, 15px) scale(0.95);
  transform: translate(0, 15px) scale(0.95);
  transition: transform 0.1s ease-out, opacity 0.1s ease-out;
  pointer-events: none;
}

.more-dot {
  background-color: #d7262c;
  margin: 0 auto;
  display: inline-block;
  width: 7px;
  height: 7px;
  margin-right: 3px;
  border-radius: 50%;
  transition: background-color 0.3s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="show-more-menu">
  <button id="more-btn">
    <span class="more-dot" />
    <span class="more-dot" />
    <span class="more-dot" />
  </button>
  <div class="more-menu" aria-hidden="true">
    <div class="more-menu-caret">
      <div class="more-menu-caret-outer" />
      <div class="more-menu-caret-inner" />
    </div>
  </div>
</div></code>```

答:
Using the transform property on your container elements is giving them their own stacking context which is inherited by the more containers. And since your buttons and menus are sibling elements, the z-index property has no bearing on their positions relative to one another.  A simple fix would be to just remove the transform from your .container elements and find another way to position them the way you want.  I would give a suggestion but I'm not quite sure of the effect you're going for.

I made a fork where I just removed the transform and top: 100% from the menu, it's centered but stacks as you wanted.

Body:
Hhere's a codesandbox that running the code, you'll figure out that more button (3 dots) is displayed over the more-menu. Click on the 3 dots to see what i mean.

Here's the css code of more-menu:

.more-menu {
  position: absolute;
  top: 100%;
  z-index: 900;
  float: left;
  width: fit-content;
  margin-top: 29px;
  margin-left: calc(50% - 45px);
  background-color: #fff;
  border: 1px solid #ccd8e0;
  border-radius: 4px;
  box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.25);
  opacity: 0;
  -webkit-transform: translate(0, 15px) scale(0.95);
  transform: translate(0, 15px) scale(0.95);
  transition: transform 0.1s ease-out, opacity 0.1s ease-out;
  pointer-events: none;
}

.more-dot {
  background-color: #d7262c;
  margin: 0 auto;
  display: inline-block;
  width: 7px;
  height: 7px;
  margin-right: 3px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

  <button id="more-btn">

  </button>


问:
summernote note-popover appearing in top left on clicking button to add editor
I have a problem with summernote.

I've got adding note-popover appearing in top left on clicking button to add editor.
here is a screenshot

Anyone else have that problem?

here is a screenshot of the DOM tree

I have last version of the summernote from their website [0.8.9]

```<code> $(discription_list).summernote({
        // width: editorWidth,
        toolbar: [
          ['font-style', ['bold', 'italic', 'underline', 'strikethrough', 'clear']],
          ['para', ['ul', 'ol']],
          ['misc', ['undo', 'redo']],
          ['savebutton', ['save']],
          ['cancelbutton', ['cancel']],
        ],
        buttons: {
          save: SaveButton,
          cancel: CancelButton
        }
      });
</code>```

答:
There seems to be a conflict between summernote and bootstrap 4 that causes that error to display, after unzipping summernote file use summernote-bs4.css and summernote-bs4.js to display. This will show no popover on the top left

```<code>    <link href="summernote/summernote-bs4.css" rel="stylesheet" type="text/css">
   <script src="summernote/summernote-bs4.js"></script>
</code>```

View Issue on Gitlab

Body:
I have a problem with summernote.

I've got adding note-popover appearing in top left on clicking button to add editor.
here is a screenshot

Anyone else have that problem?

here is a screenshot of the DOM tree

I have last version of the summernote from their website [0.8.9]

 $(discription_list).summernote({
        // width: editorWidth,
        toolbar: [
          ['font-style', ['bold', 'italic', 'underline', 'strikethrough', 'clear']],
          ['para', ['ul', 'ol']],
          ['misc', ['undo', 'redo']],
          ['savebutton', ['save']],
          ['cancelbutton', ['cancel']],
        ],
        buttons: {
          save: SaveButton,
          cancel: CancelButton
        }
      });

Body:
There seems to be a conflict between summernote and bootstrap 4 that causes that error to display, after unzipping summernote file use summernote-bs4.css and summernote-bs4.js to display. This will show no popover on the top left

    <link href="summernote/summernote-bs4.css" rel="stylesheet" type="text/css">
   <script src="summernote/summernote-bs4.js"></script>

View Issue on Gitlab


问:
Android - Shared element transitions with calling activity finish()
I'm working on making an application more Material and I'm just stuck on how to implement some shared element transitions. I have an activity A that starts another B and then calls finish() in order to remove it from the back stack. In my case I have an element I want to share between the two activities, but once it is passed from A to B, A no longer matters.
If I don't call finish() after startActivity(ctx,intent, bundle) the exit/enter animation works perfectly. However, if I do call finish, there's a really ugly flicker before the animation starts.

Is there something I'm overlooking or is it just not possible to do what I am trying to do?

答:
If you use ActivityOptions.makeSceneTransitionAnimation(Activity, android.view.View, String) to make your transition you should use its callback method in Activity B to finish Activity A.

```<code>    setEnterSharedElementCallback(new SharedElementCallback() {
        @Override
        public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots) {
            super.onSharedElementEnd(sharedElementNames, sharedElements, sharedElementSnapshots);
                // finish Activity A

        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you use ActivityOptions.makeSceneTransitionAnimation(Activity, android.view.View, String) to make your transition you should use its callback method in Activity B to finish Activity A.

    setEnterSharedElementCallback(new SharedElementCallback() {
        @Override
        public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots) {
            super.onSharedElementEnd(sharedElementNames, sharedElements, sharedElementSnapshots);
                // finish Activity A

        }
    });


问:
Limit users to create only one profile with Devise in Rails
I have a user model and profile model using devise.

user has_one profile
profile belongs_to user

How can I throw an error if a user that already has a profile associate to them when they try to create another profile.

so if a user goes to example.com/profiles/new it would throw the error

答:
The best practice is to change your model! This will prevent problems in your db ... add to your model/profile.rb.

```<code>class Profile < ApplicationRecord
    belongs_to :user
    validates_uniqueness_of :user_id

    #[... other codes...]
end
</code>```

Body:
The best practice is to change your model! This will prevent problems in your db ... add to your model/profile.rb.

class Profile < ApplicationRecord
    belongs_to :user
    validates_uniqueness_of :user_id

    #[... other codes...]
end


问:
How to avoid calling malloc for each node in a linked list
This question was inspired by

Prevent malloc function wrapping

I have written a program that allocates memory for individual nodes in a linked list by calling malloc.

There are speed tests in which malloc is wrapped by a function that causes malloc calls to take more time than normal. This allows the tests to detect frequent usage of malloc.

How do I avoid calling malloc for each node?

答:
The simplest thing you can do is continue to call malloc for the individual nodes of the linked list, but when nodes are freed, put them on a list of free nodes.

```<code>node *free_list = 0;

node *node_alloc(void)
{
   /* get a node fast from the free list, if available */
   if (free_list != 0) {
      node *ret = free_list;
      free_list = free_list->next;
      return ret;
   } else {
      node *ret = malloc(sizeof *ret);
      /* check for non-null, initialize */
      return ret;
   }
}

void node_free(node *node)
{
   node->next = free_list;
   free_list = node;
}
</code>```

If your program has some objects that are only on one list at any given time, you can put the list nodes right inside those objects, so that they don't require separate allocation:

```<code>struct process {
   node queue_node; /* list links for putting process into queues */
   ...
};
</code>```

Body:
The simplest thing you can do is continue to call malloc for the individual nodes of the linked list, but when nodes are freed, put them on a list of free nodes.

node *free_list = 0;

node *node_alloc(void)
{
   /* get a node fast from the free list, if available */
   if (free_list != 0) {
      node *ret = free_list;
      free_list = free_list->next;
      return ret;
   } else {
      node *ret = malloc(sizeof *ret);
      /* check for non-null, initialize */
      return ret;
   }
}

void node_free(node *node)
{
   node->next = free_list;
   free_list = node;
}

If your program has some objects that are only on one list at any given time, you can put the list nodes right inside those objects, so that they don't require separate allocation:

struct process {
   node queue_node; /* list links for putting process into queues */
   ...
};


问:
Capturing folder path from Windows Explorer
I would like to add to a Delphi application a way for the user to call Windows Explorer (possibly using something like ShellExecute, perhaps).

However, and this is where I need some help, please, the application would need to capture ^H^H^H^H^H^H read the folder path that the user navigates to while within Windows Explorer.

Is it possible to obtain this information from Windows Explorer?

[edit: If not possible, or unrealistic, my fallback plan is to provide a separate "Browse for folder" button, to allow the user to select the folder first, then they can launch the Window explorer afterwards].

Thanks for any advice.
PhilW.

答: I dont know your exact needs, but most likely, this is not the way to go. For details, Microsoft developer Raymond Chen has written a blog post about this. What you should do, I think, is to embed an explorer browser control in a custom form in your own application.</p>


问:
"Combine" 2 variables to declare a new one?
I am new to coding and I am trying to declare a variable that refers to 2 "combined" previously declared variables as followed :

```<code>var player1 = "Red", player2 = "Blue", player3 = "Green";
var p=1;
var Red = {x: 2, y: 4};
var Blue = {x: 6, y: 2};
var Green = {x: 8, y: 1};

var x = player+p.x; // should be player+1 so "Red" so x=2
var y = player+p.y; // should be y=4

console.log(x);
console.log(y);
</code>```

x and y should be the coordinates of player n°p depending on the color of that player (in this example player n°1).

I hope it's clear enough ! Thanks for your help !

答:
You can use an array for what I think you want:

```<code>var players = ["Red", "Blue", "Green"];
var p = 1;
console.log(players[p]);
</code>```

If you need more info for each player, then this can be an array of objects:

```<code>var players = [{color: 'Red', x: 2, y: 3}, // etc]
</code>```

Body:
I am new to coding and I am trying to declare a variable that refers to 2 "combined" previously declared variables as followed :

var player1 = "Red", player2 = "Blue", player3 = "Green";
var p=1;
var Red = {x: 2, y: 4};
var Blue = {x: 6, y: 2};
var Green = {x: 8, y: 1};

var x = player+p.x; // should be player+1 so "Red" so x=2
var y = player+p.y; // should be y=4

console.log(x);
console.log(y);

x and y should be the coordinates of player n°p depending on the color of that player (in this example player n°1).

I hope it's clear enough ! Thanks for your help !

Body:
You can use an array for what I think you want:

var players = ["Red", "Blue", "Green"];
var p = 1;
console.log(players[p]);

If you need more info for each player, then this can be an array of objects:

var players = [{color: 'Red', x: 2, y: 3}, // etc]


问:
Ruby on Rails [heroku] git push heroku master error
I am trying to upload my web app on heroku, but the following error occurs.

(I'm coding with cloud 9 IDE)

```<code>$ git push heroku master
.....
remote: -----> Installing node-v10.14.1-linux-x64
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        Yarn executable was not detected in the system.
remote:        Download Yarn at https://yarnpkg.com/en/docs/install
remote:        I, [2019-05-22T02:13:47.373334 #1766]  INFO -- : Writing
/tmp/build_fcc84922ee6a02bfc05a163c871d0548/public/assets/noimage-
3aa3997354b4e9c37f379deb61626f55ade493078d1b42dcefe4a3ccbed34106.jpg
remote:        rake aborted!
remote:        ExecJS::RuntimeError: SyntaxError: Unexpected character '`'
remote:        JS_Parse_Error.get ((execjs):3538:621)
remote:        (execjs):4060:48
remote:        (execjs):1:102
.....
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
</code>```

First of all, It says that "there Yarn executable was not detected in the system", but it is properly downloaded if I check it with yarn -v.

Also, ExecJS :: RuntimeError: SyntaxError: Unexpected character '`' error seems to be that es6 is not recognized, as a solution

config.assets.js_compressor =: uglifier

config.assets.js_compressor = Uglifier.new (harmony: true)

Changed to This seems to be able to read es6. But the above error still persists.

Also, if I run 'rake assets: precompile RAILS_ENV = production' on the console, it runs normally without error.

Thanks.

答:
Try this, Go to heroku dashboard on their website, select your app, click on the gear icon (the settings), scroll down until you see “build packs” add ruby and nodejs buildpacks, and make sure the order is that that nodejs comes first in the list, and then ruby (from top to bottom).

If that doesn’t work, can you clarify how you are triggering the compilation of your JS?

Explanation: I’ve seen this error before(with npm, not yarn), essentially you want herokus nodejs buildpack to take care of JS compiling, the one rails has built in seems to not be compatible with their system.

Body:
I am trying to upload my web app on heroku, but the following error occurs.

(I'm coding with cloud 9 IDE)

$ git push heroku master
.....
remote: -----> Installing node-v10.14.1-linux-x64
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        Yarn executable was not detected in the system.
remote:        Download Yarn at https://yarnpkg.com/en/docs/install
remote:        I, [2019-05-22T02:13:47.373334 #1766]  INFO -- : Writing
/tmp/build_fcc84922ee6a02bfc05a163c871d0548/public/assets/noimage-
3aa3997354b4e9c37f379deb61626f55ade493078d1b42dcefe4a3ccbed34106.jpg
remote:        rake aborted!
remote:        ExecJS::RuntimeError: SyntaxError: Unexpected character '`'
remote:        JS_Parse_Error.get ((execjs):3538:621)
remote:        (execjs):4060:48
remote:        (execjs):1:102
.....
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.

First of all, It says that "there Yarn executable was not detected in the system", but it is properly downloaded if I check it with yarn -v.

Also, ExecJS :: RuntimeError: SyntaxError: Unexpected character '`' error seems to be that es6 is not recognized, as a solution

config.assets.js_compressor =: uglifier

config.assets.js_compressor = Uglifier.new (harmony: true)

Changed to This seems to be able to read es6. But the above error still persists.

Also, if I run 'rake assets: precompile RAILS_ENV = production' on the console, it runs normally without error.

Thanks.


问:
alternatives to jpeg_read_header libjpeg
So I'm running into an issue using libjpeg on Windows which causes jpeg_read_header() to crash.

The problem is (fairly hilariously) described here: http://sourceforge.net/projects/gnuwin32/forums/forum/74807/topic/1629371?message=4053776

I've decided on the 3rd option, which is not using jpeg_stdio_src/dest APIs.  However, after much googling, I can't seem to find the 'other ways to feed data into libjpeg' mentioned at the end of the post, can anyone point me to the right place?

答:
I had a similar issue and came across this post when looking for solutions. Ultimately, I just messed around with the code because it was crucial for me to read directly from file. To fix, I did the following:

```<code>// Declare needed structs
struct jpeg_decompress_struct dinfo;
struct jpeg_error_mgr jerr;

// Open file
FILE * infile = fopen("myimage.jpg", "rw");

// Create error manager instance
dinfo.err = jpeg_std_error(&jerr);

// Decompression process
jpeg_create_decompress(&dinfo);
jpeg_stdio_src(&dinfo, infile);
jpeg_read_header(&dinfo, TRUE);

// ... remainder of program
</code>```

The two functions work fine and as expected after doing this... I'm not sure why this fixed my issue, but I'll take it. Hope this helps someone else.

ContentLicense: CC BY-SA 2.5

Body:
I had a similar issue and came across this post when looking for solutions. Ultimately, I just messed around with the code because it was crucial for me to read directly from file. To fix, I did the following:

// Declare needed structs
struct jpeg_decompress_struct dinfo;
struct jpeg_error_mgr jerr;

// Open file
FILE * infile = fopen("myimage.jpg", "rw");

// Create error manager instance
dinfo.err = jpeg_std_error(&jerr);

// Decompression process
jpeg_create_decompress(&dinfo);
jpeg_stdio_src(&dinfo, infile);
jpeg_read_header(&dinfo, TRUE);

// ... remainder of program

The two functions work fine and as expected after doing this... I'm not sure why this fixed my issue, but I'll take it. Hope this helps someone else.


问:
JSON to CSV Conversion in Python
There're lots of questions regarding JSON to CSV Conversion in Python , but unfortunately couldn't solve my problem.

I've this simple simple JSON Data which is in a file and looks like this after loading.

Raw data in single line [I've structured this to understand better]:

```<code>{
    "t_id":"80740185.1558980000000.120184.121164",
    "s_id":"80740185",
    "pt_slot":"null:null",
    "ch_id":1,"o_id":121164,"c_id":120184,
    "msg_type":1,
    "amd":"{
                \"msg\":\" some Bengali text\",
                \"mask\":\"1GB_OFFER\",
                \"ec\":\"1\",
                \"time-out\":\"0\",
                \"validity\":\"30052019 000000\"
           }",
    "time":1558960217731,
    "dlr":"1",
    "msisdn":"xxxxx",
    "entity":1
}
</code>```

**After loading to JSON formated data looks like below **

```<code>{
    u't_id': u'80740185.1558980000000.120184.121164',
    u'c_id': 120184,
    u'msg_type': 1,
    u'dlr': u'1',
    u'msisdn': u'xxxxxxxx',
    u'amd': u'{
                "msg":" \u0986\u099c \u09b0\u09be\u09a4 \u09e7\u09e8\u099f\u09be\u09b0 \u09ae\u09a7\u09cd\u09af\u09c7 *21291*609# \u09a1\u09be\u09df\u09be\u09b2\u09c7 \u0995\u09bf\u09a8\u09c1\u09a8 \u09e7\u099c\u09bf\u09ac\u09bf \u09ef\u099f\u09be\u0995\u09be\u09a4\u09c7 (\u09e9\u09a6\u09bf\u09a8)",
                "mask":"1GB_OFFER",
                "ec":"1",
                "time-out":"0",
                "validity":"30052019 000000"
               }',
    u'entity': 1,
    u's_id': u'80740185',
    u'ch_id': 1,
    u'time': 1558960217731,
    u'pt_slot': u'null:null',
    u'o_id': 121164
}
</code>```

I've above very simple JSON Data which I'm trying to convert to CSV data. But getting below error.

Here is my code

```<code>#!/usr/bin/python

import json
import csv

def write_sms_dat_to_csv_file():
    f = csv.writer(open('csv_data.txt','wb+'),delimiter = '|')
    with open('test.dat') as fh:
            data = json.load(fh)

    for dt in data:
            f.writerow([dt['c_id'],dt['msisdn'],dt["amd"]["mask"]])

if __name__=="__main__":
    write_sms_dat_to_csv_file()
</code>```

Error Message

```<code>Traceback (most recent call last):
File "./sms_data_read.py", line 16, in <module>
write_sms_dat_to_csv_file()
File "./sms_data_read.py", line 13, in write_sms_dat_to_csv_file
f.writerow([dt['c_id'],dt['msisdn'],dt['amd']['mask']])
TypeError: string indices must be integers
</code>```

Removing for loops with below statement gives same error:

```<code>f.writerow([data['c_id'],data['msisdn'],data['amd']["mask"]])
</code>```

答:
The problem is with the loop. json.load returns a dictionary, and iterating over a dictionary with a for...in loop iterates over the keys. You are treating dt as a dictionary in the body of the loop, but it is actually a string—a key in the dictionary data. It also looks like something about the raw JSON data is causing json.load to not parse the value mapped to by amd as a JSON object, so data["amd"] is a string rather than a dictionary. You can get around this by parsing this string separately. Putting both of these things together, you should be able to replace the loop with

```<code>amd = json.load(data["amd"])
f.writerow([data['c_id'],data['msisdn'],amd["mask"]])
</code>```

to get the result you're looking for.

Title: JSON to CSV Conversion in Python

Body:
There're lots of questions regarding JSON to CSV Conversion in Python , but unfortunately couldn't solve my problem.

I've this simple simple JSON Data which is in a file and looks like this after loading.

Raw data in single line [I've structured this to understand better]:

{
    "t_id":"80740185.1558980000000.120184.121164",
    "s_id":"80740185",
    "pt_slot":"null:null",
    "ch_id":1,"o_id":121164,"c_id":120184,
    "msg_type":1,
    "amd":"{
                \"msg\":\" some Bengali text\",
                \"mask\":\"1GB_OFFER\",
                \"ec\":\"1\",
                \"time-out\":\"0\",
                \"validity\":\"30052019 000000\"
           }",
    "time":1558960217731,
    "dlr":"1",
    "msisdn":"xxxxx",
    "entity":1
}

**After loading to JSON formated data looks like below **

{
    u't_id': u'80740185.1558980000000.120184.121164',
    u'c_id': 120184,
    u'msg_type': 1,
    u'dlr': u'1',
    u'msisdn': u'xxxxxxxx',
    u'amd': u'{
                "msg":" \u0986\u099c \u09b0\u09be\u09a4 \u09e7\u09e8\u099f\u09be\u09b0 \u09ae\u09a7\u09cd\u09af\u09c7 *21291*609# \u09a1\u09be\u09df\u09be\u09b2\u09c7 \u0995\u09bf\u09a8\u09c1\u09a8 \u09e7\u099c\u09bf\u09ac\u09bf \u09ef\u099f\u09be\u0995\u09be\u09a4\u09c7 (\u09e9\u09a6\u09bf\u09a8)",
                "mask":"1GB_OFFER",
                "ec":"1",
                "time-out":"0",
                "validity":"30052019 000000"
               }',
    u'entity': 1,
    u's_id': u'80740185',
    u'ch_id': 1,
    u'time': 1558960217731,
    u'pt_slot': u'null:null',
    u'o_id': 121164
}

I've above very simple JSON Data which I'm trying to convert to CSV data. But getting below error.

Here is my code

#!/usr/bin/python

import json
import csv

def write_sms_dat_to_csv_file():
    f = csv.writer(open('csv_data.txt','wb+'),delimiter = '|')
    with open('test.dat') as fh:
            data = json.load(fh)

    for dt in data:
            f.writerow([dt['c_id'],dt['msisdn'],dt["amd"]["mask"]])

if __name__=="__main__":
    write_sms_dat_to_csv_file()

Error Message

Traceback (most recent call last):
File "./sms_data_read.py", line 16, in <module>
write_sms_dat_to_csv_file()
File "./sms_data_read.py", line 13, in write_sms_dat_to_csv_file
f.writerow([dt['c_id'],dt['msisdn'],dt['amd']['mask']])
TypeError: string indices must be integers

Removing for loops with below statement gives same error:

f.writerow([data['c_id'],data['msisdn'],data['amd']["mask"]])

Body:
The problem is with the loop. json.load returns a dictionary, and iterating over a dictionary with a for...in loop iterates over the keys. You are treating dt as a dictionary in the body of the loop, but it is actually a string—a key in the dictionary data. It also looks like something about the raw JSON data is causing json.load to not parse the value mapped to by amd as a JSON object, so data["amd"] is a string rather than a dictionary. You can get around this by parsing this string separately. Putting both of these things together, you should be able to replace the loop with

amd = json.load(data["amd"])
f.writerow([data['c_id'],data['msisdn'],amd["mask"]])

to get the result you're looking for.


问:
Is there a VBA function that allows me to set the number of hours in a day to less than 24 hrs?
I am trying to create a VBA loop that will run through a set of orders. For each order I have a duration in hours. For each record, it will add the duration to the start date time and create the end date time. The end date time will be the start date time for the next record etc.

I have this working using the dateadd function but that assumes that the production happens 24 hrs a day.

How can I specify that we only work 12 hours a day for example, so any work that goes past say, 7 pm in the evening will spill into the next day?

I tried using dateadd in a loop and it works but I cannot specify 12 hours in a day

```<code>Set rs = db.OpenRecordset("Select * from Combined_Prod_PO_2_T ORDER BY SEQ")

'Define Changeover master as RefChangeover recordset
Dim EffStart_DateTime As Date
Dim EffEnd_DateTime As Date
Dim FamFrom As String
Dim FamTo As String
Dim changeover As Double
Dim RefChangeover As Recordset

'rs.OpenRecordset
rs.MoveFirst
Do Until rs.EOF
    EffEnd_DateTime = rs.Fields("EFFEND_DATETIME")
    FamFrom = rs.Fields("PRODUCT_FAMILY")
    Debug.Print FamFrom

    rs.MoveNext
    If Not rs.EOF Then        ' making sure that the "next" line exists i.e. stop at the second last line
        FamTo = rs.Fields("PRODUCT_FAMILY")
        Debug.Print FamTo
        Duration = rs.Fields("DURATION")

        Dim sqlcmd As String
        sqlcmd = "select sum(hrs) from (SELECT hrs from AP_Changeover_Master where [FROM] = '" & FamFrom & "'" & " and [TO] = '" & FamTo & "'" & " union select distinct 0 from AP_Changeover_Master) "

        Debug.Print sqlcmd
        Set RefChangeover = db.OpenRecordset(sqlcmd)
        changeover = RefChangeover.Fields(0).Value
        Debug.Print changeover

        'If Not rs.EOF Then

        rs.Edit
        rs("Effstart_datetime") = EffEnd_DateTime
        rs("EffEnd_DateTime") = DateAdd("n", (Duration + changeover) * 60, EffEnd_DateTime)
        rs("changeover") = changeover
        rs.Update
    End If
Loop
rs.Close
Set rs = Nothing
</code>```

答:
When your DateTime value goes over 12 hours you could divide that value by 2.

Start Time = 05/01/2019 8:00AM
End Time = 05/02/2019 8:00 AM

The Total time taken here is 24 hours. But since you only work 12 hour days, dividing by 2 will give you, 12 hours.

If you worked 8 hour days, you could divide by 3 to return only 8 hours and so forth.

Keep in mind your value with this solution will be in a decimal format, not a Time format

```<code>Dim ActualTimeTaken as Decimal

rs.Edit

If rs.("YourTimeTaken").value > 12 Then

    ActualTimeTaken = rs.("YourTimeTaken").Value / 2
    'Do whatever you need here.

End If

rs.Update
</code>```

Body:
I am trying to create a VBA loop that will run through a set of orders. For each order I have a duration in hours. For each record, it will add the duration to the start date time and create the end date time. The end date time will be the start date time for the next record etc.

I have this working using the dateadd function but that assumes that the production happens 24 hrs a day.

How can I specify that we only work 12 hours a day for example, so any work that goes past say, 7 pm in the evening will spill into the next day?

I tried using dateadd in a loop and it works but I cannot specify 12 hours in a day

Set rs = db.OpenRecordset("Select * from Combined_Prod_PO_2_T ORDER BY SEQ")

'Define Changeover master as RefChangeover recordset
Dim EffStart_DateTime As Date
Dim EffEnd_DateTime As Date
Dim FamFrom As String
Dim FamTo As String
Dim changeover As Double
Dim RefChangeover As Recordset

'rs.OpenRecordset
rs.MoveFirst
Do Until rs.EOF
    EffEnd_DateTime = rs.Fields("EFFEND_DATETIME")
    FamFrom = rs.Fields("PRODUCT_FAMILY")
    Debug.Print FamFrom

    rs.MoveNext
    If Not rs.EOF Then        ' making sure that the "next" line exists i.e. stop at the second last line
        FamTo = rs.Fields("PRODUCT_FAMILY")
        Debug.Print FamTo
        Duration = rs.Fields("DURATION")

        Dim sqlcmd As String
        sqlcmd = "select sum(hrs) from (SELECT hrs from AP_Changeover_Master where [FROM] = '" & FamFrom & "'" & " and [TO] = '" & FamTo & "'" & " union select distinct 0 from AP_Changeover_Master) "

        Debug.Print sqlcmd
        Set RefChangeover = db.OpenRecordset(sqlcmd)
        changeover = RefChangeover.Fields(0).Value
        Debug.Print changeover

        'If Not rs.EOF Then

        rs.Edit
        rs("Effstart_datetime") = EffEnd_DateTime
        rs("EffEnd_DateTime") = DateAdd("n", (Duration + changeover) * 60, EffEnd_DateTime)
        rs("changeover") = changeover
        rs.Update
    End If
Loop
rs.Close
Set rs = Nothing

Body:
When your DateTime value goes over 12 hours you could divide that value by 2.

Start Time = 05/01/2019 8:00AM
End Time = 05/02/2019 8:00 AM

The Total time taken here is 24 hours. But since you only work 12 hour days, dividing by 2 will give you, 12 hours.

If you worked 8 hour days, you could divide by 3 to return only 8 hours and so forth.

Keep in mind your value with this solution will be in a decimal format, not a Time format

Dim ActualTimeTaken as Decimal

rs.Edit

If rs.("YourTimeTaken").value > 12 Then

    ActualTimeTaken = rs.("YourTimeTaken").Value / 2
    'Do whatever you need here.

End If

rs.Update


问:
How to import excel relationship matrix to Neo4j?
I want to import an excel file which is actually a relationship matrix nxn with several relationship types between the n elements.

```<code>id| name     | element1 | element2 | element3 ... n
1 | element1              1;2;3        1;5
2 | element2   1;2;3
3 | element3     1;5
...
</code>```

I saved the excel as CSV, which creates a lot of null cells (empty cells).

In Neo4j I tried:

```<code>load csv with headers from 'file:///test.csv' as line
WITH line where not line.ID is null
merge (c:element{id: toInteger(line.id),name: line.name})
</code>```

as a result, I receive no changes and records.

答:
Aside from @Raj's answer (property names are case sensitive), your CSV file needs to use the same delimiter between all values.

Your CSV file (as shown in your question) is using inconsistent delimiters. It uses spaces sometimes, and spaces and vertical bars (|) at other times. This will not work, as the LOAD CSV clause only supports a single kind of delimiter. Also, if you are not using the default delimiter, the comma, then you need to use the FIELDTERMINATOR option to specify what that delimiter is.

Here is a fixed version of your CSV file that uses the default delimiter, the comma. Notice that 2 adjacent commas are used to indicate a missing value. If a line is missing its first value, then the first comma should be at the beginning of that line. In addition, notice that there are no extraneous spaces.

```<code>id,name,element1,element2,element3
1,element1,,1;2;3,1;5
2,element2,1;2;3
3,element3,1;5
</code>```

Body:
I want to import an excel file which is actually a relationship matrix nxn with several relationship types between the n elements.

id| name     | element1 | element2 | element3 ... n
1 | element1              1;2;3        1;5
2 | element2   1;2;3
3 | element3     1;5
...

I saved the excel as CSV, which creates a lot of null cells (empty cells).

In Neo4j I tried:

load csv with headers from 'file:///test.csv' as line
WITH line where not line.ID is null
merge (c:element{id: toInteger(line.id),name: line.name})

as a result, I receive no changes and records.

Body:
Aside from @Raj's answer (property names are case sensitive), your CSV file needs to use the same delimiter between all values.

Your CSV file (as shown in your question) is using inconsistent delimiters. It uses spaces sometimes, and spaces and vertical bars (|) at other times. This will not work, as the LOAD CSV clause only supports a single kind of delimiter. Also, if you are not using the default delimiter, the comma, then you need to use the FIELDTERMINATOR option to specify what that delimiter is.

Here is a fixed version of your CSV file that uses the default delimiter, the comma. Notice that 2 adjacent commas are used to indicate a missing value. If a line is missing its first value, then the first comma should be at the beginning of that line. In addition, notice that there are no extraneous spaces.

id,name,element1,element2,element3
1,element1,,1;2;3,1;5
2,element2,1;2;3
3,element3,1;5


问:
How to implement link verification for sign up
I'm looking to customize Azure AD B2C Sign Up Scenario by doing the following :

User press on Reset Password, he put his email address

Link is being sent to his email address

User click on the link

User is being redirected to change password forms

User input password  + password again

Any documentation on how to implement this scenario?

答:
You could do this with custom policies.

The link could be a "magic link" as described here.

You could have a new self-asserting technical profile that just asks for an email address. This would then call a REST API that generates the "magic link" and sends the email.


问:
How to change the Content-Type in *aioes*
I'm using the library aioes and when I try to execute this script:

```<code>from aioes import Elasticsearch

import asyncio

@asyncio.coroutine
def check():
    host = 'localhost'
    port = 1234

    es = Elasticsearch(['{host}:{port}'.format(host=host, port=port)])

    answer = yield from es.search(index="test-index", body={})
    print(answer)

loop = asyncio.get_event_loop()
loop.run_until_complete(check())
</code>```

I get this error: aioes.exception.TransportError: TransportError(406, '{"error":"Content-Type header [application/octet-stream] is not supported","status":406}')

I've tried to go through the Internet, but I haven't found any solution. Where am I wrong?

答:
aioes has been abandoned and I don't think it supports ES6.0 and above, which require the content header to be specified.  If you check out the aioes github they recommend the 'official' ES python client now.

https://github.com/aio-libs-abandoned/aioes

Body:
I'm using the library aioes and when I try to execute this script:

from aioes import Elasticsearch

import asyncio

@asyncio.coroutine
def check():
    host = 'localhost'
    port = 1234

    es = Elasticsearch(['{host}:{port}'.format(host=host, port=port)])

    answer = yield from es.search(index="test-index", body={})
    print(answer)

loop = asyncio.get_event_loop()
loop.run_until_complete(check())

I get this error: aioes.exception.TransportError: TransportError(406, '{"error":"Content-Type header [application/octet-stream] is not supported","status":406}')

I've tried to go through the Internet, but I haven't found any solution. Where am I wrong?


问:
Python Multiprocessing Pool With Infinite While Loop
I am attempting to run an infinite while loop that will call a function that makes an API call. Each API call can take between 9-12 seconds and I want x processes constantly running.

I've attempted some of the existing pool examples but they seem to take a function along with a list of arguments. My function generates all inputs needed.

from multiprocessing import Process
from random import randint
from time import sleep

def loop_a():
    while 1:
        wait = randint(5,9)
        print("now waiting" + str(wait) + " seconds")
        sleep(wait)

if __name__ == '__main__':
    #Initialize two separate while loops that can call/wait for responses independently
    Process(target=loop_a).start()
    Process(target=loop_a).start()
```

<p>This sample code I found from another question solves my problem mostly, but I am wondering if there is an elegant way to define how many processes to run at once. Id like to be able to enter the number of processes as a parameter rather than defining a new line for each process. Is there a nice way to accomplish this?</p>

<p>This snippet seems to fix the issue I was facing.</p>

<pre class="lang-py prettyprint-override"><code>if __name__ == '__main__':
    [Process(target=loop_a).start() for x in range(2)]
</code>```

答:
You should use Pool

```<code>from multiprocessing import Pool
pool = Pool(processes=2) # define number of processes
results = [pool.apply(loop_a) for x in range(2)]
</code>```

Body:
I am attempting to run an infinite while loop that will call a function that makes an API call. Each API call can take between 9-12 seconds and I want x processes constantly running.

I've attempted some of the existing pool examples but they seem to take a function along with a list of arguments. My function generates all inputs needed.

from multiprocessing import Process
from random import randint
from time import sleep

def loop_a():
    while 1:
        wait = randint(5,9)
        print("now waiting" + str(wait) + " seconds")
        sleep(wait)

if __name__ == '__main__':
    #Initialize two separate while loops that can call/wait for responses independently
    Process(target=loop_a).start()
    Process(target=loop_a).start()

This sample code I found from another question solves my problem mostly, but I am wondering if there is an elegant way to define how many processes to run at once. Id like to be able to enter the number of processes as a parameter rather than defining a new line for each process. Is there a nice way to accomplish this?

This snippet seems to fix the issue I was facing.

if __name__ == '__main__':
    [Process(target=loop_a).start() for x in range(2)]

Body:
You should use Pool

from multiprocessing import Pool
pool = Pool(processes=2) # define number of processes
results = [pool.apply(loop_a) for x in range(2)]


问:
Is there a way to use To Do Skill when you lack permission to add required scopes
When I run the add_remote_skill.ps1 command I see the following warning message:

"Could not configure scopes automatically. You must configure the following scopes in the Azure Portal to use this skill: Tasks.ReadWrite Notes.ReadWrite People.Read User.Read Contacts.Read"

I lack the proper permissions to add scopes or modify the application registration for my To Do Skill.  Is there a way to use my personal hotmail/outlook account to work around not having permissions to add necessary scopes in my current tenant? If so, what are the steps to configure that?

答:
Based on the Manual Authentication Connection configuration documentation, if a Skill requires Authentication connections to Office/Office 365, the PowerShell script will automatically add the required configuration to your Bot and associated Azure AD Application.

If your Azure AD application has allowed users outside of your tenant to access the application, then auto-provisioning isn't possible and the CLI will give a warning(the warning which you got above) that it wasn't able to configure Scopes and provides the Scopes you should manually add. Follow the instructions below to manually add the scopes:

Find the Azure AD Application for your Bot within the Azure Portal.

In the Authentication section ensure the Redirect Uri is set to https://token.botframework.com/.auth/web/redirect

In the API permissions section click Add Permission, then Microsoft Graph and Delegated Permissions. Find each scope provided in the message shown during Skill registration and add.


问:
Problem getting certificate from let's encrypt using Traefik with docker
I've set up Traefik with Docker and a service behind it. The basic setup works. I can browse to port 80 using the domain name I'm redirected to https and then see "invalid certificate" - since the let's encrypt part is broken.

[ router ] <-:80/:443-> [linux/docker [Traefik:80/:443][Service:8080]]

Here is the entry in the log (edited domain.)

Logs:

acme: Error -> One or more domains had a problem:\n[xyz.example.net] acme: error: 400 :: urn:ietf:params:acme:error:connection :: Fetching
  http://xyz.example.net/.well-known/acme-challenge/eIAFZqaGMHMWaBjINjzk4m8PuWiYfuCHCTnSU9M:
  Error getting validation data, url: \n"

The error message is accurate, I can not browse to that URL.  I have noticed that I can go to that URL using the internal IP http://10.0.0.21/.well-known/acme-challenge/key and Traefik responds with this in the log:

traefik    | time="2019-05-28T21:20:52Z" level=error msg="Error getting challenge for token retrying in 542.914495ms"

I suspect the problem is the domain name redirect setup. My service is at xyz.example.net (and so is Traefik.) I suspect the problem is that Traefik is redirecting all traffic coming in on xyz.example.net:80/:443 to the service, and not handling the ./well-known/acme-challenge itself. Do I need to give the gateway itself a name? (E.g. zzz.example.net is Traefik and xyz.example.net is the service?)

How can I fix this?

My TOML file:

```<code>debug = false

logLevel = "ERROR" #DEBUG, INFO, WARN, ERROR, FATAL, PANIC
InsecureSkipVerify = true
defaultEntryPoints = ["https", "http"]

[entryPoints]
  [entryPoints.http]
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]

[retry]

[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "example.net"
watch = true
exposedbydefault = false

[acme]
email = "me@example.net"
storage = "acme.json"
entryPoint = "https"
onDemand = false

onHostRule = true
[acme.httpChallenge]
entryPoint = "http"
</code>```

答:
I noticed that although the internal IP 192.xxx worked - the external IP did not.  Of course, I would say, this seems like a firewall problem - BUT - the firewall lets thru traffic just fine for the services that I was testing, so I was confused.

The solution? port 80 was not being forwarded on the firewall, 443 was. So when I tried testing with curl/browser I was typing in https://xyz.example.com - and that was working.

Body:
I've set up Traefik with Docker and a service behind it. The basic setup works. I can browse to port 80 using the domain name I'm redirected to https and then see "invalid certificate" - since the let's encrypt part is broken.

[ router ] <-:80/:443-> [linux/docker [Traefik:80/:443][Service:8080]]

Here is the entry in the log (edited domain.)

Logs:

acme: Error -> One or more domains had a problem:\n[xyz.example.net] acme: error: 400 :: urn:ietf:params:acme:error:connection :: Fetching
  http://xyz.example.net/.well-known/acme-challenge/eIAFZqaGMHMWaBjINjzk4m8PuWiYfuCHCTnSU9M:
  Error getting validation data, url: \n"

The error message is accurate, I can not browse to that URL.  I have noticed that I can go to that URL using the internal IP http://10.0.0.21/.well-known/acme-challenge/key and Traefik responds with this in the log:

traefik    | time="2019-05-28T21:20:52Z" level=error msg="Error getting challenge for token retrying in 542.914495ms"

I suspect the problem is the domain name redirect setup. My service is at xyz.example.net (and so is Traefik.) I suspect the problem is that Traefik is redirecting all traffic coming in on xyz.example.net:80/:443 to the service, and not handling the ./well-known/acme-challenge itself. Do I need to give the gateway itself a name? (E.g. zzz.example.net is Traefik and xyz.example.net is the service?)

How can I fix this?

My TOML file:

debug = false

logLevel = "ERROR" #DEBUG, INFO, WARN, ERROR, FATAL, PANIC
InsecureSkipVerify = true
defaultEntryPoints = ["https", "http"]

[entryPoints]
  [entryPoints.http]
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]

[retry]

[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "example.net"
watch = true
exposedbydefault = false

[acme]
email = "me@example.net"
storage = "acme.json"
entryPoint = "https"
onDemand = false

onHostRule = true
[acme.httpChallenge]
entryPoint = "http"


问:
How to update array value in Laravel
My controller code:

```<code>        $userBasicInfoId = $this->userBasicInfo->where('user_id', $userProfile['id'])->value('id');
        if($userBasicInfoId) {
            $userBasicInfo = $this->userBasicInfo->find($userBasicInfoId);
            $userBasicInfo->fill($userProfile)->save();
        } else {
            $userBasicInfo = $this->userBasicInfo->create($request->only($this->userBasicInfo->getModel()->fillable));
        }
</code>```

This is my userBasicInfo model values:

```<code>        protected $table = "user_basic_info";

protected $fillable = [
    'first_name', 'middle_name', 'last_name', 'profile_pic', 'date_of_birth', 'gender', 'area_id', 'user_id', 'created_by', 'updated_by', 'created_at', 'deletedAt','title','cell_no','address','ssn','work_phone','fax','extension','primary_facility','affiliated_facility','employed_by','emergency_phone','designation','department','employment_type','biography','hiring_date','from','to'
];
</code>```

I can update the values but the issue is there is only one field which I am sending as array that is affiliated_facility, how I can update this value?

My body request:

```<code>                  "user_profile": {

    "id": 38,
    "email": "shahzad124@ovadamd.com",
    "status": 0,
    "first_name": "shahzad12",
    "middle_name": "Admin",
    "last_name": "super",
    "date_of_birth": "2015-01-01",
    "gender": "M",
    "address": "Minhatten NY",
    "city": "New York",
    "state": "Washington",
    "zip": "12312",
    "fax": "111-111-1111",
    "extension": "2471",
    "work_phone": "111-111-1111",
    "social_security": "111-11-1111",
    "module_id": 2,
    "title": "Mr",
    "cell_no": "124788",
    "ssn": "256",
    "primary_facility": 1,
    "affiliated_facility":  [1],
    "employed_by": "john",
    "emergency_phone": "57744",
    "designation": " supervisor",
    "department": "facility",
    "employment_type": "Temporary",
    "biography": "I am Doctor",
    "hiring_date": "2015-01-01",
    "from": "2015-01-01",
    "to": "2015-01-01",
    "image": ""
    },
</code>```

You can see in my body request I am sending "affiliated_facility" (marked with [1] above). When I hit request it says:

```<code>   "Array to string conversion (SQL: update `user_basic_info` set `gender` = M, `updated_at` = 2019-05-29 18:19:34, `affiliated_facility` = 1 where `id` = 36)"
</code>```

How can I update this specific field which I am sending as array?

答:
You can use list function, but you have to beware of that because the list function could change the behaviors for PHP 4 to 5/7.

For example:

You have array $array = [1,2,3], so far fine right?

So in PHP 4 if you do:

```<code>list($one, $two, $three) = $array
</code>```

Your output will be:

```<code>$one = 3, $two = 2, $three = 1
</code>```

Because in the PHP 4 the list function assign the values from right to left, but if you using in 7 the output it'll be reverse, example:

```<code>list($one, $two, $three) = $array
// $one = 1, $two = 2, $three = 4
</code>```

It'll gonna help for your case, otherwise, I strongly suggest you revise your code and structure, if your field affiliated_facility isn't an array so why you're receiving one? No makes sense right?

So before you try "approach" a solution in PHP for that I strongly suggest you revise your logic.

For more reference for the function, you can see at the documentation: https://www.php.net/manual/en/function.list.php

Title: How to update array value in Laravel

Body:
My controller code:

        $userBasicInfoId = $this->userBasicInfo->where('user_id', $userProfile['id'])->value('id');
        if($userBasicInfoId) {
            $userBasicInfo = $this->userBasicInfo->find($userBasicInfoId);
            $userBasicInfo->fill($userProfile)->save();
        } else {
            $userBasicInfo = $this->userBasicInfo->create($request->only($this->userBasicInfo->getModel()->fillable));
        }

This is my userBasicInfo model values:

        protected $table = "user_basic_info";

protected $fillable = [
    'first_name', 'middle_name', 'last_name', 'profile_pic', 'date_of_birth', 'gender', 'area_id', 'user_id', 'created_by', 'updated_by', 'created_at', 'deletedAt','title','cell_no','address','ssn','work_phone','fax','extension','primary_facility','affiliated_facility','employed_by','emergency_phone','designation','department','employment_type','biography','hiring_date','from','to'
];

I can update the values but the issue is there is only one field which I am sending as array that is affiliated_facility, how I can update this value?

My body request:

                  "user_profile": {

    "id": 38,
    "email": "shahzad124@ovadamd.com",
    "status": 0,
    "first_name": "shahzad12",
    "middle_name": "Admin",
    "last_name": "super",
    "date_of_birth": "2015-01-01",
    "gender": "M",
    "address": "Minhatten NY",
    "city": "New York",
    "state": "Washington",
    "zip": "12312",
    "fax": "111-111-1111",
    "extension": "2471",
    "work_phone": "111-111-1111",
    "social_security": "111-11-1111",
    "module_id": 2,
    "title": "Mr",
    "cell_no": "124788",
    "ssn": "256",
    "primary_facility": 1,
    "affiliated_facility":  [1],
    "employed_by": "john",
    "emergency_phone": "57744",
    "designation": " supervisor",
    "department": "facility",
    "employment_type": "Temporary",
    "biography": "I am Doctor",
    "hiring_date": "2015-01-01",
    "from": "2015-01-01",
    "to": "2015-01-01",
    "image": ""
    },

You can see in my body request I am sending "affiliated_facility" (marked with [1] above). When I hit request it says:

   "Array to string conversion (SQL: update `user_basic_info` set `gender` = M, `updated_at` = 2019-05-29 18:19:34, `affiliated_facility` = 1 where `id` = 36)"

How can I update this specific field which I am sending as array?

Body:
You can use list function, but you have to beware of that because the list function could change the behaviors for PHP 4 to 5/7.

For example:

You have array $array = [1,2,3], so far fine right?

So in PHP 4 if you do:

list($one, $two, $three) = $array

Your output will be:

$one = 3, $two = 2, $three = 1

Because in the PHP 4 the list function assign the values from right to left, but if you using in 7 the output it'll be reverse, example:

list($one, $two, $three) = $array
// $one = 1, $two = 2, $three = 4

It'll gonna help for your case, otherwise, I strongly suggest you revise your code and structure, if your field affiliated_facility isn't an array so why you're receiving one? No makes sense right?

So before you try "approach" a solution in PHP for that I strongly suggest you revise your logic.

For more reference for the function, you can see at the documentation: https://www.php.net/manual/en/function.list.php


问:
google cloud python sdk installation error - SSL Certification Error
Trying to install Google Cloud SDK(Python) on Windows 10 for All Users. Getting the following error.

This is new machine and start building fresh. Installed python 2.7 version prior to this.

Please help me to resolve this.

Output folder: C:\Program Files (x86)\Google\Cloud SDK Downloading
  Google Cloud SDK core. Extracting Google Cloud SDK core. Create Google
  Cloud SDK bat file: C:\Program Files (x86)\Google\Cloud
  SDK\cloud_env.bat Installing components. Welcome to the Google Cloud
  SDK! This will install all the core command line tools necessary for
  working with the Google Cloud Platform. Traceback (most recent call
  last):   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\bin\bootstrapping\install.py", line 214, in

      main()   File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\bootstrapping\install.py", line 192, in main
      Install(pargs.override_components, pargs.additional_components)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\bin\bootstrapping\install.py", line 134, in
  Install
      InstallOrUpdateComponents(to_install, update=update)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\bin\bootstrapping\install.py", line 177, in
  InstallOrUpdateComponents
      ['--quiet', 'components', verb, '--allow-no-backup'] + component_ids)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 813, in
  Execute
      self._HandleAllErrors(exc, command_path_string, specified_arg_names)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 787, in
  Execute
      resources = args.calliope_command.Run(cli=self, args=args)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\backend.py", line
  754, in Run
      resources = command_instance.Run(args)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\surface\components\update.py", line 99, in
  Run
      version=args.version)   File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\update_manager.py",
  line 850, in Update
      command_path='components.update')   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\update_manager.py",
  line 591, in _GetStateAndDiff
      command_path=command_path)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\update_manager.py",
  line 574, in _GetLatestSnapshot
      *effective_url.split(','), command_path=command_path)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\snapshots.py",
  line 165, in FromURLs
      for url in urls]   File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\snapshots.py",
  line 186, in _DictFromURL
      response = installers.ComponentInstaller.MakeRequest(url, command_path)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\installers.py",
  line 285, in MakeRequest
      return ComponentInstaller._RawRequest(req, timeout=timeout)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\installers.py",
  line 329, in _RawRequest
      should_retry_if=RetryIf, sleep_ms=500)   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\core\util\retry.py", line 155,
  in TryFunc
      return func(*args, kwargs), None   File "C:\Program Files (x86)\Google\Cloud
  SDK\google-cloud-sdk\lib\googlecloudsdk\core\url_opener.py", line 73,
  in urlopen
      return opener.open(req, data, timeout)   File "c:\users\cpa8161\appdata\local\temp\tmpxcdivh\python\lib\urllib2.py",
  line 429, in open
      response = self._open(req, data)   File "c:\users\cpa8161\appdata\local\temp\tmpxcdivh\python\lib\urllib2.py",
  line 447, in _open
      '_open', req)   File "c:\users\cpa8161\appdata\local\temp\tmpxcdivh\python\lib\urllib2.py",
  line 407, in _call_chain
      result = func(*args)   File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\url_opener.py", line 58,
  in https_open
      return self.do_open(build, req)   File "c:\users\cpa8161\appdata\local\temp\tmpxcdivh\python\lib\urllib2.py",
  line 1195, in do_open
      h.request(req.get_method(), req.get_selector(), req.data, headers)   File
  "c:\users\cpa8161\appdata\local\temp\tmpxcdivh\python\lib\httplib.py",
  line 1042, in request
      self._send_request(method, url, body, headers)   File "c:\users\cpa8161\appdata\local\temp\tmpxcdivh\python\lib\httplib.py",
  line 1082, in _send_request
      self.endheaders(body)   File "c:\users\cpa8161\appdata\local\temp\tmpxcdivh\python\lib\httplib.py",
  line 1038, in endheaders
      self._send_output(message_body)   File "c:\users\cpa8161\appdata\local\temp\tmpxcdivh\python\lib\httplib.py",
  line 882, in _send_output
      self.send(msg)   File "c:\users\cpa8161\appdata\local\temp\tmpxcdivh\python\lib\httplib.py",
  line 844, in send
      self.connect()   File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\third_party\httplib2__init__.py", line 1081,
  in connect
      raise SSLHandshakeError(e)
  **httplib2.SSLHandshakeError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661) Failed to install.

答:
I just spent hours trying to make the installer run trying to edit ca cert files but the installer keeps wiping the directories as part of the installation process. In order to make the bundle gcloud sdk installer work, I ended up having to create an environment variable SSL_CERT_FILE and setting the path to a ca cert text file that contained the Google CAs + my company's proxy CA cert. Then the installer ran without issue. It seems that env variable is used by the python http client for CA validation.

Then you need to run gcloud config set custom_ca_certs_file  before running gcloud init