问:
Why is my javascript function not found by the page it is embedded in?
I have a page that has a simple javascript in the header portion of the page:

```<code><script type="text/javascript">
    function doLogout() {
        var conf = confirm("Really log out?");
        if (conf === true) {      //changed == to === for boolean comparison
            $.post("logout.aspx");
        }
    }
</script>
</code>```

It uses jQuery to do an AJAX post to my logout page.  The only issue right now is that when I click on the link (logout) to fire this function, nothing happens.  I checked FireBug's console, and it told me that the function is not defined.  This has happened to me before, but I think I botched a bunch of code to fix it sometimes.

Does anyone know the proper way to fix this issue?

Edit

After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise!  Hopefully this information will be useful for more people.

答:
This can also occur if there is a syntax error earlier in your javascript code.  Often this will just be interpreted as the function not existing (nor any function AFTER the error).  Check the code above this code (if there is any) and this code for syntax errors.

A way to tell if the cache error is it is to open Firebug and view the Script source.  If the page was cached, you won't see your code.   If it loaded but has syntax errors, the code will show, though it won't "find" it.

OwnerDisplayName: Anders

Body:
I have a page that has a simple javascript in the header portion of the page:

It uses jQuery to do an AJAX post to my logout page.  The only issue right now is that when I click on the link (logout) to fire this function, nothing happens.  I checked FireBug's console, and it told me that the function is not defined.  This has happened to me before, but I think I botched a bunch of code to fix it sometimes.

Does anyone know the proper way to fix this issue?

Edit

After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise!  Hopefully this information will be useful for more people.

LastEditorDisplayName: Anders

OwnerDisplayName: Bill James

LastEditorDisplayName: Joel Coehoorn


来源: stackexchange

问:
How to resolve ambiguous column names when retrieving results?
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

```<code>SELECT * FROM news JOIN users ON news.user = user.id
</code>```

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

答:
Here's an answer to the above, that's both simple and also works with JSON results being returned. While the SQL query will automatically prefix table names to each instance of identical field names when you use SELECT *, JSON encoding of the result to send back to the webpage, ignores the values of those fields with a duplicate name and instead returns a NULL value.

Precisely what it does is include the first instance of the duplicated field name, but makes its value NULL. And the second instance of the field name (in the other table) is omitted entirely, both field name and value. But, when you test the query directly on the database (such as using Navicat), all fields are returned in the result set. It's only when you next do JSON encoding of that result, do they have NULL values and subsequent duplicate names are omitted entirely.

So, an easy way to fix that problem is to first do a SELECT *, then follow with aliased fields for the duplicates. Here's an example, where both tables have identically named site_name fields.

```<code>SELECT *, w.site_name AS wo_site_name FROM ws_work_orders w JOIN ws_inspections i WHERE w.hma_num NOT IN(SELECT hma_number FROM ws_inspections) ORDER BY CAST(w.hma_num AS UNSIGNED);
</code>```

Now in the decoded JSON, you can use the field wo_site_name and it has a value. In this case, site names have special characters such as apostrophes and single quotes, hence the encoding when originally saving, and the decoding when using the result from the database.

```<code>...decHTMLifEnc(decodeURIComponent( jsArrInspections[x]["wo_site_name"]))
</code>```

You must always put the * first in the SELECT statement, but after it you can include as many named and aliased columns as you want, as repeatedly selecting a column causes no problem.

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 4.0

Body:
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

SELECT * FROM news JOIN users ON news.user = user.id

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

LastEditorDisplayName: Dan

Body:
Here's an answer to the above, that's both simple and also works with JSON results being returned. While the SQL query will automatically prefix table names to each instance of identical field names when you use SELECT *, JSON encoding of the result to send back to the webpage, ignores the values of those fields with a duplicate name and instead returns a NULL value.

Precisely what it does is include the first instance of the duplicated field name, but makes its value NULL. And the second instance of the field name (in the other table) is omitted entirely, both field name and value. But, when you test the query directly on the database (such as using Navicat), all fields are returned in the result set. It's only when you next do JSON encoding of that result, do they have NULL values and subsequent duplicate names are omitted entirely.

So, an easy way to fix that problem is to first do a SELECT *, then follow with aliased fields for the duplicates. Here's an example, where both tables have identically named site_name fields.

SELECT *, w.site_name AS wo_site_name FROM ws_work_orders w JOIN ws_inspections i WHERE w.hma_num NOT IN(SELECT hma_number FROM ws_inspections) ORDER BY CAST(w.hma_num AS UNSIGNED);

Now in the decoded JSON, you can use the field wo_site_name and it has a value. In this case, site names have special characters such as apostrophes and single quotes, hence the encoding when originally saving, and the decoding when using the result from the database.

...decHTMLifEnc(decodeURIComponent( jsArrInspections[x]["wo_site_name"]))

You must always put the * first in the SELECT statement, but after it you can include as many named and aliased columns as you want, as repeatedly selecting a column causes no problem.


问:
Simple TCP Server unable to connect
I'm in my intro to networking course and we are learning how to program a basic TCP server.

My Setup:
The assignment calls for a server that  web server that handles one HTTP request at a time. My web server should "accept and parse the HTTP request, get the requested file from the server’s file system, create an HTTP response message consisting of the requested file preceded by header lines, and then send the response directly to the client. If the requested file is not present in the server, the server should send an HTTP “404 Not Found” message back to the client."  I have the server coded in Python (see below) and as far as I can tell, the code is accurate. In the same directory I have also created a simple hello world html file so I have something to request.

Running my server:
When I run the code, the terminal expected 'ready to serve...' message and listens for a connection. This is correct.

Then when I type in a URL in my browser (I've tried both http://localhost:1001 and http://localhost:1001/HelloWorld.html) the browser says its unable to connect.

Unable to connect screen from browser

I'm pretty sure I'm either not connecting to the server properly as a client or if my windows machine isn't set up properly but any advise on how to connect and get my request through to the server would be greatly appreciated.

```<code>#import socket module
from socket import *
import sys # In order to terminate the program

serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a sever socket
serverPort = 1001
serverSocket.bind(('',serverPort))
serverSocket.listen(1)

while True:
    #Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(1024).decode()
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read()
        #Send one HTTP header line into socket
        #Fill in start
        header = 'HTTP/1.1 200 OK\n'
        connectionSocket.send(header.encode())

        #Fill in end

        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())

        connectionSocket.send("\r\n".encode())
        connectionSocket.close()
    except IOError:
        #Send response message for file not found (404)
        #Fill in start
        error = 'HTTP/1.1 404 Not Found'
        connectionSocket.send(error.encode())
        #Fill in end

        #Close client socket
        #Fill in start
        connectionSocket.close()
        #Fill in end

serverSocket.close()
sys.exit()  #Terminate the program after sending the corresponding data
</code>```

答:
I just tried running your server and it worked properly. I tried getting the python code itself using the url "http://localhost:1001/test.py" and I got back your code.

Some things you might want to check is if you have access to your server's port 1001. Since this is not a standard port, some hosts could block it. You could try using port 80 instead.

Title: Simple TCP Server unable to connect

Body:
I'm in my intro to networking course and we are learning how to program a basic TCP server.

My Setup:
The assignment calls for a server that  web server that handles one HTTP request at a time. My web server should "accept and parse the HTTP request, get the requested file from the server’s file system, create an HTTP response message consisting of the requested file preceded by header lines, and then send the response directly to the client. If the requested file is not present in the server, the server should send an HTTP “404 Not Found” message back to the client."  I have the server coded in Python (see below) and as far as I can tell, the code is accurate. In the same directory I have also created a simple hello world html file so I have something to request.

Running my server:
When I run the code, the terminal expected 'ready to serve...' message and listens for a connection. This is correct.

Then when I type in a URL in my browser (I've tried both http://localhost:1001 and http://localhost:1001/HelloWorld.html) the browser says its unable to connect.

Unable to connect screen from browser

I'm pretty sure I'm either not connecting to the server properly as a client or if my windows machine isn't set up properly but any advise on how to connect and get my request through to the server would be greatly appreciated.

#import socket module
from socket import *
import sys # In order to terminate the program

serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a sever socket
serverPort = 1001
serverSocket.bind(('',serverPort))
serverSocket.listen(1)

while True:
    #Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(1024).decode()
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read()
        #Send one HTTP header line into socket
        #Fill in start
        header = 'HTTP/1.1 200 OK\n'
        connectionSocket.send(header.encode())

        #Fill in end

        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())

        connectionSocket.send("\r\n".encode())
        connectionSocket.close()
    except IOError:
        #Send response message for file not found (404)
        #Fill in start
        error = 'HTTP/1.1 404 Not Found'
        connectionSocket.send(error.encode())
        #Fill in end

        #Close client socket
        #Fill in start
        connectionSocket.close()
        #Fill in end

serverSocket.close()
sys.exit()  #Terminate the program after sending the corresponding data


问:
androidx ViewModel MutableLiveData LiveData
I am new to Kotlin and Android programming. I cannot figure out why onChanged didnt show up in the first two examples but the last sample is ok. Any suggestions will be greater appreciated. </p>

```<code>var liveDataTest:MutableLiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})
</code>```

```<code>var liveDataTest:LiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})
</code>```

```<code>class test:androidx.lifecycle.Observer<String>{
    override fun onChanged(t: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}
</code>```

答:
In kotlin user can directly observe without implement override methods :</p>

```<code>val liveDataTest: MutableLiveData<String> = MutableLiveData("ABC")
        liveDataTest.observe(this, androidx.lifecycle.Observer { it ->
            Toast.makeText(context,it,Toast.LENGTH_SHORT).show()
        })
</code>```

Body:
I am new to Kotlin and Android programming. I cannot figure out why onChanged didnt show up in the first two examples but the last sample is ok. Any suggestions will be greater appreciated.

var liveDataTest:MutableLiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})

var liveDataTest:LiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})

class test:androidx.lifecycle.Observer<String>{
    override fun onChanged(t: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

Body:
In kotlin user can directly observe without implement override methods :

val liveDataTest: MutableLiveData<String> = MutableLiveData("ABC")
        liveDataTest.observe(this, androidx.lifecycle.Observer { it ->
            Toast.makeText(context,it,Toast.LENGTH_SHORT).show()
        })


问:
Why Mercurial doesn't need "recursive merge strategy"?
AFAIK git's default merge strategy is "recursive" which means when more than one "common ancestor" ends up being a "good candidate", git will merge them and create a new "virtual common ancestor" for the contributors. It basically helps solving situations where files were already merged and it avoids merging them again or coming up with incorrect merge contributors.

My question is: if Mercurial doesn't use "recursive", how does it handle the same situation?

Thanks

答:
Most version control system do not know how to handle a situation where there is multiple base versions for a merge. The math merge equation is

Result = Destination + SumOf(I=1-N)(Base(I) - Source(I))

In most cases N=1 and you got a classic merge with source, destination and base versions which a typical 3-way merge tool can handle. Although many source control systems do not have even in this simple case a correct algorithm for finding the Base version. To do so you need to trace back through version tree going up the merge arrows, until you meet at a common ancestor. But sometimes the common ancestor is too far, not fitting the equation above for N=1 and in that case you need to find multiple common ancestors for multiple partial merges.

Example would be a case where a branch is merged down and up multiple times, then we try to cross merge the changes from this branch to another branch. In such case the N > 1, but lower than the number of merge downs on the source branch.

This is one of the hardest thing to do in branch merging and I don't know a source control system that actually does it correctly.

ContentLicense: CC BY-SA 3.0


问:
Is there any command to toggle enable auto text wrapping?
By default, I think my vimrc setttings enable the auto-wrapping. However, sometimes, I would like to see text lines are not wrapped. Is there any command I toggle the text line wrapping enabled and disabled? This would avoid me to exit and to change settings.</p>

答: I happen to like tpope’s unimpaired plugin, where yow will toggle wrap settings.

ContentLicense: CC BY-SA 2.5


问:
VBA. Deleting multiple cells in a row if one cell is blank
I have multiple columns in an excel sheet...say A1:D10.
I want to find any blank cells in column C, delete that cell as well as the A,B, and D cells of that same row, then shift up.  But only in the range of A1:D10.  I have other information in this excel sheet outside this range that I want to perserve in its original position.  Therefore I can not use somthing like this:

```<code>.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
</code>```

Nor can I get something like the following to work, because it only shifts the single column up, not all four columns.

```<code>Set rng = Range("A1:D10").SpecialCells(xlCellTypeBlanks)
rng.Rows.Delete Shift:=xlShiftUp
</code>```

答:
If there is no data in columns A to D below row 10 that you don't want to move up, then SpecialCells and Delete Shift Up can be used like this

```<code>Sub Demo1()
    Dim ws As Worksheet
    Dim TestColumn As Long
    Dim StartColumn As Long
    Dim EndColumn As Long
    Dim FirstRow As Long
    Dim LastRow As Long

    Dim i As Long
    Dim rng As Range, arr As Range

    ' set up reference data
    Set ws = ActiveSheet '<~~ update as required
    TestColumn = 3  'C
    StartColumn = 1 'A
    EndColumn = 4   'D
    FirstRow = 1
    LastRow = 10

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    With ws
        On Error Resume Next
            Set rng = .Range(.Cells(FirstRow, TestColumn), .Cells(LastRow, TestColumn)).SpecialCells(xlCellTypeBlanks)
        On Error GoTo 0

        If Not rng Is Nothing Then
            For Each arr In rng.Areas
                arr.EntireRow.Resize(, EndColumn - StartColumn + 1).Delete Shift:=xlShiftUp
            Next
        End If
    End With
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub
</code>```

If there is  data in columns A to D below row 10 that you don't want to move up, then you can use Cut and Paste, like this

```<code>Sub Demo()
    Dim ws As Worksheet
    Dim TestColumn As Long
    Dim StartColumn As Long
    Dim EndColumn As Long
    Dim FirstRow As Long
    Dim LastRow As Long

    Dim i As Long

    ' set up reference data
    Set ws = ActiveSheet '<~~ update as required
    TestColumn = 3  'C
    StartColumn = 1 'A
    EndColumn = 4   'D
    FirstRow = 1
    LastRow = 10

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    With ws
        If IsEmpty(.Cells(LastRow, TestColumn)) Then
            .Cells(LastRow, StartColumn).Resize(1, EndColumn - StartColumn + 1).Clear
        End If
        For i = LastRow - 1 To FirstRow Step -1
            If IsEmpty(.Cells(i, TestColumn)) Then
                .Range(.Cells(i + 1, StartColumn), .Cells(LastRow, EndColumn)).Cut .Cells(i, StartColumn)
            End If
        Next
    End With
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub
</code>```

Body:
I have multiple columns in an excel sheet...say A1:D10.
I want to find any blank cells in column C, delete that cell as well as the A,B, and D cells of that same row, then shift up.  But only in the range of A1:D10.  I have other information in this excel sheet outside this range that I want to perserve in its original position.  Therefore I can not use somthing like this:

.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

Nor can I get something like the following to work, because it only shifts the single column up, not all four columns.

Set rng = Range("A1:D10").SpecialCells(xlCellTypeBlanks)
rng.Rows.Delete Shift:=xlShiftUp

Body:
If there is no data in columns A to D below row 10 that you don't want to move up, then SpecialCells and Delete Shift Up can be used like this

Sub Demo1()
    Dim ws As Worksheet
    Dim TestColumn As Long
    Dim StartColumn As Long
    Dim EndColumn As Long
    Dim FirstRow As Long
    Dim LastRow As Long

    Dim i As Long
    Dim rng As Range, arr As Range

    ' set up reference data
    Set ws = ActiveSheet '<~~ update as required
    TestColumn = 3  'C
    StartColumn = 1 'A
    EndColumn = 4   'D
    FirstRow = 1
    LastRow = 10

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    With ws
        On Error Resume Next
            Set rng = .Range(.Cells(FirstRow, TestColumn), .Cells(LastRow, TestColumn)).SpecialCells(xlCellTypeBlanks)
        On Error GoTo 0

        If Not rng Is Nothing Then
            For Each arr In rng.Areas
                arr.EntireRow.Resize(, EndColumn - StartColumn + 1).Delete Shift:=xlShiftUp
            Next
        End If
    End With
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

If there is  data in columns A to D below row 10 that you don't want to move up, then you can use Cut and Paste, like this

Sub Demo()
    Dim ws As Worksheet
    Dim TestColumn As Long
    Dim StartColumn As Long
    Dim EndColumn As Long
    Dim FirstRow As Long
    Dim LastRow As Long

    Dim i As Long

    ' set up reference data
    Set ws = ActiveSheet '<~~ update as required
    TestColumn = 3  'C
    StartColumn = 1 'A
    EndColumn = 4   'D
    FirstRow = 1
    LastRow = 10

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    With ws
        If IsEmpty(.Cells(LastRow, TestColumn)) Then
            .Cells(LastRow, StartColumn).Resize(1, EndColumn - StartColumn + 1).Clear
        End If
        For i = LastRow - 1 To FirstRow Step -1
            If IsEmpty(.Cells(i, TestColumn)) Then
                .Range(.Cells(i + 1, StartColumn), .Cells(LastRow, EndColumn)).Cut .Cells(i, StartColumn)
            End If
        Next
    End With
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub


问:
How to JUnit MapperToJsonString class
Please help me concerning my problem on how to unit test my class.

Here is the class that I can't fully cover with my JUnit.

```<code>@Component
public class Utils {

    @Autowired
    private ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private LoggingService loggingService;

    public <E> String mapToJsonString(E object) {
        try {
            if (object == null) {
                throw new IOException(ErrorMessage.ERROR_PROCESSING_JSON_NULL);
            }

            return mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object);
        } catch (IOException e) {
            loggingService.logError(this.getClass().getName(), "1", ErrorMessage.ERROR_MAPPING_TO_JSONSTRING, e);
            return "";
        }
    }
}
</code>```

Here is my test case:

```<code>@MockBean
private LoggingService loggingService;
@Before
public void setUp() {
    myModelClass = new MyModelclass();
    myModelClass.setStatus("U");
    myModelClass.setTermCode("001");
    myModelClass.setLocation("BGC");
}

@Test
public void testObjectToJson() throws JsonProcessingException {

    Mockito.when(utils.mapToJsonString(myModelClass)).thenReturn("");
    String output = utils.mapToJsonString(myModelClass);
    assertThat(output).isEqualTo(utils.mapToJsonString(""));
}

@Test(expected=IOException.class)
public void testJsonParsingException() {
    utils.mapToJsonString(null);
    String output = utils.mapToJsonString(myModelClass);
    Mockito.when(utils.mapToJsonString(null)).thenThrow(new IOException());
    assertThat(output).isNull();
}
</code>```

Any help would be much appreciated. Thanks.

答:
You should not be mocking Utils object or mapToJsonString() method as this is the method which you want to test and you would want to call the real method instead of mocked.

Which means following statements should not be present in your junit.

```<code>Mockito.when(utils.mapToJsonString(myModelClass)).thenReturn("");
Mockito.when(utils.mapToJsonString(null)).thenThrow(new IOException());
</code>```

At the outset, I can think of following junits but you should think of more scenarios to test and write junits for them.

Happy scenario : You pass in a object to mapToJsonString() and assert/verify the JSON String it returns.

Pass null to mapToJsonString() and assert/verify empty String. As in the catch block you are using an external object loggingService, you need to mock loggingService.logError() call.

Also, do not write any junit for @Test(expected=IOException.class) as it will never be successful because you are not re-throwing IOException in catch block.

Title: How to JUnit MapperToJsonString class

Body:
Please help me concerning my problem on how to unit test my class.

Here is the class that I can't fully cover with my JUnit.

@Component
public class Utils {

    @Autowired
    private ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private LoggingService loggingService;

    public <E> String mapToJsonString(E object) {
        try {
            if (object == null) {
                throw new IOException(ErrorMessage.ERROR_PROCESSING_JSON_NULL);
            }

            return mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object);
        } catch (IOException e) {
            loggingService.logError(this.getClass().getName(), "1", ErrorMessage.ERROR_MAPPING_TO_JSONSTRING, e);
            return "";
        }
    }
}

Here is my test case:

@MockBean
private LoggingService loggingService;
@Before
public void setUp() {
    myModelClass = new MyModelclass();
    myModelClass.setStatus("U");
    myModelClass.setTermCode("001");
    myModelClass.setLocation("BGC");
}

@Test
public void testObjectToJson() throws JsonProcessingException {

    Mockito.when(utils.mapToJsonString(myModelClass)).thenReturn("");
    String output = utils.mapToJsonString(myModelClass);
    assertThat(output).isEqualTo(utils.mapToJsonString(""));
}

@Test(expected=IOException.class)
public void testJsonParsingException() {
    utils.mapToJsonString(null);
    String output = utils.mapToJsonString(myModelClass);
    Mockito.when(utils.mapToJsonString(null)).thenThrow(new IOException());
    assertThat(output).isNull();
}

Any help would be much appreciated. Thanks.

Body:
You should not be mocking Utils object or mapToJsonString() method as this is the method which you want to test and you would want to call the real method instead of mocked.

Which means following statements should not be present in your junit.

Mockito.when(utils.mapToJsonString(myModelClass)).thenReturn("");
Mockito.when(utils.mapToJsonString(null)).thenThrow(new IOException());

At the outset, I can think of following junits but you should think of more scenarios to test and write junits for them.

Happy scenario : You pass in a object to mapToJsonString() and assert/verify the JSON String it returns.

Pass null to mapToJsonString() and assert/verify empty String. As in the catch block you are using an external object loggingService, you need to mock loggingService.logError() call.

Also, do not write any junit for @Test(expected=IOException.class) as it will never be successful because you are not re-throwing IOException in catch block.


问:
How do I count the number of words (text) in an HTML source
I have some html documents for which I need to return the number of words in the document. This count should only include actual text (so no html tags e.g. html, br, etc).

Any ideas how to do this? Naturally, I would prefer to re-use some code.

Thanks,

Assaf

答:
Strip out the HTML tags , get the text content , reuse Jsoup

Read file line by line , hold a Map<String, Integer> wordToCountMap and read through and operate on the Map


问:
How to find rows in SQL DB with a definite word length?
Good day, I've got a column with text in my table, but i need to export words 17 letters long only in it.

I tried to use

```<code>where description like '%_%_%_%_%_%_%_%_%_%_%_%_%_%_%'
</code>```

but my query newer  completes.

This is an example of text cell

REIGHT CAR DUMP T.M. "HOWO", COMMERCIAL NAME A7, MODEL TOTAL 4 PIECES,
  WITHOUT PACKING IDENTIFICATION NUMBER ENGINE NUMBER 191007018177;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 3) VIN: LZZ5DYSD5KA545780;
  CHASSIS NUMBER LZZ5DYSD5KA545780; ENGINE NUMBER 191007018247;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 4) VIN: LZZ5DYSD2KA545784;
  CHASSIS NUMBER LZZ5DYSD2KA545784; ENGINE NUMBER 191007018137;
  TRANSMISSION NUMBER NO; BRIDGE ROOMS ARE NOT AVAILABLE FREIGHT VEHICLE
  –

I am using Microsoft SQL management studio

答:
If you are using sql server

```<code>where LEN(description) = 17
</code>```

Edit: I have implemented it in sql server, convert it into ms sql 2012

```<code>
drop table #asas

create table #asas
(
RN int identity(1,1),
description  varchar(max)
)
insert into #asas values('REIGHT CAR DUMP T.M. "HOWO",
COMMERCIAL NAME A7,
MODEL TOTAL 4 PIECES,
WITHOUT PACKING IDENTIFICATION NUMBER ENGINE NUMBER 191007018177;
TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 3)
VIN: LZZ5DYSD5KA545780;
CHASSIS NUMBER LZZ5DYSD5KA545780;
ENGINE NUMBER 191007018247;
TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 4)
VIN: LZZ5DYSD2KA545784; CHASSIS NUMBER LZZ5DYSD2KA545784; ENGINE NUMBER 191007018137; TRANSMISSION NUMBER NO; BRIDGE ROOMS ARE NOT AVAILABLE FREIGHT VEHICLE –
VIN: LZZ5DYSD2KA545700;'),
('sddddddddddddddddddddddddddddddVIN: LZZ5DYSD2KA545700;sddddddddddVIN: LZZ5DYSD2KA543300;oooooooooVIN: LZZ5DYSD2KA544400;iuiuiuiuiuiuVIN: LZZ5DYSD2KA555700;'),
('sssdsdsdsddddddddVIN: LZZ5DYSD2KA545700;sddddd323232dddddVIN: LZZ5DYSD2KA543300;oooooooooVIN: LZZ5DYSD2KA544400;iuiuiuiuiuiuVIN: LZZ5DYSD2KA555700;')

drop table #table
create table #table
(
RN int identity (1,1),
result varchar(max)
)

--drop table #table
declare @first int,@newString varchar(max),@v1  varchar(max),@originalString varchar(max),
@initcount int=1,@count int
select @count=count(*) from #asas

while(@initcount<=@count)
Begin
insert into #table values('')
set @originalString=''
select @originalString=[description] from #asas where RN=@initcount

    while(PATINDEX('%VIN%',@originalString)>0)
    begin

    select @first= PATINDEX('%VIN%',@originalString)

    --select SUBSTRING(@originalString,PATINDEX('%VIN%',@originalString),22) as result

    select @v1=SUBSTRING(@originalString,PATINDEX('%VIN%',@originalString),22)

    update #table set result=result+', '+@v1 where RN=@initcount

    select @originalString=SUBSTRING(@originalString,PATINDEX('%VIN%',@originalString)+22,len(@originalString))

    end

Set @initcount=@initcount+1
End
select * from #table

</code>```

Body:
Good day, I've got a column with text in my table, but i need to export words 17 letters long only in it.

I tried to use

where description like '%_%_%_%_%_%_%_%_%_%_%_%_%_%_%'

but my query newer  completes.

This is an example of text cell

REIGHT CAR DUMP T.M. "HOWO", COMMERCIAL NAME A7, MODEL TOTAL 4 PIECES,
  WITHOUT PACKING IDENTIFICATION NUMBER ENGINE NUMBER 191007018177;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 3) VIN: LZZ5DYSD5KA545780;
  CHASSIS NUMBER LZZ5DYSD5KA545780; ENGINE NUMBER 191007018247;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 4) VIN: LZZ5DYSD2KA545784;
  CHASSIS NUMBER LZZ5DYSD2KA545784; ENGINE NUMBER 191007018137;
  TRANSMISSION NUMBER NO; BRIDGE ROOMS ARE NOT AVAILABLE FREIGHT VEHICLE
  –

I am using Microsoft SQL management studio

Body:
If you are using sql server

where LEN(description) = 17

Edit: I have implemented it in sql server, convert it into ms sql 2012

drop table #asas

create table #asas
(
RN int identity(1,1),
description  varchar(max)
)
insert into #asas values('REIGHT CAR DUMP T.M. "HOWO",
COMMERCIAL NAME A7,
MODEL TOTAL 4 PIECES,
WITHOUT PACKING IDENTIFICATION NUMBER ENGINE NUMBER 191007018177;
TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 3)
VIN: LZZ5DYSD5KA545780;
CHASSIS NUMBER LZZ5DYSD5KA545780;
ENGINE NUMBER 191007018247;
TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 4)
VIN: LZZ5DYSD2KA545784; CHASSIS NUMBER LZZ5DYSD2KA545784; ENGINE NUMBER 191007018137; TRANSMISSION NUMBER NO; BRIDGE ROOMS ARE NOT AVAILABLE FREIGHT VEHICLE –
VIN: LZZ5DYSD2KA545700;'),
('sddddddddddddddddddddddddddddddVIN: LZZ5DYSD2KA545700;sddddddddddVIN: LZZ5DYSD2KA543300;oooooooooVIN: LZZ5DYSD2KA544400;iuiuiuiuiuiuVIN: LZZ5DYSD2KA555700;'),
('sssdsdsdsddddddddVIN: LZZ5DYSD2KA545700;sddddd323232dddddVIN: LZZ5DYSD2KA543300;oooooooooVIN: LZZ5DYSD2KA544400;iuiuiuiuiuiuVIN: LZZ5DYSD2KA555700;')

drop table #table
create table #table
(
RN int identity (1,1),
result varchar(max)
)

--drop table #table
declare @first int,@newString varchar(max),@v1  varchar(max),@originalString varchar(max),
@initcount int=1,@count int
select @count=count(*) from #asas

while(@initcount<=@count)
Begin
insert into #table values('')
set @originalString=''
select @originalString=[description] from #asas where RN=@initcount

    while(PATINDEX('%VIN%',@originalString)>0)
    begin

    select @first= PATINDEX('%VIN%',@originalString)

    --select SUBSTRING(@originalString,PATINDEX('%VIN%',@originalString),22) as result

    select @v1=SUBSTRING(@originalString,PATINDEX('%VIN%',@originalString),22)

    update #table set result=result+', '+@v1 where RN=@initcount

    select @originalString=SUBSTRING(@originalString,PATINDEX('%VIN%',@originalString)+22,len(@originalString))

    end

Set @initcount=@initcount+1
End
select * from #table


问:
How to change Strapi link inside a description to HTML link tag
I'm creating a simple blog post project and when I put a link inside a description or body of the article it is created like this [text](#).

When requesting the said article using axios.get in ReactJS and console logging the response gets the [text](#).

How to change the [text](#) to text

答: You will need to use a Markdown to HTML library to convert it.</p>


问:
div with image is not showing in d-flex flex-column
The structure is:

```<code><div className="d-flex flex-column">
  <div>
     Text
  </div>
  <div style={{ backgroundImage: 'url(...)' }}>
  </div>
</div>
</code>```

Url is working. Div exists, but image not showing
When I use flex-row it works

答:
add two more styles
background-size: contain;background-repeat: no-repeat;

     Text

```

Body:
The structure is:

     Text

Url is working. Div exists, but image not showing
When I use flex-row it works

Body:
add two more styles
background-size: contain;background-repeat: no-repeat;

<div class="d-flex flex-column">
  <div>
     Text
  </div>
  <div style="background: url(https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png);background-size: contain;background-repeat: no-repeat;">
  <br><br><br><br>
  </div>
</div>


问:
npm 404 Not found, well known package
Trying to install 7zip-bin package using npm, bring this error:

```<code>npm ERR! code E404
npm ERR! 404 Not Found: 7zip-bin@5.0.3

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/user/.npm/_logs/2020-02-11T22_06_51_357Z-debug.log
</code>```

In the log file I see this output:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'install',
1 verbose cli   '-g',
1 verbose cli   '7zip-bin@5.0.3' ]
2 info using npm@6.4.1
3 info using node@v8.15.0
4 verbose npm-session 57413e14b663097a
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 404 https://registry.npmjs.org/7zip-bin 522ms
8 silly fetchPackageMetaData error for 7zip-bin@5.0.3 404 Not Found: 7zip-bin@5.0.3
9 timing stage:rollbackFailedOptional Completed in 0ms
10 timing stage:runTopLevelLifecycles Completed in 745ms
11 verbose stack Error: 404 Not Found: 7zip-bin@5.0.3
11 verbose stack     at fetch.then.res (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/fetch.js:42:19)
11 verbose stack     at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
11 verbose stack     at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31)
11 verbose stack     at Promise._settlePromise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18)
11 verbose stack     at Promise._settlePromise0 (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
11 verbose stack     at Promise._settlePromises (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
11 verbose stack     at Async._drainQueue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:16)
11 verbose stack     at Async._drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143:10)
11 verbose stack     at Immediate.Async.drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
11 verbose stack     at runCallback (timers.js:810:20)
11 verbose stack     at tryOnImmediate (timers.js:768:5)
11 verbose stack     at processImmediate [as _immediateCallback] (timers.js:745:5)
12 verbose cwd /Users/user/Projects/fotomaster.com/mosaicpresentation
13 verbose Darwin 18.7.0
14 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "7zip-bin"
15 verbose node v8.15.0
16 verbose npm  v6.4.1
17 error code E404
18 error 404 Not Found: 7zip-bin@5.0.3
19 verbose exit [ 1, true ]
</code>```

I know I had this package installed already and didn't do anything to uninstall it.
What do I miss?

答:
The other solutions didn't work for me

For me, the issue was being on an outdated version on npm (6.4.1)

Updating to 6.13.4 fixed it

Title: npm 404 Not found, well known package

Body:
Trying to install 7zip-bin package using npm, bring this error:

npm ERR! code E404
npm ERR! 404 Not Found: 7zip-bin@5.0.3

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/user/.npm/_logs/2020-02-11T22_06_51_357Z-debug.log

In the log file I see this output:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'install',
1 verbose cli   '-g',
1 verbose cli   '7zip-bin@5.0.3' ]
2 info using npm@6.4.1
3 info using node@v8.15.0
4 verbose npm-session 57413e14b663097a
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 404 https://registry.npmjs.org/7zip-bin 522ms
8 silly fetchPackageMetaData error for 7zip-bin@5.0.3 404 Not Found: 7zip-bin@5.0.3
9 timing stage:rollbackFailedOptional Completed in 0ms
10 timing stage:runTopLevelLifecycles Completed in 745ms
11 verbose stack Error: 404 Not Found: 7zip-bin@5.0.3
11 verbose stack     at fetch.then.res (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/fetch.js:42:19)
11 verbose stack     at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
11 verbose stack     at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31)
11 verbose stack     at Promise._settlePromise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18)
11 verbose stack     at Promise._settlePromise0 (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
11 verbose stack     at Promise._settlePromises (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
11 verbose stack     at Async._drainQueue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:16)
11 verbose stack     at Async._drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143:10)
11 verbose stack     at Immediate.Async.drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
11 verbose stack     at runCallback (timers.js:810:20)
11 verbose stack     at tryOnImmediate (timers.js:768:5)
11 verbose stack     at processImmediate [as _immediateCallback] (timers.js:745:5)
12 verbose cwd /Users/user/Projects/fotomaster.com/mosaicpresentation
13 verbose Darwin 18.7.0
14 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "7zip-bin"
15 verbose node v8.15.0
16 verbose npm  v6.4.1
17 error code E404
18 error 404 Not Found: 7zip-bin@5.0.3
19 verbose exit [ 1, true ]

I know I had this package installed already and didn't do anything to uninstall it.
What do I miss?


问:
How do I extract a certain amount of lines after a pattern in perl?
Lets say I have a text file:

```<code>Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10
</code>```

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

```<code>Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9
</code>```

So far all I have is code to find the target and print it out:

```<code>use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}
</code>```

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

答:
A basic way is to use a flag and a counter, for when to start and how much to print. One way:

```<code>use warnings;
use strict;

my $how_many = 3;

my $to_print = 0;
while (<>) {
    $to_print = 1+$how_many  if /Target\s+\S+/;

    print if $to_print-- > 0;
}
</code>```

This uses one variable to control operation, set to the number of lines to print (plus one) whenever the "trigger" is seen and then counted down with each print.  It makes some assumptions.

The <> operator
reads lines from files given on the command line (or from STDIN) so run the script by passing filenames as arguments when it is invoked.

Body:
Lets say I have a text file:

Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9

So far all I have is code to find the target and print it out:

use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

Body:
A basic way is to use a flag and a counter, for when to start and how much to print. One way:

use warnings;
use strict;

my $how_many = 3;

my $to_print = 0;
while (<>) {
    $to_print = 1+$how_many  if /Target\s+\S+/;

    print if $to_print-- > 0;
}

This uses one variable to control operation, set to the number of lines to print (plus one) whenever the "trigger" is seen and then counted down with each print.  It makes some assumptions.

The <> operator
reads lines from files given on the command line (or from STDIN) so run the script by passing filenames as arguments when it is invoked.


问:
How to know half-width or full-width character?
I would like to know characters that contain in a String are half-width or full-width.

So I have tested like that:

```<code> /* Checking typing password is valid or not.
 * If length of typing password is less than 6 or
 * is greater than 15 or password is composed by full-width character at least one,
 * it will return false.
 * If it is valid, it will return true.
 * @param cmdl
 * @param oldPassword
 * @return
 */
public boolean isValidNewPassword(String password) {

    if ((password.length() < 6)
            || (password.length() > 15) || (isContainFullWidth(password))) {
        return false;
    }

    return true;
}

/**
 * Checking full-width character is included in string.
 * If full-width character is included in string,
 * it will return true.
 * If is not, it will return false.
 * @param cmdl
 * @return
 */
public boolean isContainFullWidth(String cmdl) {
    boolean isFullWidth = false;
    for (char c : cmdl.toCharArray()) {
        if(!isHalfWidth(c)) {
            isFullWidth = true;
            break;
        }
    }

    return isFullWidth;
}

/**
 * Checking character is half-width or not.
 * Unicode value of half-width range:
 * '\u0000' - '\u00FF'
 * '\uFF61' - '\uFFDC'
 * '\uFFE8' - '\uFFEE'
 * If unicode value of character is within this range,
 * it will be half-width character.
 * @param c
 * @return
 */
public boolean isHalfWidth(char c)
{
    return '\u0000' <= c && c <= '\u00FF'
        || '\uFF61' <= c && c <= '\uFFDC'
        || '\uFFE8' <= c && c <= '\uFFEE' ;
}
</code>```

But it is not OK for all full-width and half width characters.

So, may I know if you have any suggestion with this problem?

Half-width and full-width are used in asian language e.g japanese

There are two type full-width and half-width when writing japanese characters.

half-width characters = ｱﾃﾞﾁｬｴｳｨｵﾌﾟ

full-width characters = アｓｄファｓヂオｐｐ

Thanks a lot!

答:
With number you can use this code</p>

```<code>    /**
 * Full-angle string conversion half-corner string
 * 1, half-width characters are starting from 33 to 126 end
 * 2, the full-width character corresponding to the half-width character is from 65281 start to 65374 end
 * 3, the half corner of the space is 32. The corresponding Full-width space is 12288
 * The relationship between Half-width and Full-width is obvious, except that the character offset is 65248 (65281-33 = 65248).
 *
 * @param fullWidthStr Non-empty full-width string
 * @return Half-angle string
 */
public String halfWidth2FullWidth(String fullWidthStr) {
    if (null == fullWidthStr || fullWidthStr.length() <= 0) {
        return "";
    }
    char[] arr = fullWidthStr.toCharArray();
    for (int i = 0; i < arr.length; ++i) {
        int charValue = (int) arr[i];
        if (charValue >= 33 && charValue <= 126) {
            arr[i] = (char) (charValue + 65248);
        } else if (charValue == 32) {
            arr[i] = (char) 12288;
        }
    }
    return new String(arr);
}
</code>```

Body:
I would like to know characters that contain in a String are half-width or full-width.

So I have tested like that:

 /* Checking typing password is valid or not.
 * If length of typing password is less than 6 or
 * is greater than 15 or password is composed by full-width character at least one,
 * it will return false.
 * If it is valid, it will return true.
 * @param cmdl
 * @param oldPassword
 * @return
 */
public boolean isValidNewPassword(String password) {

    if ((password.length() < 6)
            || (password.length() > 15) || (isContainFullWidth(password))) {
        return false;
    }

    return true;
}

/**
 * Checking full-width character is included in string.
 * If full-width character is included in string,
 * it will return true.
 * If is not, it will return false.
 * @param cmdl
 * @return
 */
public boolean isContainFullWidth(String cmdl) {
    boolean isFullWidth = false;
    for (char c : cmdl.toCharArray()) {
        if(!isHalfWidth(c)) {
            isFullWidth = true;
            break;
        }
    }

    return isFullWidth;
}

/**
 * Checking character is half-width or not.
 * Unicode value of half-width range:
 * '\u0000' - '\u00FF'
 * '\uFF61' - '\uFFDC'
 * '\uFFE8' - '\uFFEE'
 * If unicode value of character is within this range,
 * it will be half-width character.
 * @param c
 * @return
 */
public boolean isHalfWidth(char c)
{
    return '\u0000' <= c && c <= '\u00FF'
        || '\uFF61' <= c && c <= '\uFFDC'
        || '\uFFE8' <= c && c <= '\uFFEE' ;
}

But it is not OK for all full-width and half width characters.

So, may I know if you have any suggestion with this problem?

Half-width and full-width are used in asian language e.g japanese

There are two type full-width and half-width when writing japanese characters.

half-width characters = ｱﾃﾞﾁｬｴｳｨｵﾌﾟ

full-width characters = アｓｄファｓヂオｐｐ

Thanks a lot!

Body:
With number you can use this code

    /**
 * Full-angle string conversion half-corner string
 * 1, half-width characters are starting from 33 to 126 end
 * 2, the full-width character corresponding to the half-width character is from 65281 start to 65374 end
 * 3, the half corner of the space is 32. The corresponding Full-width space is 12288
 * The relationship between Half-width and Full-width is obvious, except that the character offset is 65248 (65281-33 = 65248).
 *
 * @param fullWidthStr Non-empty full-width string
 * @return Half-angle string
 */
public String halfWidth2FullWidth(String fullWidthStr) {
    if (null == fullWidthStr || fullWidthStr.length() <= 0) {
        return "";
    }
    char[] arr = fullWidthStr.toCharArray();
    for (int i = 0; i < arr.length; ++i) {
        int charValue = (int) arr[i];
        if (charValue >= 33 && charValue <= 126) {
            arr[i] = (char) (charValue + 65248);
        } else if (charValue == 32) {
            arr[i] = (char) 12288;
        }
    }
    return new String(arr);
}


问:
Docker build fails with error: failed to register layer: re-exec error: exit status 1
We're in the middle of trying to update a bunch of Docker builds from Windows 2016 to Windows 2019 so that we can upgrade our Service Fabric cluster from Windows 2016 to Windows 2019, and also so we can upgrade from .NET Core 2.2 which is end-of-life to .NET Core 3.1 which has LTS support.

Docker images for .NET Core 3.1 are not provided for Windows 2016 which is making the upgrade more difficult. Our current issue is that on the Windows 2019 build nodes, we are seeing about a 33% failure rate of docker builds due to an intermittent error when doing a docker build (thus a docker pull) of:

ERROR: for sdk  failed to register layer: re-exec error: exit
  status 1: output: ProcessUtilityVMImage
  \?\C:\ProgramData\docker\windowsfilter\1ca28cd86a3256aeff525cb4933d34059f2baae2b223e572bc5dc321ed1e3175\UtilityVM:
  Incorrect function. failed to register layer: re-exec error: exit
  status 1: output: ProcessUtilityVMImage
  \?\C:\ProgramData\docker\windowsfilter\1ca28cd86a3256aeff525cb4933d34059f2baae2b223e572bc5dc321ed1e3175\UtilityVM:
  Incorrect function.

答:
This looks like a Windows version specific problem, as similar issue has been reported by many people using Windows 10 1903. After doing some Google search, looks like the problem can be solved by removing some CBFS drivers that certain apllications install on the system.

Following links might be helpful as they report similar issues:

https://github.com/docker/for-win/issues/3884

https://github.com/microsoft/hcsshim/issues/624


问:
How to copy file from local machine to SFTP server using Jenkins pipeline?
I am building a Jenkins Pipeline where my jenkins is installed on my local windows machine. The war is build and stored in my local system. As part of the deployment cycle followed in project where I work, am supposed to copy it to SFTP server to some location. Am not able to figure this out. Can someone please help.</p>

答:
So, what problem? You can use pscp and psftp. This tools are very customizable(options) and light weight. Open source.

http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

Download it and write a bat file to send package to server. Then call this bat file from Jenkins.


问:
How to wrap array into string in laravel
How can i wrap my return array into string in laravel?
Some thing like this

Laravel:

```<code>    $columnDefinitions = array();

    $columnDefinition = new \stdClass();
    $columnDefinition->label = "No";
    $columnDefinition->sortable = true;
    $columnDefinition->thClass = 'width-50';
    $columnDefinition->tdClass = 'text-center';
    //end add custom css
    $columnDefinitions["index_number"] = $columnDefinition;
    return $columnDefinitions;
</code>```

Expected result

```<code>'[{
   apple: {
             label: "No"
             sortable: true
             tdClass: "text-center"
          }
}]'
</code>```

答:
seems like you are trying to make an array of object with an object attribute?

try this:

```<code>    $columnDefinitions = array();

    $columnDefinition = new \stdClass();
    $columnDefinition->label = 'No';
    $columnDefinition->sortable = true;
    $columnDefinition->thClass = 'width-50';
    $columnDefinition->tdClass = 'text-center';

    $appleDefinition = new \stdClass();
    $appleDefinition->apple = $columnDefinition;
    //end add custom css

    $columnDefinitions[] = $appleDefinition;
    return json_encode($columnDefinitions);
</code>```

Body:
How can i wrap my return array into string in laravel?
Some thing like this

Laravel:

    $columnDefinitions = array();

    $columnDefinition = new \stdClass();
    $columnDefinition->label = "No";
    $columnDefinition->sortable = true;
    $columnDefinition->thClass = 'width-50';
    $columnDefinition->tdClass = 'text-center';
    //end add custom css
    $columnDefinitions["index_number"] = $columnDefinition;
    return $columnDefinitions;

Expected result

'[{
   apple: {
             label: "No"
             sortable: true
             tdClass: "text-center"
          }
}]'

Body:
seems like you are trying to make an array of object with an object attribute?

try this:

    $columnDefinitions = array();

    $columnDefinition = new \stdClass();
    $columnDefinition->label = 'No';
    $columnDefinition->sortable = true;
    $columnDefinition->thClass = 'width-50';
    $columnDefinition->tdClass = 'text-center';

    $appleDefinition = new \stdClass();
    $appleDefinition->apple = $columnDefinition;
    //end add custom css

    $columnDefinitions[] = $appleDefinition;
    return json_encode($columnDefinitions);


问:
HTML width 100% goes outside the page
I'm pretty newbie with HTML and CSS. So, I've got a problem with the width of 100%. It appears to go beyond the borders of the browser. Please take a look at the example below! Should I decrease the width per cents a little or is there some flaws in my code that could cause this?

I found some other posts here about the width 100%, but neither of them didn't really help me. Here's the example I made: http://jsfiddle.net/gj53jbz9/

 body{
              font-size: 15px;
              margin: 0px;
              background-color: lightgrey;  }

            #header{
              padding: 30px;
              width: 100%;
              height: 250px;
              background-color: grey;   }

            #name{
              padding: 5px;
              font-size: 25px;
              float: left;  }

            #navbar{
              float: right;
              text-align: right;    }

            #navbar a{
              background-color: black;
              display: inline-block;
              width: 120px;
              text-align: center;
              padding: 10px 0px;
              text-decoration: none;
              color: lightgrey; }

            #title{
              clear: both;
              text-align: center;
              padding-top: 100px;
              font-size: 45px;  }

            #content{
              text-align: center;
              width: 80%;
              margin: 0px auto;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <div id=header>
            <div id=name>Name</div>
            <div id=navbar>
                Link1
                Link2
            </div>
            <div id=title>Insert title here</div>
        </div>
        <div id=content>
            <h3>Age of aggression</h3>
            <p>We drink to our youth, to days come and gone. For the age of aggression is just about done. We'll drive out the Stormcloaks and restore what we own. With our blood and our steel we will take back our home.</p>
            <p>Down with Ulfric! The killer of kings! On the day of your death we will drink and we'll sing. We're the children of Skyrim, and we fight all our lives. And when Sovngarde beckons, every one of us dies! But this land is ours and we'll see it wiped clean. Of the scourge that has sullied our hopes and our dreams!</p>
  </div></code>```

答:
```<code>left: 0px;
right: 0px;
width: auto;
position: relative;
</code>```

Title: HTML width 100% goes outside the page

Body:
I'm pretty newbie with HTML and CSS. So, I've got a problem with the width of 100%. It appears to go beyond the borders of the browser. Please take a look at the example below! Should I decrease the width per cents a little or is there some flaws in my code that could cause this?

I found some other posts here about the width 100%, but neither of them didn't really help me. Here's the example I made: http://jsfiddle.net/gj53jbz9/

 body{
              font-size: 15px;
              margin: 0px;
              background-color: lightgrey;  }

            #header{
              padding: 30px;
              width: 100%;
              height: 250px;
              background-color: grey;   }

            #name{
              padding: 5px;
              font-size: 25px;
              float: left;  }

            #navbar{
              float: right;
              text-align: right;    }

            #navbar a{
              background-color: black;
              display: inline-block;
              width: 120px;
              text-align: center;
              padding: 10px 0px;
              text-decoration: none;
              color: lightgrey; }

            #title{
              clear: both;
              text-align: center;
              padding-top: 100px;
              font-size: 45px;  }

            #content{
              text-align: center;
              width: 80%;
              margin: 0px auto;  }

Name

                Link1
                Link2

Insert title here

Age of aggression

We drink to our youth, to days come and gone. For the age of aggression is just about done. We'll drive out the Stormcloaks and restore what we own. With our blood and our steel we will take back our home.

Down with Ulfric! The killer of kings! On the day of your death we will drink and we'll sing. We're the children of Skyrim, and we fight all our lives. And when Sovngarde beckons, every one of us dies! But this land is ours and we'll see it wiped clean. Of the scourge that has sullied our hopes and our dreams!


问:
Append the specific column in another existing table using SQL QUERY
I know it sounds easy when appending a entire row to new table, but this is different

Question 1, state to combine the Table 1 and Table 2 and keep duplicate value, to create a new table, I have used the following query:

```<code>CREATE TABLE EMP_TBL_3
(
    EMP_ID int,
    Name varchar(255),
    DOJ int
);

INSERT INTO EMP_TBL_3 (EMP_ID, Name, DOJ)
   SELECT * FROM EMP_TBL_1
   UNION ALL
   SELECT * FROM EMP_TBL_2;
</code>```

Results:

Now the problem arise at 2nd question, saying: Take the D.O.B from EMP_BRTH_REC and combine them to EMP_TBL_3:

I have tried this query:

```<code>ALTER TABLE EMP_TBL_3
ADD DOB int;

SELECT * FROM EMP_TBL_3;

SELECT EMP_ID, Name, DOJ, DOB
FROM EMP_TBL_3
UNION ALL
SELECT EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
FROM EMP_BRTH_REC
LEFT JOIN EMP_TBL_3 ON EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;
</code>```

Results:

My desired output is:

How do I do that?

答:
You are twice inserting the records using UNION ALL. I would suggest you to truncate and reload data into Tbl3 as given below:</p>

```<code>ALTER TABLE EMP_TBL_3
ADD DOB int;

TRUNCATE TABLE Emp_Tbl_3;

INSERT INTO Emp_Tbl_3(Emp_Id, Name, DOJ, DOB)
SELECT EMP_TBL_1.EMP_ID, EMP_TBL_1.Name, EMP_TBL_1.DOJ, EMP_BRTH_REC.DOB
from
EMP_BRTH_REC
LEFT JOIN EMP_TBL_1
on EMP_BRTH_REC.EMP_ID = EMP_TBL_1.EMP_ID
UNION ALL
SELECT EMP_TBL_2.EMP_ID, EMP_TBL_2.Name, EMP_TBL_2.DOJ, EMP_BRTH_REC.DOB
from
EMP_BRTH_REC
LEFT JOIN EMP_TBL_2
on EMP_BRTH_REC.EMP_ID = EMP_TBL_2.EMP_ID;
</code>```

Body:
I know it sounds easy when appending a entire row to new table, but this is different

Question 1, state to combine the Table 1 and Table 2 and keep duplicate value, to create a new table, I have used the following query:

CREATE TABLE EMP_TBL_3
(
    EMP_ID int,
    Name varchar(255),
    DOJ int
);

INSERT INTO EMP_TBL_3 (EMP_ID, Name, DOJ)
   SELECT * FROM EMP_TBL_1
   UNION ALL
   SELECT * FROM EMP_TBL_2;

Results:

Now the problem arise at 2nd question, saying: Take the D.O.B from EMP_BRTH_REC and combine them to EMP_TBL_3:

I have tried this query:

ALTER TABLE EMP_TBL_3
ADD DOB int;

SELECT * FROM EMP_TBL_3;

SELECT EMP_ID, Name, DOJ, DOB
FROM EMP_TBL_3
UNION ALL
SELECT EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
FROM EMP_BRTH_REC
LEFT JOIN EMP_TBL_3 ON EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;

Results:

My desired output is:

How do I do that?

Body:
You are twice inserting the records using UNION ALL. I would suggest you to truncate and reload data into Tbl3 as given below:

ALTER TABLE EMP_TBL_3
ADD DOB int;

TRUNCATE TABLE Emp_Tbl_3;

INSERT INTO Emp_Tbl_3(Emp_Id, Name, DOJ, DOB)
SELECT EMP_TBL_1.EMP_ID, EMP_TBL_1.Name, EMP_TBL_1.DOJ, EMP_BRTH_REC.DOB
from
EMP_BRTH_REC
LEFT JOIN EMP_TBL_1
on EMP_BRTH_REC.EMP_ID = EMP_TBL_1.EMP_ID
UNION ALL
SELECT EMP_TBL_2.EMP_ID, EMP_TBL_2.Name, EMP_TBL_2.DOJ, EMP_BRTH_REC.DOB
from
EMP_BRTH_REC
LEFT JOIN EMP_TBL_2
on EMP_BRTH_REC.EMP_ID = EMP_TBL_2.EMP_ID;


问:
How do i use MMX mulH and mulL for two 64 bit integers to get one 128 bit integer
Hello, I'm working on yet another arbitrary precision integer library. I wanted to implement multiplication but I got stuck when _m_pmulhw in <mmintrin.h> just didn't work. there is very little documentation on MMX instructions. When I test it out, it just gives me gibberish when I multiply two UINT64_MAXs.

```<code>uint_fast64_t mulH(const uint_fast64_t &a, const uint_fast64_t &b)  {
    return (uint_fast64_t)_m_pmulhw((__m64)a,(__m64)b);
}
uint_fast64_t mulL(const uint_fast64_t &a, const uint_fast64_t &b)  {
    return (uint_fast64_t)_m_pmullw((__m64)a,(__m64)b);
}
int main() {
    uint64_t a = UINT64_MAX;
    uint64_t b = UINT64_MAX;
    std::cout <<  std::bitset<64>(mulH(a,b)) << std::bitset<64>(mulL(a,b));
}

output: 00000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001
</code>```

I don't know why it's not working i have an A6-4400M APU...

coreinfo's output:MMX             *       Supports MMX instruction set

So I think I can say, it isn't unsupported. If anyone can give me some tips on how to make this work thanks.

Compiler: gcc

IDE: visual studio code

答:
I'm not an expert on this, but according to https://www.felixcloutier.com/x86/pmulhw, these instructions don't do a 64x64->128 multiply; they do four 16x16->32 multiplies.  Note the word "packed" in the description.  Moreover it's a signed multiply.

So your 64-bit UINT64_MAX values are interpreted as four words of 0xffff, which is to say -1.  So you are multiplying -1 by -1, four times.  Of course the numerical answer to each one is 1.  The result of the pmulhw instruction is the high halves of the results (i.e. four words of 0x0000), and pmullw is the low halves (i.e. four words of 0x0001).

Which is exactly what you got, so it seems to me the instructions are working perfectly.

If you want to do an unsigned multiply of two 64-bit integers, the plain old fashioned mul instruction will serve your purpose, and the easiest way to get gcc to generate it is probably by casting the inputs to __uint128_t and multiplying with the usual * operator.

Body:
Hello, I'm working on yet another arbitrary precision integer library. I wanted to implement multiplication but I got stuck when _m_pmulhw in <mmintrin.h> just didn't work. there is very little documentation on MMX instructions. When I test it out, it just gives me gibberish when I multiply two UINT64_MAXs.

uint_fast64_t mulH(const uint_fast64_t &a, const uint_fast64_t &b)  {
    return (uint_fast64_t)_m_pmulhw((__m64)a,(__m64)b);
}
uint_fast64_t mulL(const uint_fast64_t &a, const uint_fast64_t &b)  {
    return (uint_fast64_t)_m_pmullw((__m64)a,(__m64)b);
}
int main() {
    uint64_t a = UINT64_MAX;
    uint64_t b = UINT64_MAX;
    std::cout <<  std::bitset<64>(mulH(a,b)) << std::bitset<64>(mulL(a,b));
}

output: 00000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001

I don't know why it's not working i have an A6-4400M APU...

coreinfo's output:MMX             *       Supports MMX instruction set

So I think I can say, it isn't unsupported. If anyone can give me some tips on how to make this work thanks.

Compiler: gcc

IDE: visual studio code


问:
CORS error working only for one controller
I am working on a dotnet core web api.

My API is hosted on localhost:44366
and My client side application is hosted at http://127.0.0.1:5501/ (using vs code live server)

I am making two POST request using a submit button
Previously I faced the following issue when I was making one POST request:

```<code>Access to XMLHttpRequest at 'https://localhost:44366/api/surveycreatoroptions' from origin
'http://127.0.0.1:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.
</code>```

I have tried the [EnableCors("AllowMyOrigin")] method on both the controllers.

It works the for the first request but not for the second request (giving the same error)

This is what I have used for Enabling CORS

```<code> services.AddCors(options =>
            {
            options.AddPolicy("AllowMyOrigin",
             builder => builder.WithOrigins("http://127.0.0.1:5501").AllowAnyMethod().AllowAnyHeader())
             ;
            });

        }
</code>```

How can I make it work for both the requests.

答:
Try this code to see if it work for you</p>

```<code>public void ConfigureServices(IServiceCollection services)
{
      services.AddCors();
      services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(
        options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
    );

    app.UseMvc();
}
</code>```

Body:
I am working on a dotnet core web api.

My API is hosted on localhost:44366
and My client side application is hosted at http://127.0.0.1:5501/ (using vs code live server)

I am making two POST request using a submit button
Previously I faced the following issue when I was making one POST request:

Access to XMLHttpRequest at 'https://localhost:44366/api/surveycreatoroptions' from origin
'http://127.0.0.1:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.

I have tried the [EnableCors("AllowMyOrigin")] method on both the controllers.

It works the for the first request but not for the second request (giving the same error)

This is what I have used for Enabling CORS

 services.AddCors(options =>
            {
            options.AddPolicy("AllowMyOrigin",
             builder => builder.WithOrigins("http://127.0.0.1:5501").AllowAnyMethod().AllowAnyHeader())
             ;
            });

        }

How can I make it work for both the requests.

Body:
Try this code to see if it work for you

public void ConfigureServices(IServiceCollection services)
{
      services.AddCors();
      services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(
        options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
    );

    app.UseMvc();
}


问:
rewrite a kdb script in DolphinDB database
I am trying to rewrite a kdb script in DolphinDB.

Let me first explain what I need to do. If a signal is above a threshold T1, we establish a long position in the security. We don't want to close the position as soon as the signal dips below T1, so we give it a cushion: only when the signal dips below T10 that is less than T1 do we close the position.

On the other side, if the signal is below a threshold T2, we establish a short position. Only when the signal moves above T20>T2 do we close the position.

T1>T10>T20>T2.

Basically I need the following vector:

```<code> - if signal>T1, return 1. Subsequent elements are 1 until when signal<T10;
 - if signal<T2, return -1. Subsequent elements are -1 until when signal>T20;
 - 0 otherwise
</code>```

The kdb script for the task above is:

```<code>0h^fills(-).(0N 1h)[(signal>T1;signal<T2)]^'(0N 0h)[(signal<T10;signal>T20)]

</code>```

Does anyone how to rewrite it in DolphinDB?

答:
DolphinDB 1.01 introduced a new feature, JIT. One can achieve big performance improvement simply by adding a notation @jit in front of the function definition. Moreover, one can use for-loop to solve the above problem, much easier than the vectorized solution.

```<code>@jit
def calculate_with_jit(signal, n, t1, t10, t20, t2) {
  cur = 0
  idx = 0
  output = array(INT, n, n)
  for (s in signal) {
    if(s > t1) {           // (t1, inf)
      cur = 1
    } else if(s >= t10) {  // [t10, t1]
      if(cur == -1) cur = 0
    } else if(s > t20) {   // [t20, t10)
      cur = 0
    } else if(s >= t2) {   // [t2, t20]
      if(cur == 1) cur = 0
    } else {               // (-inf, t2)
      cur = -1
    }
    output[idx] = cur
    idx += 1
  }
  return output
}
</code>```

On my machine, the jit version takes only 170ms for 10-million-long signal while the vectorized version takes 410ms.

Please refer the jit tutorial (https://github.com/dolphindb/Tutorials_EN/blob/master/jit.md) for more details

Body:
I am trying to rewrite a kdb script in DolphinDB.

Let me first explain what I need to do. If a signal is above a threshold T1, we establish a long position in the security. We don't want to close the position as soon as the signal dips below T1, so we give it a cushion: only when the signal dips below T10 that is less than T1 do we close the position.

On the other side, if the signal is below a threshold T2, we establish a short position. Only when the signal moves above T20>T2 do we close the position.

T1>T10>T20>T2.

Basically I need the following vector:

 - if signal>T1, return 1. Subsequent elements are 1 until when signal<T10;
 - if signal<T2, return -1. Subsequent elements are -1 until when signal>T20;
 - 0 otherwise

The kdb script for the task above is:

0h^fills(-).(0N 1h)[(signal>T1;signal<T2)]^'(0N 0h)[(signal<T10;signal>T20)]

Does anyone how to rewrite it in DolphinDB?

Body:
DolphinDB 1.01 introduced a new feature, JIT. One can achieve big performance improvement simply by adding a notation @jit in front of the function definition. Moreover, one can use for-loop to solve the above problem, much easier than the vectorized solution.

@jit
def calculate_with_jit(signal, n, t1, t10, t20, t2) {
  cur = 0
  idx = 0
  output = array(INT, n, n)
  for (s in signal) {
    if(s > t1) {           // (t1, inf)
      cur = 1
    } else if(s >= t10) {  // [t10, t1]
      if(cur == -1) cur = 0
    } else if(s > t20) {   // [t20, t10)
      cur = 0
    } else if(s >= t2) {   // [t2, t20]
      if(cur == 1) cur = 0
    } else {               // (-inf, t2)
      cur = -1
    }
    output[idx] = cur
    idx += 1
  }
  return output
}

On my machine, the jit version takes only 170ms for 10-million-long signal while the vectorized version takes 410ms.

Please refer the jit tutorial (https://github.com/dolphindb/Tutorials_EN/blob/master/jit.md) for more details


问:
0 in integer part of a decimal variable is not displaying
Below is the code to display a decimal(18,2) value from database:

```<code>document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + response + " US$/kg";
</code>```

So it displayed as:

```<code>Total Knitting Cost : .55 US$/kg
</code>```

How to make it display 0.55 US$/kg?

Update - response is from Ajax:

```<code>function fetch_select(val, obj)
{
    $.ajax({
            type:'post',
            url: 'get.php',
            data: {
                    get_option:val, "get_object":obj.id
                  },
            success: function (response)
                {
                    switch (obj.id) {
                        case "Yarn":
                            //code to process yarndivid here
                            document.getElementById(yarndivid).innerHTML=response;

                            break;

                        case "Knitting":
                            document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + parseFloat(response) + " US$/kg";
                        break;

                        case "Dyestuff":
                        break;

                    }
                }

        });
}
</code>```

get.php:

```<code><?php
 if(isset($_POST['get_option']) or isset($_POST['get_object']))
{

 $connectionInfo = array("Database"=>$db, "UID"=>$user, "PWD"=>$pass);
 $dbhandle = sqlsrv_connect($server,$connectionInfo) or die("Couldn’t connect to SQL Server on $server");
 if( $dbhandle === false )
    {
    die( print_r( sqlsrv_errors(), true));
    }

 $id = $_POST['get_option'];
 $objid = $_POST['get_object'];
 $tblname = $sql = "";

 switch ($objid) {
    case "Yarn":
        $tblname = "tblYarnFilament";
        break;
    case "Knitting":
        $tblname = "tblKnitting";
        break;
    case "Coloration":
        $tblname = "tblDyestuff";
        break;
    }

 $sql = "select price2 from ".$tblname." where id = '$id'";

 $find=sqlsrv_query($dbhandle, $sql);

    while($row=sqlsrv_fetch_array($find))
    {
        echo $row['price2'];
    }
}
?>

</code>```

答:
JavaScript would never display a number as .55. So response is not a number (and is, presumably, a string). Make it a number:

```<code>document.getElementById("knittingcost").innerHTML =
    "Total Knitting Cost : " + parseFloat(response) + " US$/kg";
</code>```

Body:
Below is the code to display a decimal(18,2) value from database:

document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + response + " US$/kg";

So it displayed as:

Total Knitting Cost : .55 US$/kg

How to make it display 0.55 US$/kg?

Update - response is from Ajax:

function fetch_select(val, obj)
{
    $.ajax({
            type:'post',
            url: 'get.php',
            data: {
                    get_option:val, "get_object":obj.id
                  },
            success: function (response)
                {
                    switch (obj.id) {
                        case "Yarn":
                            //code to process yarndivid here
                            document.getElementById(yarndivid).innerHTML=response;

                            break;

                        case "Knitting":
                            document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + parseFloat(response) + " US$/kg";
                        break;

                        case "Dyestuff":
                        break;

                    }
                }

        });
}

get.php:

<?php
 if(isset($_POST['get_option']) or isset($_POST['get_object']))
{

 $connectionInfo = array("Database"=>$db, "UID"=>$user, "PWD"=>$pass);
 $dbhandle = sqlsrv_connect($server,$connectionInfo) or die("Couldn’t connect to SQL Server on $server");
 if( $dbhandle === false )
    {
    die( print_r( sqlsrv_errors(), true));
    }

 $id = $_POST['get_option'];
 $objid = $_POST['get_object'];
 $tblname = $sql = "";

 switch ($objid) {
    case "Yarn":
        $tblname = "tblYarnFilament";
        break;
    case "Knitting":
        $tblname = "tblKnitting";
        break;
    case "Coloration":
        $tblname = "tblDyestuff";
        break;
    }

 $sql = "select price2 from ".$tblname." where id = '$id'";

 $find=sqlsrv_query($dbhandle, $sql);

    while($row=sqlsrv_fetch_array($find))
    {
        echo $row['price2'];
    }
}
?>

Body:
JavaScript would never display a number as .55. So response is not a number (and is, presumably, a string). Make it a number:

document.getElementById("knittingcost").innerHTML =
    "Total Knitting Cost : " + parseFloat(response) + " US$/kg";


问:
Pointer as parameter in Linux kernel code

    Recently, I have read the linux kernel code to see how the code looks like. I understands only the basic of pointers.

So, i came across this function declaration:-

```<code>kernel_write(struct file *file, const void *buf, size_t count,loff_t *pos)
</code>```

What does struct file *file imply?

Based on my understanding, struct file *file means that you pass the pointer that points to the memory blocks that contains multiple file structs?

Here is a diagram to visualize my understanding :-

Is my understanding accurate or i am actually misguided?

答: No, that's not correct. In this context, that pointer points to exactly one struct file. Advancing it and trying to read a second one would be Undefined Behavior, and that's especially bad when it happens in the kernel.

Body:
Recently, I have read the linux kernel code to see how the code looks like. I understands only the basic of pointers.

So, i came across this function declaration:-

kernel_write(struct file *file, const void *buf, size_t count,loff_t *pos)

What does struct file *file imply?

Based on my understanding, struct file *file means that you pass the pointer that points to the memory blocks that contains multiple file structs?

Here is a diagram to visualize my understanding :-

Is my understanding accurate or i am actually misguided?


问:
Python win32com.client - Email only goes out when I have outlook open
I currently have a python script which I'm trying to automate to send an email out via my account. I'm using the win23com.client library to do this, and really briefly this is what my code is doing:

```<code>mail = outlook.CreateItem(0)
mail.To = (list of emails)
#mail.cc = x
mail.Subject = x
mail.HTMLBody = (python object with HTML code)
mail.Send()
</code>```

When I run the above with Outlook closed, I get the following error code:

```<code>com_error: (-2147467260, 'Operation aborted', None, None)
</code>```

However if I run it with Outlook open it sends it out fine through my email account. I'm guessing it must have an issue in authenticating my account with outlook closed, but my colleagues don't seem to be having the same issue on the same network.

Any ideas?

答:
```<code>import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application")
message = 'Hello'
mail = outlook.CreateItem(0)
mail.To = 'email'
mail.Subject = 'This is a test'
mail.HTMLBody = message
mail.Send()
</code>```

Check this. It works for me even with Outlook closed.

Body:
I currently have a python script which I'm trying to automate to send an email out via my account. I'm using the win23com.client library to do this, and really briefly this is what my code is doing:

mail = outlook.CreateItem(0)
mail.To = (list of emails)
#mail.cc = x
mail.Subject = x
mail.HTMLBody = (python object with HTML code)
mail.Send()

When I run the above with Outlook closed, I get the following error code:

com_error: (-2147467260, 'Operation aborted', None, None)

However if I run it with Outlook open it sends it out fine through my email account. I'm guessing it must have an issue in authenticating my account with outlook closed, but my colleagues don't seem to be having the same issue on the same network.

Any ideas?

Body:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application")
message = 'Hello'
mail = outlook.CreateItem(0)
mail.To = 'email'
mail.Subject = 'This is a test'
mail.HTMLBody = message
mail.Send()

Check this. It works for me even with Outlook closed.


问:
Fading one div into another: Make more stable, remove white pause, multiple fades
I have a test setup where the thumbnail div fades into another div, there's a couple of problems with it though.

How can I remove the white pause? At the moment it fades one div out to white then fades in the second div. How can I make it fade from one div to the other without it fading to white?

It's a little unstable, if you hover over quickly and out the second div appears below the original. How can I make it a bit more stable?

I'm going have multiple thumbnails with different images and text in each one, how can I setup the grid to include multiple boxes without them all fading in/out at once (i.e separately).

Here's the code:

Javacript:

```<code><script type="text/javascript">

$(document).ready(function(){
            $(".phase-2").hide();
        });

$(function(){
$('.grid-box').hover(
        function(){
            $('.grid-box .phase-1').fadeOut(300, function(){
                $('.grid-box .phase-2').fadeIn(300);
            });
        },
        function(){
            $('.grid-box .phase-2').fadeOut(300, function(){
                $('.grid-box .phase-1').fadeIn(300);
            });
        }
        );
});
</script>
</code>```

HTML:

```<code><div class="grid-box">
<div class="phase-1">
       <img class="grid-image" src="http://teamworksdesign.com/v2/wp-content/themes/default/images/dtr.jpg" alt="" height="152" width="210" />
   <div class="grid-heading">
        <h2>DTR Medical</h2>
        <h3>Branding, Web, Print</h3>
    </div>
</div>
<div class="phase-2">
    <div class="grid-info">
        <h4>Probeything 2000</h4>
        <p>Marketing unglamorous single-use medical intruments is not simple. We helped Neurosign increasetheir sales by 25% and increasemarket awareness.</p>
    </div>
    <div class="grid-heading-hover">
        <h2>DTR Medical</h2>
        <h3>Branding, Web, Print</h3>
    </div>
</div>
</code>```

答:
1) Rather than do the fadeIn of the hover item on the callback, do it immediately. This will prevent the white background showing through:

```<code>$('.grid-box .phase-1').fadeOut(300);
$('.grid-box .phase-2').fadeIn(300);
</code>```

2) The easiest way to do this is to specify a size on the thumbnail container and the add overflow: hidden; to it.

3) Finally the following code will make sure only the elements contained within the hovered-over div will be affected:

```<code>$(function(){
    $('.grid-box').hover(
        function(){
            $('.phase-1', this).fadeOut(300);
            $('.phase-2', this).fadeIn(300);
        },
        function(){
            $('.phase-2', this).fadeOut(300)
            $('.phase-1', this).fadeIn(300);
        }
    );
});
</code>```

Body:
I have a test setup where the thumbnail div fades into another div, there's a couple of problems with it though.

How can I remove the white pause? At the moment it fades one div out to white then fades in the second div. How can I make it fade from one div to the other without it fading to white?

It's a little unstable, if you hover over quickly and out the second div appears below the original. How can I make it a bit more stable?

I'm going have multiple thumbnails with different images and text in each one, how can I setup the grid to include multiple boxes without them all fading in/out at once (i.e separately).

Here's the code:

Javacript:

HTML:

DTR Medical

Branding, Web, Print

Probeything 2000

Marketing unglamorous single-use medical intruments is not simple. We helped Neurosign increasetheir sales by 25% and increasemarket awareness.

DTR Medical

Branding, Web, Print

Body:
1) Rather than do the fadeIn of the hover item on the callback, do it immediately. This will prevent the white background showing through:

$('.grid-box .phase-1').fadeOut(300);
$('.grid-box .phase-2').fadeIn(300);

2) The easiest way to do this is to specify a size on the thumbnail container and the add overflow: hidden; to it.

3) Finally the following code will make sure only the elements contained within the hovered-over div will be affected:

$(function(){
    $('.grid-box').hover(
        function(){
            $('.phase-1', this).fadeOut(300);
            $('.phase-2', this).fadeIn(300);
        },
        function(){
            $('.phase-2', this).fadeOut(300)
            $('.phase-1', this).fadeIn(300);
        }
    );
});


答:
```<code>document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + parseFloat(response.toString()).toFixed(2)  + " US$/kg";
</code>```

convert it into a string (.toString()) and then fix it into 2 decimal (.toFixed(2)) places will solved the issues.

Title: 0 in integer part of a decimal variable is not displaying

Body:
document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + parseFloat(response.toString()).toFixed(2)  + " US$/kg";

convert it into a string (.toString()) and then fix it into 2 decimal (.toFixed(2)) places will solved the issues.


问:
Android - Fragments or custom views? Which should I be using?
I am trying to create a layout in an activity that will look different in landscape and portrait, however it will contain the same sections, just in different places on the screen.

Most examples I find on fragments is always the list and detail, which is not what I'm looking at.

In my example I have, amongst others,

a scrolling image section (carousel)

a page title with some brief details

a carousel of thumbnails

two buttons

full details of the page

Now in the landscape layout, the image section will always be on the left side with down the right side, the page title, carousel of thumbs, two buttons and full details.
In the Portrait the title will appear at top, with image carousel beneath, then thumbs, then buttons etc.

The way it works in my head, is that each section should be a fragment, and then depending on the layout file in the respective res/layout folder corresponding to land/port, the fragments are arranged accordingly. But I'm also thinking is each section a whole fragment? Or could it be a separate view that get's loaded in, but just in a different order depending on the screen orientation.

I hope that made sense?

Does anyone have any good tutorials that explain exactly when you should and shouldn't use fragments. All the usual suspects just list the list/detail example, which is not applicable in my case.

tl;dr Can I use fragments as modules/blocks in various layouts or should I just create other layouts and display them inside the main layouts.

答: Fragments can be used to have split screen and to store previous state unlike views. It is difficult to manage back button with views</p>


问:
Idiomatic way of performance evaluation?
I am evaluating a network+rendering workload for my project.

The program continuously runs a main loop:

```<code>while (true) {
   doSomething()
   drawSomething()
   doSomething2()
   sendSomething()
}
</code>```

The main loop runs more than 60 times per second.

I want to see the performance breakdown, how much time each procedure takes.

My concern is that if I print the time interval for every entrance and exit of each procedure,

It would incur huge performance overhead.

I am curious what is an idiomatic way of measuring the performance.

Printing of logging is good enough?

答:
Generally: For repeated short things, you can just time the whole repeat loop.  (But microbenchmarking is hard; easy to distort results unless you understand the implications of doing that; for very short things, throughput and latency are different, so measure both separately by making one iteration use the result of the previous or not.  Also beware that branch prediction and caching can make something look fast in a microbenchmark when it would actually be costly if done one at a time between other work in a larger program.
e.g. loop unrolling and lookup tables often look good because there's no pressure on I-cache or D-cache from anything else.)

Or if you insist on timing each separate iteration, record the results in an array and print later; you don't want to invoke heavy-weight printing code inside your loop.

This question is way too broad to say anything more specific.

Many languages have benchmarking packages that will help you write microbenchmarks of a single function.  Use them.  e.g. for Java, JMH makes sure the function under test is warmed up and fully optimized by the JIT, and all that jazz, before doing timed runs.  And runs it for a specified interval, counting how many iterations it completes.  See How do I write a correct micro-benchmark in Java? for that and more.

Beware common microbenchmark pitfalls

Failure to warm up code / data caches and stuff: page faults within the timed region for touching new memory, or code / data cache misses, that wouldn't be part of normal operation.  (Example of noticing this effect: Performance: memset; or example of a wrong conclusion based on this mistake)

Never-written memory (obtained fresh from the kernel) gets all its pages copy-on-write mapped to the same system-wide physical page (4K or 2M) of zeros if you read without writing, at least on Linux. So you can get cache hits but TLB misses.  e.g. A large allocation from new / calloc / malloc, or a zero-initialized array in static storage in .bss.  Use a non-zero initializer or memset.

Failure to give the CPU time to ramp up to max turbo: modern CPUs clock down to idle speeds to save power, only clocking up after a few milliseconds.  (Or longer depending on the OS / HW).

related: on modern x86, RDTSC counts reference cycles, not core clock cycles, so it's subject to the same CPU-frequency variation effects as wall-clock time.

Most integer and FP arithmetic asm instructions (except divide and square root which are already slower than others) have performance (latency and throughput) that doesn't depend on the actual data.  Except for subnormal aka denormal floating point being very slow, and in some cases (e.g. legacy x87 but not SSE2) also producing NaN or Inf can be slow.

On modern CPUs with out-of-order execution, some things are too short to truly time meaningfully, see also this.  Performance of a tiny block of assembly language (e.g. generated by a compiler for one function) can't be characterized by a single number, even if it doesn't branch or access memory (so no chance of mispredict or cache miss).  It has latency from inputs to outputs, but different throughput if run repeatedly with independent inputs is higher.  e.g. an add instruction on a Skylake CPU has 4/clock throughput, but 1 cycle latency.  So dummy = foo(x) can be 4x faster than x = foo(x); in a loop.  Floating-point instructions have higher latency than integer, so it's often a bigger deal.  Memory access is also pipelined on most CPUs, so looping over an array (address for next load easy to calculate) is often much faster than walking a linked list (address for next load isn't available until the previous load completes).

Obviously performance can differ between CPUs; in the big picture usually it's rare for version A to be faster on Intel, version B to be faster on AMD, but that can easily happen in the small scale.  When reporting / recording benchmark numbers, always note what CPU you tested on.

Related to the above and below points: you can't "benchmark the * operator" in C in general, for example.  Some use-cases for it will compile very differently from others, e.g. tmp = foo * i; in a loop can often turn into tmp += foo (strength reduction), or if the multiplier is a constant power of 2 the compiler will just use a shift.  The same operator in the source can compile to very different instructions, depending on surrounding code.

You need to compile with optimization enabled, but you also need to stop the compiler from optimizing away the work, or hoisting it out of a loop.  Make sure you use the result (e.g. print it or store it to a volatile) so the compiler has to produce it.  For an array, volatile double sink = output[argc]; is a useful trick: the compiler doesn't know the value of argc so it has to generate the whole array, but you don't need to read the whole array or even call an RNG function.  (Unless the compiler aggressively transforms to only calculate the one output selected by argc, but that tends not to be a problem in practice.)

For inputs, use a random number or argc or something instead of a compile-time constant so your compiler can't do constant-propagation for things that won't be constants in your real use-case.  In C you can sometimes use inline asm or volatile for this, e.g. the stuff this question is asking about.  A good benchmarking package like Google Benchmark will include functions for this.

If the real use-case for a function lets it inline into callers where some inputs are constant, or the operations can be optimized into other work, it's not very useful to benchmark it on its own.

Big complicated functions with special handling for lots of special cases can look fast in a microbenchmark when you run them repeatedly, especially with the same input every time.  In real life use-cases, branch prediction often won't be primed for that function with that input.  Also, a massively unrolled loop can look good in a microbenchmark, but in real life it slows everything else down with its big instruction-cache footprint leading to eviction of other code.

Related to that last point: Don't tune only for huge inputs, if the real use-case for a function includes a lot of small inputs.  e.g. a memcpy implementation that's great for huge inputs but takes too long to figure out which strategy to use for small inputs might not be good.  It's a tradeoff; make sure it's good enough for large inputs (for an appropriate definition of "enough"), but also keep overhead low for small inputs.

Litmus tests:

If you're benchmarking two functions in one program: if reversing the order of testing changes the results, your benchmark isn't fair.  e.g. function A might only look slow because you're testing it first, with insufficient warm-up.  example: Why is std::vector slower than an array? (it's not, whichever loop runs first has to pay for all the page faults and cache misses; the 2nd just zooms through filling the same memory.)

Increasing the iteration count of a repeat loop should linearly increase the total time, and not affect the calculated time-per-call.  If not, then you have non-negligible measurement overhead or your code optimized away (e.g. hoisted out of the loop and runs only once instead of N times).

Vary other test parameters as a sanity check.

For C / C++, see also Simple for() loop benchmark takes the same time with any loop bound where I went into some more detail about microbenchmarking and using volatile or asm to stop important work from optimizing away with gcc/clang.

Body:
I am evaluating a network+rendering workload for my project.

The program continuously runs a main loop:

while (true) {
   doSomething()
   drawSomething()
   doSomething2()
   sendSomething()
}

The main loop runs more than 60 times per second.

I want to see the performance breakdown, how much time each procedure takes.

My concern is that if I print the time interval for every entrance and exit of each procedure,

It would incur huge performance overhead.

I am curious what is an idiomatic way of measuring the performance.

Printing of logging is good enough?


问:
How to find rows in SQL DB with a definite word length?
Good day, I've got a column with text in my table, but i need to export words 17 letters long only in it.

I tried to use

```<code>where description like '%_%_%_%_%_%_%_%_%_%_%_%_%_%_%'
</code>```

but my query newer  completes.

This is an example of text cell

REIGHT CAR DUMP T.M. "HOWO", COMMERCIAL NAME A7, MODEL TOTAL 4 PIECES,
  WITHOUT PACKING IDENTIFICATION NUMBER ENGINE NUMBER 191007018177;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 3) VIN: LZZ5DYSD5KA545780;
  CHASSIS NUMBER LZZ5DYSD5KA545780; ENGINE NUMBER 191007018247;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 4) VIN: LZZ5DYSD2KA545784;
  CHASSIS NUMBER LZZ5DYSD2KA545784; ENGINE NUMBER 191007018137;
  TRANSMISSION NUMBER NO; BRIDGE ROOMS ARE NOT AVAILABLE FREIGHT VEHICLE
  –

I am using Microsoft SQL management studio

答:
You can use that:</p>

```<code>SELECT SUBSTRING("Some words in a comumn", 1, 17) AS ExtractString;
</code>```

Body:
Good day, I've got a column with text in my table, but i need to export words 17 letters long only in it.

I tried to use

where description like '%_%_%_%_%_%_%_%_%_%_%_%_%_%_%'

but my query newer  completes.

This is an example of text cell

REIGHT CAR DUMP T.M. "HOWO", COMMERCIAL NAME A7, MODEL TOTAL 4 PIECES,
  WITHOUT PACKING IDENTIFICATION NUMBER ENGINE NUMBER 191007018177;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 3) VIN: LZZ5DYSD5KA545780;
  CHASSIS NUMBER LZZ5DYSD5KA545780; ENGINE NUMBER 191007018247;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 4) VIN: LZZ5DYSD2KA545784;
  CHASSIS NUMBER LZZ5DYSD2KA545784; ENGINE NUMBER 191007018137;
  TRANSMISSION NUMBER NO; BRIDGE ROOMS ARE NOT AVAILABLE FREIGHT VEHICLE
  –

I am using Microsoft SQL management studio

Body:
You can use that:

SELECT SUBSTRING("Some words in a comumn", 1, 17) AS ExtractString;