问:
I get an error for inserting data into SQL Server via VB.Net
I need to put some data into my SQL Server database using VB.net forms and vb language.

I already have a similar SQL request who is working but this time I get crazy errors.

This is the code who is inserting the data into the database:

```<code>Dim strIns As String = "INSERT INTO Entreprise (adresseClient, villeClient, cpClient, telClient, identClient, nomEntreprise, secteurEntreprise, dateCreationEntreprise) VALUES ('"
      strIns &= txtAdresse.Text & ", " & txtVille.Text & ", " & txtCp.Text & ", " & txtNumero.Text & ", " & txtID.Text & ", " & txtNom.Text & ", " & txtSecteur.Text & ", " & txtDateCreation.Text & "')"

Dim con As New SqlConnection
Dim cmd As New SqlCommand

Try
   con.ConnectionString = "Data Source= DESKTOP - KBTD2C1 \ MYDATABASE;Initial Catalog=MyDatabse; Integrated Security=SSPI;"
   con.Open()

   cmd.Connection = con
   cmd.CommandText = strIns

   cmd.ExecuteNonQuery()

Catch ex As Exception
    MessageBox.Show("Error While inserting record On table..." & ex.Message, "Insert Records")
Finally
    con.Close()
End Try
</code>```

I get this error:

Error while inserting record on table: Syntax error near 'Infinite'

This is the SQL command I generate in strIns:

I don't find out where is the syntax error ?

Here is my SQL Server database table:

答:
There are pieces here that replies/comments prior to this are enforced e.g. use parameters.

There are comments sprinkled throughout the code but a few things first.

It's a good idea to separate user interface from data operations thus the code below is a class which in the form an instance of the class is created, calling the AddNewRecord and passing back the newly created record's primary key.

Note how I created the SQL statement, much better than concatenating strings which is good for Framework 3.5 or higher.

Hope this helps.

```<code>Imports System.Data.SqlClient
''' <summary>
''' Created with Framework 4.5 under
''' VS2015
''' </summary>
Public Class DataOperations
    Private Server As String = "DESKTOP - KBTD2C1 \ MYDATABASE"
    Private Catalog As String = "MyDatabse"
    Private ConnectionString As String = ""
    Private mException As Exception
    ''' <summary>
    ''' If AddNewRecord returns false check this for
    ''' the exception thrown.
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property Exception As Exception
        Get
            Return mException
        End Get
    End Property
    ''' <summary>
    ''' Setup the connection string
    ''' </summary>
    Public Sub New()
        ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"
    End Sub
    ''' <summary>
    ''' I don't know you data types for fields, last one
    ''' seemed like a date so I cast the arguments in as string
    ''' exception for the last one.
    '''
    ''' Example call would be to pass in your values. Last argument
    ''' pass in a defined Integer e.g. Dim Id As Integer = 0
    ''' If this function returns true then the variable Id will contain
    ''' the new primary key value for the newly created record.
    ''' </summary>
    ''' <param name="adresseClient"></param>
    ''' <param name="villeClient"></param>
    ''' <param name="cpClient"></param>
    ''' <param name="telClient"></param>
    ''' <param name="identClient"></param>
    ''' <param name="nomEntreprise"></param>
    ''' <param name="secteurEntreprise"></param>
    ''' <param name="dateCreationEntreprise"></param>
    ''' <param name="NewIdentifier"></param>
    ''' <returns></returns>
    Public Function AddNewRecord(
        ByVal adresseClient As String,
        ByVal villeClient As String,
        ByVal cpClient As String,
        ByVal telClient As String,
        ByVal identClient As String,
        ByVal nomEntreprise As String,
        ByVal secteurEntreprise As String,
        ByVal dateCreationEntreprise As Date,
        ByRef NewIdentifier As Integer) As Boolean

        Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
            Using cmd As New SqlCommand With {.Connection = cn}
                '
                ' INSERT record then get the record's newly generated primary key
                ' (assuming the primary key is auto-incrementing int)
                '
                cmd.CommandText =
                    <SQL>
                        INSERT INTO Entreprise
                        (
                            adresseClient,
                            villeClient,
                            cpClient,
                            telClient,
                            identClient,
                            nomEntreprise,
                            secteurEntreprise,
                            dateCreationEntreprise
                        )
                        VALUES
                        (
                            @adresseClient,
                            @villeClient,
                            @cpClient,
                            @telClient,
                            @identClient,
                            @nomEntreprise,
                            @secteurEntreprise,
                            @dateCreationEntreprise
                        );
                        SELECT CAST(scope_identity() AS int);
                    </SQL>.Value

                cmd.Parameters.AddWithValue("@adresseClient", adresseClient)
                cmd.Parameters.AddWithValue("@villeClient", villeClient)
                cmd.Parameters.AddWithValue("@cpClient", cpClient)
                cmd.Parameters.AddWithValue("@telClient", telClient)
                cmd.Parameters.AddWithValue("@identClient", identClient)
                cmd.Parameters.AddWithValue("@nomEntreprise", nomEntreprise)
                cmd.Parameters.AddWithValue("@secteurEntreprise", secteurEntreprise)
                cmd.Parameters.AddWithValue("@dateCreationEntreprise", dateCreationEntreprise)

                Try
                    cn.Open()
                    NewIdentifier = CInt(cmd.ExecuteScalar)
                    Return True
                Catch ex As Exception
                    mException = ex
                    Return False
                End Try
            End Using
        End Using
    End Function
End Class
</code>```

EDIT: Mock up of usage

```<code>Public Class example
    Private dt As DataTable
    Public Sub New()
        dt = New DataTable
        dt.Columns.Add(New DataColumn With {.ColumnName = "id", .DataType = GetType(Integer), .AutoIncrement = True})
        dt.Columns.Add(New DataColumn With {.ColumnName = "adresseClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "villeClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "cpClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "telClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "identClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "nomEntreprise", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "secteurEntreprise", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "dateCreationEntreprise", .DataType = GetType(Date)})
    End Sub
    Public Sub demo()
        Dim ops As New DataOperations
        Dim id As Integer = 0
        If ops.AddNewRecord("sasas", "sdsd", "fgfgf", "wew", "asd", "cvb", "xv", Now, id) Then
            dt.Rows.Add(New Object() {id, "sasas", "sdsd", "fgfgf", "wew", "asd", "cvb", "xv", Now})
        End If
    End Sub
End Class
</code>```

Body:
I need to put some data into my SQL Server database using VB.net forms and vb language.

I already have a similar SQL request who is working but this time I get crazy errors.

This is the code who is inserting the data into the database:

Dim strIns As String = "INSERT INTO Entreprise (adresseClient, villeClient, cpClient, telClient, identClient, nomEntreprise, secteurEntreprise, dateCreationEntreprise) VALUES ('"
      strIns &= txtAdresse.Text & ", " & txtVille.Text & ", " & txtCp.Text & ", " & txtNumero.Text & ", " & txtID.Text & ", " & txtNom.Text & ", " & txtSecteur.Text & ", " & txtDateCreation.Text & "')"

Dim con As New SqlConnection
Dim cmd As New SqlCommand

Try
   con.ConnectionString = "Data Source= DESKTOP - KBTD2C1 \ MYDATABASE;Initial Catalog=MyDatabse; Integrated Security=SSPI;"
   con.Open()

   cmd.Connection = con
   cmd.CommandText = strIns

   cmd.ExecuteNonQuery()

Catch ex As Exception
    MessageBox.Show("Error While inserting record On table..." & ex.Message, "Insert Records")
Finally
    con.Close()
End Try

I get this error:

Error while inserting record on table: Syntax error near 'Infinite'

This is the SQL command I generate in strIns:

I don't find out where is the syntax error ?

Here is my SQL Server database table:

Body:
There are pieces here that replies/comments prior to this are enforced e.g. use parameters.

There are comments sprinkled throughout the code but a few things first.

It's a good idea to separate user interface from data operations thus the code below is a class which in the form an instance of the class is created, calling the AddNewRecord and passing back the newly created record's primary key.

Note how I created the SQL statement, much better than concatenating strings which is good for Framework 3.5 or higher.

Hope this helps.

Imports System.Data.SqlClient
''' <summary>
''' Created with Framework 4.5 under
''' VS2015
''' </summary>
Public Class DataOperations
    Private Server As String = "DESKTOP - KBTD2C1 \ MYDATABASE"
    Private Catalog As String = "MyDatabse"
    Private ConnectionString As String = ""
    Private mException As Exception
    ''' <summary>
    ''' If AddNewRecord returns false check this for
    ''' the exception thrown.
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property Exception As Exception
        Get
            Return mException
        End Get
    End Property
    ''' <summary>
    ''' Setup the connection string
    ''' </summary>
    Public Sub New()
        ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"
    End Sub
    ''' <summary>
    ''' I don't know you data types for fields, last one
    ''' seemed like a date so I cast the arguments in as string
    ''' exception for the last one.
    '''
    ''' Example call would be to pass in your values. Last argument
    ''' pass in a defined Integer e.g. Dim Id As Integer = 0
    ''' If this function returns true then the variable Id will contain
    ''' the new primary key value for the newly created record.
    ''' </summary>
    ''' <param name="adresseClient"></param>
    ''' <param name="villeClient"></param>
    ''' <param name="cpClient"></param>
    ''' <param name="telClient"></param>
    ''' <param name="identClient"></param>
    ''' <param name="nomEntreprise"></param>
    ''' <param name="secteurEntreprise"></param>
    ''' <param name="dateCreationEntreprise"></param>
    ''' <param name="NewIdentifier"></param>
    ''' <returns></returns>
    Public Function AddNewRecord(
        ByVal adresseClient As String,
        ByVal villeClient As String,
        ByVal cpClient As String,
        ByVal telClient As String,
        ByVal identClient As String,
        ByVal nomEntreprise As String,
        ByVal secteurEntreprise As String,
        ByVal dateCreationEntreprise As Date,
        ByRef NewIdentifier As Integer) As Boolean

        Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
            Using cmd As New SqlCommand With {.Connection = cn}
                '
                ' INSERT record then get the record's newly generated primary key
                ' (assuming the primary key is auto-incrementing int)
                '
                cmd.CommandText =
                    <SQL>
                        INSERT INTO Entreprise
                        (
                            adresseClient,
                            villeClient,
                            cpClient,
                            telClient,
                            identClient,
                            nomEntreprise,
                            secteurEntreprise,
                            dateCreationEntreprise
                        )
                        VALUES
                        (
                            @adresseClient,
                            @villeClient,
                            @cpClient,
                            @telClient,
                            @identClient,
                            @nomEntreprise,
                            @secteurEntreprise,
                            @dateCreationEntreprise
                        );
                        SELECT CAST(scope_identity() AS int);
                    </SQL>.Value

                cmd.Parameters.AddWithValue("@adresseClient", adresseClient)
                cmd.Parameters.AddWithValue("@villeClient", villeClient)
                cmd.Parameters.AddWithValue("@cpClient", cpClient)
                cmd.Parameters.AddWithValue("@telClient", telClient)
                cmd.Parameters.AddWithValue("@identClient", identClient)
                cmd.Parameters.AddWithValue("@nomEntreprise", nomEntreprise)
                cmd.Parameters.AddWithValue("@secteurEntreprise", secteurEntreprise)
                cmd.Parameters.AddWithValue("@dateCreationEntreprise", dateCreationEntreprise)

                Try
                    cn.Open()
                    NewIdentifier = CInt(cmd.ExecuteScalar)
                    Return True
                Catch ex As Exception
                    mException = ex
                    Return False
                End Try
            End Using
        End Using
    End Function
End Class

EDIT: Mock up of usage

Public Class example
    Private dt As DataTable
    Public Sub New()
        dt = New DataTable
        dt.Columns.Add(New DataColumn With {.ColumnName = "id", .DataType = GetType(Integer), .AutoIncrement = True})
        dt.Columns.Add(New DataColumn With {.ColumnName = "adresseClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "villeClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "cpClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "telClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "identClient", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "nomEntreprise", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "secteurEntreprise", .DataType = GetType(String)})
        dt.Columns.Add(New DataColumn With {.ColumnName = "dateCreationEntreprise", .DataType = GetType(Date)})
    End Sub
    Public Sub demo()
        Dim ops As New DataOperations
        Dim id As Integer = 0
        If ops.AddNewRecord("sasas", "sdsd", "fgfgf", "wew", "asd", "cvb", "xv", Now, id) Then
            dt.Rows.Add(New Object() {id, "sasas", "sdsd", "fgfgf", "wew", "asd", "cvb", "xv", Now})
        End If
    End Sub
End Class


来源: stackexchange

问:
How remove duplicates from sql list?
```<code><property name="xxDescribtionNumbers" formula="(
                select nvl(listagg(A.NUMBER, ', ') within group (order by A.NUMBER),' ')
                from  ENTER E
                left outer join ADRESS A on A.ID = E.ADRESS_ID
                where E.BUILDING_ID = ID
                )" />
</code>```

<p>This will make a list of numbers but can contains duplicities, but I don't want any duplicities. </p>

答:
You can do this by removing the values in a subquery:</p>

```<code>select coalesce(listagg(va.CISLO, ', ') within group (order by va.CISLO), ' ')
from (select distinct a.cislo
      from VCHOD V left join
           ADRESA A
           on A.ID = V.ADRESA_ID
      where V.BUDOVA_ID = ID
     ) va;
</code>```

ContentLicense: CC BY-SA 3.0

Title: How remove duplicates from sql list?

Body:
<property name="xxDescribtionNumbers" formula="(
                select nvl(listagg(A.NUMBER, ', ') within group (order by A.NUMBER),' ')
                from  ENTER E
                left outer join ADRESS A on A.ID = E.ADRESS_ID
                where E.BUILDING_ID = ID
                )" />

This will make a list of numbers but can contains duplicities, but I don't want any duplicities.

Body:
You can do this by removing the values in a subquery:

select coalesce(listagg(va.CISLO, ', ') within group (order by va.CISLO), ' ')
from (select distinct a.cislo
      from VCHOD V left join
           ADRESA A
           on A.ID = V.ADRESA_ID
      where V.BUDOVA_ID = ID
     ) va;


问:
Do i need to learn Nodejs to understand and work with NPM?
Today most of developers use NPM to manage their things. I know what NPM and NodeJS are but i'm a bit confused about how NPM works! should i have to learn NodeJS to understand NPM?</p>

答:
this guy asks a question similar to yours:

do-i-have-to-learn-node-js-in-order-to-use-npm

but i think you mean something else and your question about understanding what NPM really is!
if you simply google to what npm is you will find:

npm, short for Node Package Manager, is two things: first and foremost, it is an online repository for the publishing of open-source Node.js projects; second, it is a command-line utility for interacting with said repository that aids in package installation, version management, and dependency management

by Mr. Nico Reed. source: https://docs.nodejitsu.com/articles/getting-started/npm/what-is-npm/

Nodejs has some tools like npm and nvm. Npm(node package manager) is a package manager. It let's you install software (libraries, plugins, frameworks and applications). Typically this software is installed to build Node applications.


问:
Convert asp.net / MS proprietary json Dateformat to java8 LocalDateTime with jackson while deserializing json to object
I call a webservice from a Spring Boot App, using jackson-jsr-310 as maven dependency for being able to make use of LocalDateTime:

```<code>RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = this.createHeaders();
ResponseEntity<String> response;
response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
BusinessPartner test = mapper.readValue(response.getBody(), BusinessPartner.class);
</code>```

My problem is in the last line, the code produces this error:

java.time.format.DateTimeParseException: Text '/Date(591321600000)/' could not be parsed at index 0

The resulting JSON in response.getBody() looks like this:

```<code>{
    "d":{
        ...
        "Address":{...},
        "FirstName":"asd",
        "LastName":"asd",
        "BirthDate":"\/Date(591321600000)\/",
    }
}
</code>```

And in my model class, I have the following member:

```<code>@JsonProperty("BirthDate")
private LocalDateTime birthDate;
</code>```

So, after a bit of searching here I found out that this /Date(...)/ seems to be a Microsoft-proprietary Dateformat, which Jackson cannot deserialize into an object  per default.

Some questions advise to create a custom SimpleDateFormat and apply it to the opbject mapper, which I tried to do, but then I think I miss the right syntax for     mapper.setDateFormat(new SimpleDateFormat("..."));

I tried with e.g. mapper.setDateFormat(new SimpleDateFormat("/Date(S)/"));

or at the end even mapper.setDateFormat(new SimpleDateFormat("SSSSSSSSSSSS)"));

but it seems this does not work, too, so I am out of ideas for now and  hope some people here could help me out.

edit 1:

further investigated, it seems one way to go is to write a custom DateDeSerializer for jackson. So I tried this:

```<code>@Component
public class JsonDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

private DateTimeFormatter formatter;

private JsonDateTimeDeserializer() {
    this(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}

public JsonDateTimeDeserializer(DateTimeFormatter formatter) {
    this.formatter = formatter;
}

@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    if (parser.hasTokenId(JsonTokenId.ID_STRING)) {
        String unixEpochString = parser.getText().trim();
        unixEpochString = unixEpochString.replaceAll("[^\\d.]", "");

        long unixTime = Long.valueOf(unixEpochString);
        if (unixEpochString.length() == 0) {
            return null;
        }

        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(unixTime), ZoneId.systemDefault());
        localDateTime.format(formatter);

        return localDateTime;
    }
    return null;
}
</code>```

}

which actually returns nearly what I want, annotating my fields in the model using

```<code>@JsonDeserialize(using = JsonDateTimeDeserializer.class)
</code>```

but not exactly:
This code returns a LocalDateTime of value: 1988-09-27T01:00.
But in the thirdparty system, the xmlvalue is 1988-09-27T00:00:00.

As it is obvious, the ZoneId here:

```<code>LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(unixTime), ZoneId.systemDefault());
</code>```

is the Problem, apart from a wrong dateformat.

So could someone here please help me out in how to switch to always use zeros for the time-part and to get my dateformat right? Would be great!

答:
I'm assuming that the number 591321600000 is the epoch milli (number of milliseconds from 1970-01-01T00:00:00Z).

If that's the case, I think that SimpleDateFormat can't help you (at least I couldn't find a way to parse a date from the epoch milli using this class). The pattern S (according to javadoc) is used to format or parse the milliseconds field of a time (so its maximum value is 999) and won't work for your case.

The only way I could make it work is creating a custom deserializer.

First, I created this class:

```<code>public class SimpleDateTest {

    @JsonProperty("BirthDate")
    private LocalDateTime birthDate;

    // getter and setter
}
</code>```

Then I created the custom deserializer and added it to a custom module:

```<code>// I'll explain all the details below
public class CustomDateDeserializer extends JsonDeserializer<LocalDateTime> {

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String s = p.getText(); // s is "/Date(591321600000)/"

        // assuming the format is always /Date(number)/
        long millis = Long.parseLong(s.replaceAll("\\/Date\\((\\d+)\\)\\/", "$1"));

        Instant instant = Instant.ofEpochMilli(millis); // 1988-09-27T00:00:00Z

        // instant is in UTC (no timezone assigned to it)
        // to get the local datetime, you must provide a timezone
        // I'm just using system's default, but you must use whatever timezone your system uses
        return instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}

public class CustomDateModule extends SimpleModule {

    public CustomDateModule() {
        addDeserializer(LocalDateTime.class, new CustomDateDeserializer());
    }
}
</code>```

Then I added this module to my mapper and it worked:

```<code>// using reduced JSON with only the relevant field
String json = "{ \"BirthDate\": \"\\/Date(591321600000)\\/\" }";
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
// add my custom module
mapper.registerModule(new CustomDateModule());

SimpleDateTest value = mapper.readValue(json, SimpleDateTest.class);
System.out.println(value.getBirthDate()); // 1988-09-26T21:00
</code>```

Now some comments about the deserializer method.

First I converted the millis 591321600000 to an Instant (a class that represents a UTC instant). 591321600000 in millis is equivalent to 1988-09-27T00:00:00Z.

But that's the UTC date/time. To get the local date and time, you must know in what timezone you are, because in every timezone it's a different date and time (everybody in the world are at the same instant, but their local date/time might be different, depending on where they are).

In my example, I just used ZoneId.systemDefault(), which gets the default timezone of my system. But if you don't want to depend on the default and want to use a specific timezone, use the ZoneId.of("timezone name") method (you can get the list of all available timezones names with ZoneId.getAvailableZoneIds() - this method returns all valid names accepted by the ZoneId.of() method).

As my default timezone is America/Sao_Paulo, this code sets the birthDate to  1988-09-26T21:00.

If you don't want to convert to a specific timezone, you can use the ZoneOffset.UTC. So, in the deserializer method, the last line will be:

```<code>   return instant.atZone(ZoneOffset.UTC).toLocalDateTime();
</code>```

Now the local date will be 1988-09-27T00:00 - as we're using UTC offset, there's no timezone conversion and the local date/time is not changed.

PS: if you need to convert the birthDate back to MS's custom format, you can write a custom serializer and add to the custom module as well. To convert a LocalDateTime to that format, you can do:

```<code>LocalDateTime birthDate = value.getBirthDate();
// you must know in what zone you are to convert it to epoch milli (using default as an example)
Instant instant = birthDate.atZone(ZoneId.systemDefault()).toInstant();
String msFormat = "/Date(" + instant.toEpochMilli() + ")/";
System.out.println(msFormat); // /Date(591321600000)/
</code>```

Note that, to convert a LocalDateTime to Instant, you must know in what timezone you are. In this case, I recommend to use the same timezone for serializing and deserializing (in your case, you can use ZoneOffset.UTC instead of ZoneId.systemDefault().

Body:
I call a webservice from a Spring Boot App, using jackson-jsr-310 as maven dependency for being able to make use of LocalDateTime:

RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = this.createHeaders();
ResponseEntity<String> response;
response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
BusinessPartner test = mapper.readValue(response.getBody(), BusinessPartner.class);

My problem is in the last line, the code produces this error:

java.time.format.DateTimeParseException: Text '/Date(591321600000)/' could not be parsed at index 0

The resulting JSON in response.getBody() looks like this:

{
    "d":{
        ...
        "Address":{...},
        "FirstName":"asd",
        "LastName":"asd",
        "BirthDate":"\/Date(591321600000)\/",
    }
}

And in my model class, I have the following member:

@JsonProperty("BirthDate")
private LocalDateTime birthDate;

So, after a bit of searching here I found out that this /Date(...)/ seems to be a Microsoft-proprietary Dateformat, which Jackson cannot deserialize into an object  per default.

Some questions advise to create a custom SimpleDateFormat and apply it to the opbject mapper, which I tried to do, but then I think I miss the right syntax for     mapper.setDateFormat(new SimpleDateFormat("..."));

I tried with e.g. mapper.setDateFormat(new SimpleDateFormat("/Date(S)/"));

or at the end even mapper.setDateFormat(new SimpleDateFormat("SSSSSSSSSSSS)"));

but it seems this does not work, too, so I am out of ideas for now and  hope some people here could help me out.

edit 1:

further investigated, it seems one way to go is to write a custom DateDeSerializer for jackson. So I tried this:

@Component
public class JsonDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

private DateTimeFormatter formatter;

private JsonDateTimeDeserializer() {
    this(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}

public JsonDateTimeDeserializer(DateTimeFormatter formatter) {
    this.formatter = formatter;
}

@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    if (parser.hasTokenId(JsonTokenId.ID_STRING)) {
        String unixEpochString = parser.getText().trim();
        unixEpochString = unixEpochString.replaceAll("[^\\d.]", "");

        long unixTime = Long.valueOf(unixEpochString);
        if (unixEpochString.length() == 0) {
            return null;
        }

        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(unixTime), ZoneId.systemDefault());
        localDateTime.format(formatter);

        return localDateTime;
    }
    return null;
}

}

which actually returns nearly what I want, annotating my fields in the model using

@JsonDeserialize(using = JsonDateTimeDeserializer.class)

but not exactly:
This code returns a LocalDateTime of value: 1988-09-27T01:00.
But in the thirdparty system, the xmlvalue is 1988-09-27T00:00:00.

As it is obvious, the ZoneId here:

LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(unixTime), ZoneId.systemDefault());

is the Problem, apart from a wrong dateformat.

So could someone here please help me out in how to switch to always use zeros for the time-part and to get my dateformat right? Would be great!

Body:
I'm assuming that the number 591321600000 is the epoch milli (number of milliseconds from 1970-01-01T00:00:00Z).

If that's the case, I think that SimpleDateFormat can't help you (at least I couldn't find a way to parse a date from the epoch milli using this class). The pattern S (according to javadoc) is used to format or parse the milliseconds field of a time (so its maximum value is 999) and won't work for your case.

The only way I could make it work is creating a custom deserializer.

First, I created this class:

public class SimpleDateTest {

    @JsonProperty("BirthDate")
    private LocalDateTime birthDate;

    // getter and setter
}

Then I created the custom deserializer and added it to a custom module:

// I'll explain all the details below
public class CustomDateDeserializer extends JsonDeserializer<LocalDateTime> {

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String s = p.getText(); // s is "/Date(591321600000)/"

        // assuming the format is always /Date(number)/
        long millis = Long.parseLong(s.replaceAll("\\/Date\\((\\d+)\\)\\/", "$1"));

        Instant instant = Instant.ofEpochMilli(millis); // 1988-09-27T00:00:00Z

        // instant is in UTC (no timezone assigned to it)
        // to get the local datetime, you must provide a timezone
        // I'm just using system's default, but you must use whatever timezone your system uses
        return instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}

public class CustomDateModule extends SimpleModule {

    public CustomDateModule() {
        addDeserializer(LocalDateTime.class, new CustomDateDeserializer());
    }
}

Then I added this module to my mapper and it worked:

// using reduced JSON with only the relevant field
String json = "{ \"BirthDate\": \"\\/Date(591321600000)\\/\" }";
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
// add my custom module
mapper.registerModule(new CustomDateModule());

SimpleDateTest value = mapper.readValue(json, SimpleDateTest.class);
System.out.println(value.getBirthDate()); // 1988-09-26T21:00

Now some comments about the deserializer method.

First I converted the millis 591321600000 to an Instant (a class that represents a UTC instant). 591321600000 in millis is equivalent to 1988-09-27T00:00:00Z.

But that's the UTC date/time. To get the local date and time, you must know in what timezone you are, because in every timezone it's a different date and time (everybody in the world are at the same instant, but their local date/time might be different, depending on where they are).

In my example, I just used ZoneId.systemDefault(), which gets the default timezone of my system. But if you don't want to depend on the default and want to use a specific timezone, use the ZoneId.of("timezone name") method (you can get the list of all available timezones names with ZoneId.getAvailableZoneIds() - this method returns all valid names accepted by the ZoneId.of() method).

As my default timezone is America/Sao_Paulo, this code sets the birthDate to  1988-09-26T21:00.

If you don't want to convert to a specific timezone, you can use the ZoneOffset.UTC. So, in the deserializer method, the last line will be:

   return instant.atZone(ZoneOffset.UTC).toLocalDateTime();

Now the local date will be 1988-09-27T00:00 - as we're using UTC offset, there's no timezone conversion and the local date/time is not changed.

PS: if you need to convert the birthDate back to MS's custom format, you can write a custom serializer and add to the custom module as well. To convert a LocalDateTime to that format, you can do:

LocalDateTime birthDate = value.getBirthDate();
// you must know in what zone you are to convert it to epoch milli (using default as an example)
Instant instant = birthDate.atZone(ZoneId.systemDefault()).toInstant();
String msFormat = "/Date(" + instant.toEpochMilli() + ")/";
System.out.println(msFormat); // /Date(591321600000)/

Note that, to convert a LocalDateTime to Instant, you must know in what timezone you are. In this case, I recommend to use the same timezone for serializing and deserializing (in your case, you can use ZoneOffset.UTC instead of ZoneId.systemDefault().


问:
How to auto paste a value if checkbox is checked
I want a functionality, i have a list with checkbox i if checkbox is selected i want to paste the selected value in a text field.

Something like appeared in above image.

edited:

```<code><table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Order Id</th>
                <th>Order Proposed Id</th>
                <th>Order Proposed Date</th>
                <th>Store Id</th>
                <th>Select</th>
            </tr>
        </thead>
        <tbody>
        <%for(Order orderSList:orderList){ %>
            <tr>
                <td><%=orderSList.getOrderId()%></td>
                 <td><%=orderSList.getOrderProposedId()%></td>
                 <td><%=orderSList.getOrderProposedDate()%></td>
                 <td><%=orderSList.getStoreId()%></td>
                 <td><input type="checkbox" name="<portlet:namespace/>notSubmitList" value="<%=orderSList.getOrderId()%>" class="case" /></td>
            </tr>
          <%} %>
        </tbody>
    </table>
 <script>
</code>```

答:
```<code>var inputs = [].slice.call(document.querySelectorAll("#userTable input[type=checkbox]"));

function generateText() {
  return inputs.reduce(function(builtList, input) {
    if (input.checked) {
      return builtList.concat(input.value);
    }
    return builtList;
  }, []).join();
}

var textarea = document.querySelector("textarea");
inputs.forEach(function(input) {
  input.addEventListener("click", function() {
    textarea.value = generateText();
  });
});
</code>```

Preferably, you'd use a better way (such as document.getElementById()) to select the text area, but you didn't include it in your code so I don't know its ID

Body:
I want a functionality, i have a list with checkbox i if checkbox is selected i want to paste the selected value in a text field.

Something like appeared in above image.

edited:

                Order Id
                Order Proposed Id
                Order Proposed Date
                Store Id
                Select

        <%for(Order orderSList:orderList){ %>

                <%=orderSList.getOrderId()%>
                 <%=orderSList.getOrderProposedId()%>
                 <%=orderSList.getOrderProposedDate()%>
                 <%=orderSList.getStoreId()%>
                 <input type="checkbox" name="<portlet:namespace/>notSubmitList" value="<%=orderSList.getOrderId()%>" class="case" />

          <%} %>

Body:
var inputs = [].slice.call(document.querySelectorAll("#userTable input[type=checkbox]"));

function generateText() {
  return inputs.reduce(function(builtList, input) {
    if (input.checked) {
      return builtList.concat(input.value);
    }
    return builtList;
  }, []).join();
}

var textarea = document.querySelector("textarea");
inputs.forEach(function(input) {
  input.addEventListener("click", function() {
    textarea.value = generateText();
  });
});

Preferably, you'd use a better way (such as document.getElementById()) to select the text area, but you didn't include it in your code so I don't know its ID


问:
Accessing template variable className properties in angular 2
I have the following form with name input field. I am trying to put validations on the field. When I print the name.className value it prints ng-valid, ng-pristine and other classes.

I want to use *ngIf to display the error message but it is not working.

I tried *ngIf="name.ng-invalid" also but it is not working. Can anyone suggest what is wrong here?

```<code>    <form class="form-horizontal div-table" >
       <!-- Name -->
       <div class="form-group row-even">
          <label class="col-md-4 control-label">Name:</label>
          <div class="col-md-7">
             <input id="name" name="name" type="text" class="form-control" [(ngModel)]="data.name" required minlength="3" maxlength="64" #name>
             <small *ngIf="name.ng-invalid">
             Name is required (minimum 3 characters).
             </small>
             <small>
             Element {{ name.className }}
             </small>
          </div>
       </div>
    </form>
</code>```

答:
Try this code        </p>

```<code><form (ngSubmit)="onSubmit()" #myForm="ngForm">
...
    <div [hidden]="name.valid || name.pristine"
         class="alert alert-danger">
         Name is required
    </div>

 ...
    </form>
</code>```

Body:
I have the following form with name input field. I am trying to put validations on the field. When I print the name.className value it prints ng-valid, ng-pristine and other classes.

I want to use *ngIf to display the error message but it is not working.

I tried *ngIf="name.ng-invalid" also but it is not working. Can anyone suggest what is wrong here?

    <form class="form-horizontal div-table" >

          Name:

             <input id="name" name="name" type="text" class="form-control" [(ngModel)]="data.name" required minlength="3" maxlength="64" #name>

             Name is required (minimum 3 characters).

             Element {{ name.className }}

    </form>

Body:
Try this code

<form (ngSubmit)="onSubmit()" #myForm="ngForm">
...
    <div [hidden]="name.valid || name.pristine"
         class="alert alert-danger">
         Name is required
    </div>

 ...
    </form>


问:
Unable to load a website in iFrame
I want to register for a course using the Sign-Up option and I want to load a website in an iFrame. The website specifies the X-Frame-Options = ALLOW

But when I click on the Sign-Up button, the website is redirected to its homepage and I am not able to load it in my iFrame.

Why am I not able to load the URL in my iFrame?

答:
Assuming you create a form  with name theForm and want send the form to display the result in an iFrame container.

```<code><form id="theForm" action="example.php" method="GET" target="iframe_name">
   <input name="username" type="text" value="">
   <input name="password" type="text" value="">
   <input name="sender" type="text" value="">
  <script>
    document.getElementById('theForm').submit();
  </script>
</form>
</code>```

Title: Unable to load a website in iFrame

Body:
Assuming you create a form  with name theForm and want send the form to display the result in an iFrame container.

<iframe name='iframe_name' width='200' height='200'></iframe>

<form id="theForm" action="example.php" method="GET" target="iframe_name">
   <input name="username" type="text" value="">
   <input name="password" type="text" value="">
   <input name="sender" type="text" value="">
  <script>
    document.getElementById('theForm').submit();
  </script>
</form>


问:
How to make an array with random numbers, with one condition repeated n number of times?
I have an array which I fill with random floating numbers from 0 to 1.

```<code>x = np.random.random((20,20))
</code>```

Later on, I will extract the items in the array (x[row][column]) which are larger than 0.2,with this:

```<code>loc = np.argwhere(x > 0.2)
</code>```

However,I cannot control the size of the loc. I have to have maximum 80 elements which are providing the condition of being larger than 0.2.

```<code>maxnum = 80
len(loc) == maxnum
</code>```

And the [row][column] combinations of the items which provide being larger than 0.2 should be different each time, as it should be a random array.
To be more specific, if I would make an array :

```<code>y = np.random.random((4,4))
</code>```

which yields:

```<code>array([[ 0.90282391,  0.11295454,  0.22650744,  0.31376307],
       [ 0.44553798,  0.19264588,  0.8944689 ,  0.77730786],
       [ 0.17462983,  0.79806749,  0.02074193,  0.3545992 ],
       [ 0.60130149,  0.5982725 ,  0.20522246,  0.99080217]])
</code>```

I need only random 3 of them to be larger than 0.2.
Therefore, the expected output should look like:

```<code>array([[ **0.90282391**,  0.11295454,  0.12650744,  0.11376307],
       [ 0.14553798,  0.19264588,  0.1944689 ,  0.17730786],
       [ 0.17462983,  0.19806749,  0.02074193,  **0.3545992** ],
       [ 0.10130149,  **0.5982725** ,  0.10522246,  0.19080217]])
</code>```

and the bold ones(larger than 0.2) their location should change in every run.

Do you know how to achieve that output?

答:
```<code>import numpy as np
n = 20
threshold = 0.2
maxNum = 80
res = np.zeros([n, n])
perm = np.random.permutation(n ** 2)

res.flat[perm[:maxNum]] = np.random.uniform(size=maxNum, low=threshold, high=1)
res.flat[perm[maxNum:]] = np.random.uniform(size=n**2 - maxNum, low=0, high=threshold)
</code>```

Let me explain. We create an empty array res of shape (n, n). We will have exactly maxNum values higher than threshold.
We select maxNum distinct indices between 0 and n ** 2 - 1 (I use np.random.permutation for this). We fill the corresponding values in a flatten view of res with uniform values between 0.2 and 1.

We fill the rest of res with values uniformly drawn between 0 and 0.2.

And so:

```<code>In [59]: len(np.argwhere(res > threshold))
Out[59]: 80
</code>```

Body:
I have an array which I fill with random floating numbers from 0 to 1.

x = np.random.random((20,20))

Later on, I will extract the items in the array (x[row][column]) which are larger than 0.2,with this:

loc = np.argwhere(x > 0.2)

However,I cannot control the size of the loc. I have to have maximum 80 elements which are providing the condition of being larger than 0.2.

maxnum = 80
len(loc) == maxnum

And the [row][column] combinations of the items which provide being larger than 0.2 should be different each time, as it should be a random array.
To be more specific, if I would make an array :

y = np.random.random((4,4))

which yields:

array([[ 0.90282391,  0.11295454,  0.22650744,  0.31376307],
       [ 0.44553798,  0.19264588,  0.8944689 ,  0.77730786],
       [ 0.17462983,  0.79806749,  0.02074193,  0.3545992 ],
       [ 0.60130149,  0.5982725 ,  0.20522246,  0.99080217]])

I need only random 3 of them to be larger than 0.2.
Therefore, the expected output should look like:

array([[ **0.90282391**,  0.11295454,  0.12650744,  0.11376307],
       [ 0.14553798,  0.19264588,  0.1944689 ,  0.17730786],
       [ 0.17462983,  0.19806749,  0.02074193,  **0.3545992** ],
       [ 0.10130149,  **0.5982725** ,  0.10522246,  0.19080217]])

and the bold ones(larger than 0.2) their location should change in every run.

Do you know how to achieve that output?

Body:
import numpy as np
n = 20
threshold = 0.2
maxNum = 80
res = np.zeros([n, n])
perm = np.random.permutation(n ** 2)

res.flat[perm[:maxNum]] = np.random.uniform(size=maxNum, low=threshold, high=1)
res.flat[perm[maxNum:]] = np.random.uniform(size=n**2 - maxNum, low=0, high=threshold)

Let me explain. We create an empty array res of shape (n, n). We will have exactly maxNum values higher than threshold.
We select maxNum distinct indices between 0 and n ** 2 - 1 (I use np.random.permutation for this). We fill the corresponding values in a flatten view of res with uniform values between 0.2 and 1.

We fill the rest of res with values uniformly drawn between 0 and 0.2.

And so:

In [59]: len(np.argwhere(res > threshold))
Out[59]: 80


问:
Extract data from soap service using java code
i am tring to extract response data from wsdl url using soapui java code. all are working good, but problem is in response.

in response i am getting ? instead of getting proper data.

Eclipse Console result

but when i am tring to hit wsdl url using soapui it is working fine.

check my code

```<code>package src.com;

import com.eviware.soapui.impl.wsdl.WsdlInterface;
import com.eviware.soapui.impl.wsdl.WsdlOperation;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlImporter;
import com.eviware.soapui.model.iface.Operation;

public class Test {

    public static void main(String[] args) throws Exception {
        WsdlProject project = new WsdlProject();
        WsdlInterface[] wsdls = WsdlImporter.importWsdl(project, "http://localhost:8080/SoapService/services/TestService?wsdl");
        WsdlInterface wsdl = wsdls[0];
        for (Operation operation : wsdl.getOperationList()) {
            WsdlOperation wsdlOperation = (WsdlOperation) operation;
            System.out.println("Request:\n"+wsdlOperation.createRequest(true));
            System.out.println("\nResponse:\n"+wsdlOperation.createResponse(true));

        }
    }
}
</code>```

Check Jars

答:
Within the SoapUI application you are actually making a call out to the web service and getting a response. In your sample java code you are just generating a response XML from the WSDL file instead of actually calling out to the web service and it's defaulting any required values to have a ?. If you generate the same response within the SoapUI application you will see the same ? set for the findAllReturned element.

You can use the java SoapUI's WSDLSubmit class to make a call out to the web service and get a response back.

The answer to this linked question shows a code sample of how you would go about making an actual call out to the web service using the SoapUI java api:
https://stackoverflow.com/a/14814524/8127149

And this link has other examples of using the WSDLSubmit class:
http://www.programcreek.com/java-api-examples/index.php?api=com.eviware.soapui.impl.wsdl.WsdlSubmit

Body:
i am tring to extract response data from wsdl url using soapui java code. all are working good, but problem is in response.

in response i am getting ? instead of getting proper data.

Eclipse Console result

but when i am tring to hit wsdl url using soapui it is working fine.

check my code

package src.com;

import com.eviware.soapui.impl.wsdl.WsdlInterface;
import com.eviware.soapui.impl.wsdl.WsdlOperation;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlImporter;
import com.eviware.soapui.model.iface.Operation;

public class Test {

    public static void main(String[] args) throws Exception {
        WsdlProject project = new WsdlProject();
        WsdlInterface[] wsdls = WsdlImporter.importWsdl(project, "http://localhost:8080/SoapService/services/TestService?wsdl");
        WsdlInterface wsdl = wsdls[0];
        for (Operation operation : wsdl.getOperationList()) {
            WsdlOperation wsdlOperation = (WsdlOperation) operation;
            System.out.println("Request:\n"+wsdlOperation.createRequest(true));
            System.out.println("\nResponse:\n"+wsdlOperation.createResponse(true));

        }
    }
}

Check Jars


问:
OnGetRowsValue returns "undefined"
I have GridView with data which works perfectly fine and everything loads correctly. I need to extract data from one column using button but the function will always return undefined even it's loaded correctly.

In same .cshtml file with grid and button I have this "simple" script with 2 functions:

```<code><script id="dxss_1610925110" type="text/javascript">
    function ShowValue() {
        gridViewINS.GetRowValues(gridViewINS.GetFocusedRowIndex(), "Insolvency.FileNumber", gridViewINSOnGetRowValues());
    }

    function gridViewINSOnGetRowValues(value) {
        alert(value);
    }
</script>
</code>```

Now when I click the button two alerts pop up. One is undefined. The second is literally snippet of my code which has the value in it which I need. So it can get somehow the data but why not directly to value property? I can't find what I am doing wrong. Any help will be appreciated.

答:
I think you need to remove the parentheses () from gridViewINSOnGetRowValues().

Like so:

```<code>gridViewINS.GetRowValues(gridViewINS.GetFocusedRowIndex(), "Insolvency.FileNumber", gridViewINSOnGetRowValues);
</code>```

Title: OnGetRowsValue returns "undefined"

Body:
I have GridView with data which works perfectly fine and everything loads correctly. I need to extract data from one column using button but the function will always return undefined even it's loaded correctly.

In same .cshtml file with grid and button I have this "simple" script with 2 functions:

Now when I click the button two alerts pop up. One is undefined. The second is literally snippet of my code which has the value in it which I need. So it can get somehow the data but why not directly to value property? I can't find what I am doing wrong. Any help will be appreciated.

Body:
I think you need to remove the parentheses () from gridViewINSOnGetRowValues().

Like so:

gridViewINS.GetRowValues(gridViewINS.GetFocusedRowIndex(), "Insolvency.FileNumber", gridViewINSOnGetRowValues);


问:
Why is std::min_element and company not specialized for std::vector<bool>
I have a std::vector<bool> instance (foo, say), and I need to write a function that returns true if all the elements are true.

I use

```<code>return *std::min_element(foo.begin(), foo.end());
</code>```

to achieve that, but this has got me thinking: you know the minimum element is false, if the container contains at least one false value. In other words, you don't need to traverse the whole container to end(), which means that a specialisation of std::min_element is appropriate, just like a specialisation of std::vector<bool> has been deemed appropriate.

Am I missing anything? Or would this be viewed as a premature optimization? Perhaps a good compiler would sort it out anyway.

答:
There is no need to specialize std::min_element for std::vector<bool>.  To get the functionality that you want you can just use std::any_of which will stop at the first occurrence.

```<code>return !std::any_of(foo.begin(), foo.end(), [](auto e){ return e == false; });
</code>```

If we change this to std::all_of as Some programmer dude suggests then you do not need to negate the return value, which gives you

```<code>return std::all_of(foo.begin(), foo.end(), [](auto e){ return e; });
</code>```

Which is a little cleaner and easier to understand.

Body:
I have a std::vector<bool> instance (foo, say), and I need to write a function that returns true if all the elements are true.

I use

return *std::min_element(foo.begin(), foo.end());

to achieve that, but this has got me thinking: you know the minimum element is false, if the container contains at least one false value. In other words, you don't need to traverse the whole container to end(), which means that a specialisation of std::min_element is appropriate, just like a specialisation of std::vector<bool> has been deemed appropriate.

Am I missing anything? Or would this be viewed as a premature optimization? Perhaps a good compiler would sort it out anyway.

Body:
There is no need to specialize std::min_element for std::vector<bool>.  To get the functionality that you want you can just use std::any_of which will stop at the first occurrence.

return !std::any_of(foo.begin(), foo.end(), [](auto e){ return e == false; });

If we change this to std::all_of as Some programmer dude suggests then you do not need to negate the return value, which gives you

return std::all_of(foo.begin(), foo.end(), [](auto e){ return e; });

Which is a little cleaner and easier to understand.

ContentLicense: CC BY-SA 4.0


问:
postgresql how to use boolean in where statement
I'm a really bad in sql , my query is

```<code> select * from car_wash where
           (select ST_Within((select car_wash.lon_lat from car_wash),(select ST_Buffer(ST_GeomFromText('POINT(65.3 323.2)'),20)))) = true
        AND car_wash.was_deleted=false;
</code>```

But i know that it isn't correct because nested query can return more than 1 column, how to modify this query to use where clause

答:
I don't use postgresql, but maybe something like this works:

```<code>select * from car_wash
where EXISTS (select ST_Within((select car_wash.lon_lat from car_wash),
                 (select ST_Buffer(ST_GeomFromText('POINT(65.3 323.2)'),20))) within
              WHERE within = true)
AND car_wash.was_deleted=false;
</code>```

If it doesn't work, I have a variant, so tell me when.

Body:
I'm a really bad in sql , my query is

 select * from car_wash where
           (select ST_Within((select car_wash.lon_lat from car_wash),(select ST_Buffer(ST_GeomFromText('POINT(65.3 323.2)'),20)))) = true
        AND car_wash.was_deleted=false;

But i know that it isn't correct because nested query can return more than 1 column, how to modify this query to use where clause

Body:
I don't use postgresql, but maybe something like this works:

select * from car_wash
where EXISTS (select ST_Within((select car_wash.lon_lat from car_wash),
                 (select ST_Buffer(ST_GeomFromText('POINT(65.3 323.2)'),20))) within
              WHERE within = true)
AND car_wash.was_deleted=false;

If it doesn't work, I have a variant, so tell me when.


问:
How to pass json from java to javascript function
I make from my database a json string and i want to pass it to my javascript function, and print it into a html table. I use angular to make it easy to print the table, but i don't know how can i sent the data from java to javascript.
These is what i tried in java.

```<code>public void jsonRetr (String numeRepo) throws SQLException {
    String sql = "SELECT * FROM " + numeRepo;
    PreparedStatement prStm = (PreparedStatement) conn.prepareStatement(sql);
    ResultSet rs = prStm.executeQuery(sql);
    ArrayList<PersoaneJSON> persoane = new ArrayList<PersoaneJSON>();

    while (rs.next()) {
        String id = rs.getString("id");
        String login_name = rs.getString("login_name");
        String email = rs.getString("email");
        String public_gits = rs.getString("public_gits");
        String Html_profile = rs.getString("Html_profile");
        String Avatar_URL = rs.getString("Avatar_URL");

        PersoaneJSON persoana = new PersoaneJSON(id, login_name, email, public_gits, Html_profile, Avatar_URL);
        persoane.add(persoana);
    }
    Gson gson = new Gson();
    String json = gson.toJson(persoane);
    }
</code>```

These is what i tried in javascript.

```<code>    var employeeApp = angular.module("EmployeeApp",[]);
    employeeApp.controller("empCtrl",function($scope){
    $scope.query = {}
    $scope.queryBy = '$'
    $scope.employees = [];
    $scope.orderProp="name";
  });
</code>```

答:
You have to use a Java Servlet with WebMethod, so call that method which can return a JSON object containing data.

Example
Java code:

ApplicationConfig.java

```<code>package example;
import java.util.Set;
import javax.ws.rs.core.Application;

@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application

  @Override
  public Set<Class<?>> getClasses() {
    Set<Class<?>> resources = new java.util.HashSet<>();
    resources.add(QueryResource.class);
    return resources;
  }
}
</code>```

QueryResource.java

```<code>package example;

@Path("query")
@Produces(MediaType.TEXT_PLAIN)
public class QueryResource {

    @GET
    @Path("/employee")
    public String jsonRetr() throws Exception {
        ..
        return json;
    }
}
</code>```

Now in js, inside your controller you can creater a function to connect to Servlet, passing $http Object to controller like $scope.

```<code>$http.get("http://localhost:8086/example/webresources/query/employee").success(function (data) {
                console.log(JSON.parse(data));
            }).error(function () {
                console.error('error');
            });
</code>```

In your web.xml you have to setup a configuration like this:

```<code><servlet-mapping>
    <servlet-name>RESTServlet</servlet-name>
    <url-pattern>/webresources/*</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>RESTServlet</servlet-name>
   <servletclass>org.glassfish.jersey.servlet.ServletContainer</servletclass>
        <init-param>
          <param-name>javax.ws.rs.Application</param-name>
          <param-value>example.ApplicationConfig</param-value>
        </init-param>
        </servlet>
</code>```

You need these dependencies:

```<code><dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.26-b01</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.26-b01</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>compile</scope>
 </dependency>
</code>```

Hope this helps

Body:
I make from my database a json string and i want to pass it to my javascript function, and print it into a html table. I use angular to make it easy to print the table, but i don't know how can i sent the data from java to javascript.
These is what i tried in java.

public void jsonRetr (String numeRepo) throws SQLException {
    String sql = "SELECT * FROM " + numeRepo;
    PreparedStatement prStm = (PreparedStatement) conn.prepareStatement(sql);
    ResultSet rs = prStm.executeQuery(sql);
    ArrayList<PersoaneJSON> persoane = new ArrayList<PersoaneJSON>();

    while (rs.next()) {
        String id = rs.getString("id");
        String login_name = rs.getString("login_name");
        String email = rs.getString("email");
        String public_gits = rs.getString("public_gits");
        String Html_profile = rs.getString("Html_profile");
        String Avatar_URL = rs.getString("Avatar_URL");

        PersoaneJSON persoana = new PersoaneJSON(id, login_name, email, public_gits, Html_profile, Avatar_URL);
        persoane.add(persoana);
    }
    Gson gson = new Gson();
    String json = gson.toJson(persoane);
    }

These is what i tried in javascript.

    var employeeApp = angular.module("EmployeeApp",[]);
    employeeApp.controller("empCtrl",function($scope){
    $scope.query = {}
    $scope.queryBy = '$'
    $scope.employees = [];
    $scope.orderProp="name";
  });

Body:
You have to use a Java Servlet with WebMethod, so call that method which can return a JSON object containing data.

Example
Java code:

ApplicationConfig.java

package example;
import java.util.Set;
import javax.ws.rs.core.Application;

@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application

  @Override
  public Set<Class<?>> getClasses() {
    Set<Class<?>> resources = new java.util.HashSet<>();
    resources.add(QueryResource.class);
    return resources;
  }
}

QueryResource.java

package example;

@Path("query")
@Produces(MediaType.TEXT_PLAIN)
public class QueryResource {

    @GET
    @Path("/employee")
    public String jsonRetr() throws Exception {
        ..
        return json;
    }
}

Now in js, inside your controller you can creater a function to connect to Servlet, passing $http Object to controller like $scope.

$http.get("http://localhost:8086/example/webresources/query/employee").success(function (data) {
                console.log(JSON.parse(data));
            }).error(function () {
                console.error('error');
            });

In your web.xml you have to setup a configuration like this:

<servlet-mapping>
    <servlet-name>RESTServlet</servlet-name>
    <url-pattern>/webresources/*</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>RESTServlet</servlet-name>
   <servletclass>org.glassfish.jersey.servlet.ServletContainer</servletclass>
        <init-param>
          <param-name>javax.ws.rs.Application</param-name>
          <param-value>example.ApplicationConfig</param-value>
        </init-param>
        </servlet>

You need these dependencies:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.26-b01</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.26-b01</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>compile</scope>
 </dependency>

Hope this helps


问:
Remove Black background from Alert Dialog Box - Android
I am working on an Android Application , Here I have created a custom dialog box , The dialog box was appearing on complete height of the device , but I wanted to leave margins from top and bottom , so I set margin using below code

```<code>  WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(alertDialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = Utility.convertDPtoPixel(400, screen);

    alertDialog.show();
    alertDialog.getWindow().setAttributes(lp);
</code>```

Above code worked perfectly, but the dialog appears with black surroundings.

Here is the screen shot:

Now I want to remove these black surroundings from the dialog box.

Here is the code of dialog box:

```<code>public void showDialog() {
    AlertDialog.Builder builder;
    final AlertDialog alertDialog;
    //final Dialog alertDialog;
    Context mContext;
    mContext = screen;
    LayoutInflater inflater = (LayoutInflater) LoginActivity.screen.getSystemService(LoginActivity.screen.LAYOUT_INFLATER_SERVICE);
    layout = inflater.inflate(R.layout.countrylist, null);
    LinearLayout rellayout = (LinearLayout) layout.findViewById(R.id.rellayout);

    RelativeLayout closeAcessCodeDialog = (RelativeLayout)layout.findViewById(R.id.closeAcessCodeDialog) ;

    ListView listview = (ListView) layout.findViewById(R.id.listview);
    listview.setAdapter(new CustomAdapter1(LoginActivity.screen, countryList));

    builder = new AlertDialog.Builder(LoginActivity.screen);
    builder.setView(layout);
    alertDialog = builder.create();
    alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(alertDialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = Utility.convertDPtoPixel(400, screen);

    alertDialog.show();
    alertDialog.getWindow().setAttributes(lp);

    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos,
                                long id) {
            countryName = idCountry.get(pos);
            System.out.println("Country code is: " + countryName);
            alertDialog.cancel();
            text.setText(countryList.get(pos));
        }
    });

    closeAcessCodeDialog.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.dismiss();
        }
    });

}
</code>```

countrylist.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#ffe264"
    app:cardCornerRadius="10dp"
    >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/rellayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_above="@+id/listview"
            android:gravity="center_vertical"
            >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Select your Country"
                android:textColor="#000"
                android:textSize="18sp"
                android:textStyle="bold"
                android:layout_centerInParent="true"
                />

            <RelativeLayout
                android:id="@+id/closeAcessCodeDialog"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_alignParentRight="true"
                android:gravity="center">

                <ImageButton
                    android:id="@+id/closeDialog"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:background="@drawable/close_country_dialog" />

            </RelativeLayout>
        </RelativeLayout>

        <ListView
            android:id="@+id/listview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:cacheColorHint="@android:color/transparent"
            android:divider="#e5e5e5"
            android:background="@drawable/list_bacground"
            android:dividerHeight="1px" />

    </LinearLayout>
</code>```

I visited many similar links over stackoverflow , but no one was helpfull .

答:
Hope this will help you a lot

I think its default theme color which is Black so you have to check the import of your AlertDialog it should be import android.support.v7.app.AlertDialog; and one more thing you should use custom color for Background like below

```<code>alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
</code>```

Body:
I am working on an Android Application , Here I have created a custom dialog box , The dialog box was appearing on complete height of the device , but I wanted to leave margins from top and bottom , so I set margin using below code

  WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(alertDialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = Utility.convertDPtoPixel(400, screen);

    alertDialog.show();
    alertDialog.getWindow().setAttributes(lp);

Above code worked perfectly, but the dialog appears with black surroundings.

Here is the screen shot:

Now I want to remove these black surroundings from the dialog box.

Here is the code of dialog box:

public void showDialog() {
    AlertDialog.Builder builder;
    final AlertDialog alertDialog;
    //final Dialog alertDialog;
    Context mContext;
    mContext = screen;
    LayoutInflater inflater = (LayoutInflater) LoginActivity.screen.getSystemService(LoginActivity.screen.LAYOUT_INFLATER_SERVICE);
    layout = inflater.inflate(R.layout.countrylist, null);
    LinearLayout rellayout = (LinearLayout) layout.findViewById(R.id.rellayout);

    RelativeLayout closeAcessCodeDialog = (RelativeLayout)layout.findViewById(R.id.closeAcessCodeDialog) ;

    ListView listview = (ListView) layout.findViewById(R.id.listview);
    listview.setAdapter(new CustomAdapter1(LoginActivity.screen, countryList));

    builder = new AlertDialog.Builder(LoginActivity.screen);
    builder.setView(layout);
    alertDialog = builder.create();
    alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(alertDialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = Utility.convertDPtoPixel(400, screen);

    alertDialog.show();
    alertDialog.getWindow().setAttributes(lp);

    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos,
                                long id) {
            countryName = idCountry.get(pos);
            System.out.println("Country code is: " + countryName);
            alertDialog.cancel();
            text.setText(countryList.get(pos));
        }
    });

    closeAcessCodeDialog.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.dismiss();
        }
    });

}

countrylist.xml

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#ffe264"
    app:cardCornerRadius="10dp"
    >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/rellayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_above="@+id/listview"
            android:gravity="center_vertical"
            >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Select your Country"
                android:textColor="#000"
                android:textSize="18sp"
                android:textStyle="bold"
                android:layout_centerInParent="true"
                />

            <RelativeLayout
                android:id="@+id/closeAcessCodeDialog"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_alignParentRight="true"
                android:gravity="center">

                <ImageButton
                    android:id="@+id/closeDialog"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:background="@drawable/close_country_dialog" />

            </RelativeLayout>
        </RelativeLayout>

        <ListView
            android:id="@+id/listview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:cacheColorHint="@android:color/transparent"
            android:divider="#e5e5e5"
            android:background="@drawable/list_bacground"
            android:dividerHeight="1px" />

    </LinearLayout>

I visited many similar links over stackoverflow , but no one was helpfull .

Body:
Hope this will help you a lot

I think its default theme color which is Black so you have to check the import of your AlertDialog it should be import android.support.v7.app.AlertDialog; and one more thing you should use custom color for Background like below

alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));


问:
How to change port with PHP and avoid Content or Connection error in Firefox?
I have a server administration page coded in PHP, and one of the features is to change the port on which the admin page is accessed. This is done with a number <input> field in a self-calling form, POST method. When the Submit button is clicked, the code takes the input number, writes it to the Nginx config file for the server as the port number to use, then runs the command to restart Nginx:

exec('sudo service nginx restart > /dev/null &');

The problem is that when this command is run, Firefox throws up a Content error. I have tried to work around the problem, changing to this block of code:

```<code>$newAPort = $_POST['admin-port'];
header('Content-Length: 0');
// Restart Nginx
exec('sudo service nginx restart > /dev/null &');
sleep(15);
$newURL = 'http://'.$_SERVER[HTTP_HOST].':'.$newAPort;
header('Location: '.$newURL);
</code>```

That's some progress, the Firefox error is now "Unable to connect", and the error shows the URL with the old port number. How can I redirect to the new port correctly? I thought the above block of code would do it but it doesn't.

答:
The discussion with CBroe led in the right direction, and after a few more searches on SO and elsewhere, I got a working solution, posted here in case it helps others. The block of code in my question is refactored like so:</p>

```<code>$rawHost = $_SERVER['HTTP_HOST']; // Get host
$onlyHost = explode(':', $rawHost)[0]; // Drop port num
$newAPort = $_POST['admin-port'];
header('Refresh:5; url=http://'.$onlyHost.':'.$newAPort, true, 301);
echo '<h3>Please wait a few seconds while the server updates...</h3>';
fastcgi_finish_request();
// Restart Nginx
exec('sudo service nginx restart > /dev/null &');
</code>```

Body:
I have a server administration page coded in PHP, and one of the features is to change the port on which the admin page is accessed. This is done with a number <input> field in a self-calling form, POST method. When the Submit button is clicked, the code takes the input number, writes it to the Nginx config file for the server as the port number to use, then runs the command to restart Nginx:

exec('sudo service nginx restart > /dev/null &');

The problem is that when this command is run, Firefox throws up a Content error. I have tried to work around the problem, changing to this block of code:

$newAPort = $_POST['admin-port'];
header('Content-Length: 0');
// Restart Nginx
exec('sudo service nginx restart > /dev/null &');
sleep(15);
$newURL = 'http://'.$_SERVER[HTTP_HOST].':'.$newAPort;
header('Location: '.$newURL);

That's some progress, the Firefox error is now "Unable to connect", and the error shows the URL with the old port number. How can I redirect to the new port correctly? I thought the above block of code would do it but it doesn't.

Body:
The discussion with CBroe led in the right direction, and after a few more searches on SO and elsewhere, I got a working solution, posted here in case it helps others. The block of code in my question is refactored like so:

$rawHost = $_SERVER['HTTP_HOST']; // Get host
$onlyHost = explode(':', $rawHost)[0]; // Drop port num
$newAPort = $_POST['admin-port'];
header('Refresh:5; url=http://'.$onlyHost.':'.$newAPort, true, 301);
echo '<h3>Please wait a few seconds while the server updates...</h3>';
fastcgi_finish_request();
// Restart Nginx
exec('sudo service nginx restart > /dev/null &');


问:
How to draw dashed polyline with android google map sdk v2?
I've looked through the documentation of polyline and there is no option to make it dashed.

Do anybody know how to draw dashed polyline with android google map sdk v2?

答:
Now in Polyline you can set the pattern to be Dash, Dot or Gap
simply apply the following</p>

```<code>public static final int PATTERN_DASH_LENGTH_PX = 20;
public static final int PATTERN_GAP_LENGTH_PX = 20;
public static final PatternItem DOT = new Dot();
public static final PatternItem DASH = new Dash(PATTERN_DASH_LENGTH_PX);
public static final PatternItem GAP = new Gap(PATTERN_GAP_LENGTH_PX);
public static final List<PatternItem> PATTERN_POLYGON_ALPHA = Arrays.asList(GAP, DASH);

 private void drawDashedLeg(GoogleMap googleMap, Route route) {
    PolylineOptions polyOptions = new PolylineOptions();
    polyOptions.color(ContextCompat.getColor(getContext(), R.color.coolgrey));
    polyOptions.addAll(route.getPoints());
    polyOptions.pattern(PATTERN_POLYGON_ALPHA);
    Polyline polyline = googleMap.addPolyline(polyOptions);
    polylines.add(polyline);
}
</code>```

Body:
Now in Polyline you can set the pattern to be Dash, Dot or Gap
simply apply the following

public static final int PATTERN_DASH_LENGTH_PX = 20;
public static final int PATTERN_GAP_LENGTH_PX = 20;
public static final PatternItem DOT = new Dot();
public static final PatternItem DASH = new Dash(PATTERN_DASH_LENGTH_PX);
public static final PatternItem GAP = new Gap(PATTERN_GAP_LENGTH_PX);
public static final List<PatternItem> PATTERN_POLYGON_ALPHA = Arrays.asList(GAP, DASH);

 private void drawDashedLeg(GoogleMap googleMap, Route route) {
    PolylineOptions polyOptions = new PolylineOptions();
    polyOptions.color(ContextCompat.getColor(getContext(), R.color.coolgrey));
    polyOptions.addAll(route.getPoints());
    polyOptions.pattern(PATTERN_POLYGON_ALPHA);
    Polyline polyline = googleMap.addPolyline(polyOptions);
    polylines.add(polyline);
}


问:
Make a placeholder div overlappable dynamically
I'm using a jQuery UI accordion as a menu on the right side of a page. However, there are occasions where the menu will be taller than the content on the left. Because of this, when expanding/contracting sections of the accordion, the scrollbar on the browser can grow/shrink when opening a section of the accordion. My thought was to have a div below the accordion which is the height that the accordion could possibly get to, and when the accordion expands it would just overlap it, thus not changing the scrollbar on the browser at all (hope that makes sense). Giving it a position: absolute and declaring the height and width seems to screw up the layout, placing it overlapping the footer but bleeding below it. Anyone have any ideas on how to make this work? If you need a more detailed example, I'll see what I can do to provide it, however, the site is locked down and I can't give out a username/password.</p>

答: You probably have a container around the menu and the content right? You could add a css min-height to the container which would be equal to the tallest that the menu could be in height</p>

ContentLicense: CC BY-SA 2.5


问:
Generate error at the end of the copy if any files are not copied
I have the one batch that does the copy of some files in the network, this copy updates the previous files by the newest case they already exist in the destination folder, however if any file is in use the system does not present the error message at the end only in the Moment you are trying to update the file.

At the moment I do not want to solve this file problem being in use, I would only like the command to report only at the end of the copy if there was an error in updating some file.

I put in the end the condition if "%errorlevel%" == "0" but this condition does not work if there were errors in the middle of the copy.

My command:

```<code>xcopy "C:\origin\." "C:\destination\" /c /d /e /h /i /k /r /y
</code>```

答:
What I suggest for you is to loop through the folder and check if each file is in use, and then you can write the name of that file to some type of log, maybe a .txt file to read later to show what could not be overwritten.

```<code>2>nul (
  >>FILE.EXT (call )
) && (echo file is not locked) || (echo file is locked)
</code>```

This code, which I found at StackOverflow (dbenham deserves all the credit for this) could be used to check if a file is locked. Replace FILE.EXT with your file name, preferably in a loop to easily check every file, and if the file is locked echo the file name to a (temporary) .txt file and once completed, loop through that text file to list the results.

An added benefit to this is, if you check for files in use before trying to overwrite, you could skip files you know you can't write to thus saving a bit of time per file.

Body:
I have the one batch that does the copy of some files in the network, this copy updates the previous files by the newest case they already exist in the destination folder, however if any file is in use the system does not present the error message at the end only in the Moment you are trying to update the file.

At the moment I do not want to solve this file problem being in use, I would only like the command to report only at the end of the copy if there was an error in updating some file.

I put in the end the condition if "%errorlevel%" == "0" but this condition does not work if there were errors in the middle of the copy.

My command:

xcopy "C:\origin\." "C:\destination\" /c /d /e /h /i /k /r /y

Body:
What I suggest for you is to loop through the folder and check if each file is in use, and then you can write the name of that file to some type of log, maybe a .txt file to read later to show what could not be overwritten.

2>nul (
  >>FILE.EXT (call )
) && (echo file is not locked) || (echo file is locked)

This code, which I found at StackOverflow (dbenham deserves all the credit for this) could be used to check if a file is locked. Replace FILE.EXT with your file name, preferably in a loop to easily check every file, and if the file is locked echo the file name to a (temporary) .txt file and once completed, loop through that text file to list the results.

An added benefit to this is, if you check for files in use before trying to overwrite, you could skip files you know you can't write to thus saving a bit of time per file.


问:
Android Firebase phone authentication INVALID_APP_CREDENTIAL:App validation failed
I am really new to android firebase and I have implemented the necessary libraries for Firebase Auth. I try putting a valid number, but the log says its:

```<code>W/JEJE: onVerificationFailed
com.google.firebase.FirebaseException: An internal error has occurred. [ INVALID_APP_CREDENTIAL:App validation failed ]
at com.google.android.gms.internal.nf.zzK(Unknown Source)
at com.google.android.gms.internal.og.zza(Unknown Source)
at com.google.android.gms.internal.oh.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
</code>```

Here is my code:

```<code>public class MainActivity extends AppCompatActivity {

    private static String mVerificationId;
    private static PhoneAuthProvider.ForceResendingToken mResendToken;
    private static FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText editText = (EditText) findViewById(R.id.phone);
        Button submit = (Button) findViewById(R.id.submit);

        final PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                Log.d("JEJE", "onVerificationCompleted:" + phoneAuthCredential);

                signInWithPhoneAuthCredential(phoneAuthCredential);
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                Log.w("JEJE", "onVerificationFailed", e);

                if (e instanceof FirebaseAuthInvalidCredentialsException) {
                    Log.d("JEJE", "INVALID REQUEST");
                } else if (e instanceof FirebaseTooManyRequestsException) {
                    Log.d("JEJE", "Too many Request");
                }
            }

            @Override
            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(s, forceResendingToken);
                Log.d("JEJE", "onCodeSent:" + s);

                mVerificationId = s;
                mResendToken = forceResendingToken;

            }
        };

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNum = editText.getText().toString();
                Toast.makeText(MainActivity.this, phoneNum, Toast.LENGTH_SHORT).show();
                verifyPhone(phoneNum,mCallBacks);
            }

        });
    }

    private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
        mAuth.signInWithCredential(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()){
                    FirebaseUser user = task.getResult().getUser();
                }else {
                    if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                        // The verification code entered was invalid
                    }
                }
            }
        });
    }

    public void verifyPhone(String phoneNumber, PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks){
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                "+639952874699",        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallback
    }

}
</code>```

please tell me whats wrong thanks..

答:
Adding SHA Certificate Fingerprint solves my problem. Well, Im fairly new to this but I managed to show output and I was able to received a sms verification.

For reference here are my codes:
https://github.com/coozgan/TestingPhoneAuth

Body:
I am really new to android firebase and I have implemented the necessary libraries for Firebase Auth. I try putting a valid number, but the log says its:

W/JEJE: onVerificationFailed
com.google.firebase.FirebaseException: An internal error has occurred. [ INVALID_APP_CREDENTIAL:App validation failed ]
at com.google.android.gms.internal.nf.zzK(Unknown Source)
at com.google.android.gms.internal.og.zza(Unknown Source)
at com.google.android.gms.internal.oh.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

Here is my code:

public class MainActivity extends AppCompatActivity {

    private static String mVerificationId;
    private static PhoneAuthProvider.ForceResendingToken mResendToken;
    private static FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText editText = (EditText) findViewById(R.id.phone);
        Button submit = (Button) findViewById(R.id.submit);

        final PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                Log.d("JEJE", "onVerificationCompleted:" + phoneAuthCredential);

                signInWithPhoneAuthCredential(phoneAuthCredential);
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                Log.w("JEJE", "onVerificationFailed", e);

                if (e instanceof FirebaseAuthInvalidCredentialsException) {
                    Log.d("JEJE", "INVALID REQUEST");
                } else if (e instanceof FirebaseTooManyRequestsException) {
                    Log.d("JEJE", "Too many Request");
                }
            }

            @Override
            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(s, forceResendingToken);
                Log.d("JEJE", "onCodeSent:" + s);

                mVerificationId = s;
                mResendToken = forceResendingToken;

            }
        };

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNum = editText.getText().toString();
                Toast.makeText(MainActivity.this, phoneNum, Toast.LENGTH_SHORT).show();
                verifyPhone(phoneNum,mCallBacks);
            }

        });
    }

    private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
        mAuth.signInWithCredential(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()){
                    FirebaseUser user = task.getResult().getUser();
                }else {
                    if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                        // The verification code entered was invalid
                    }
                }
            }
        });
    }

    public void verifyPhone(String phoneNumber, PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks){
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                "+639952874699",        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallback
    }

}

please tell me whats wrong thanks..


问:
How to make anchor move with respect to a block dragged in jsplumb?
I am trying to build a flowchart using drag and drop options. The user should be able to drag an element from one div and drop it to another.

Now I'm able to drag and drop. I have given an option such that on dropping the block, anchors should appear on them. And I'm able to link these blocks with connectors using js plumb.

I have given the draggable option for dropped blocks. The problem is whenever I drag connected blocks, the anchors' position does not change.

How to make a change such that whenever I drag any block, its anchor and connecting lines should also drag?

Here's my code:
jsPlumb.ready(function() {

```<code>var EndpointOptions = {
    setDragAllowedWhenFull: true,
    endpoint: "Dot",
    maxConnections: 10,

    paintStyle: {
        width: 21,
        height: 21,
        fillStyle: '#666',

    },
    isSource: true,
    connectorStyle: {
        strokeStyle: "#666"
    },
    isTarget: true,
    dropOptions: {
        drop: function(e, ui) {
            alert('drop!');
        }
    }

};

var count = 0;
var x = "";
//Make element draggable
$(".drag").draggable({
    helper: 'clone',
    cursor: 'move',
    tolerance: 'fit',
    revert: true
});

$(".droppable").droppable({
    accept: '.drag',
    activeClass: "drop-area",
    <!--  stop: function( event, ui ) {}, -->
    drop: function(e, ui) {
        if ($(ui.draggable)[0].id !== "") {

            x = ui.helper.clone();
            console.log("x" + JSON.stringify(x));
            ui.helper.remove();
            x.draggable({
                helper: 'original',
                cursor: 'move',
                containment: '.droppable',
                tolerance: 'fit',

                drop: function(event, ui) {
                    $(ui.draggable).remove();

                }
            });

            x.appendTo('.droppable');

            x.addClass('clg');
            $(".clg").each(function() {

                //alert("hello");
                jsPlumb.addEndpoint($(this), EndpointOptions);

            });

        }

        <!-- $(".clg").dblclick(function() { -->

        <!-- //alert("hello"); -->
        <!-- jsPlumb.addEndpoint($(this), EndpointOptions); -->

        <!-- });     -->
        jsPlumb.bind('connection', function(e) {
            jsPlumb.select(e).addOverlay(["Arrow", {
                foldback: 0.2,
                location: 0.65,
                width: 25
            }]);
        });
        console.log("out x" + JSON.stringify(x));

    }

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

答:
Here I'm generating an id for each block and adding endpoints based upon respective id.
Here is my changes:</p>

```<code>if(null == ui.draggable.attr('id')){
            if( ui.draggable.attr('class').indexOf('rule') != -1){
                clone.attr('id', 'rule_' + i);
                jsPlumb.addEndpoint(clone,{anchors: ["Left"]}, EndpointOptions);
            } else {
                clone.attr('id', 'event_' + i);
                jsPlumb.addEndpoint(clone, {anchors: ["Left"]}, EndpointOptions);
            }
i++;
</code>```

Body:
I am trying to build a flowchart using drag and drop options. The user should be able to drag an element from one div and drop it to another.

Now I'm able to drag and drop. I have given an option such that on dropping the block, anchors should appear on them. And I'm able to link these blocks with connectors using js plumb.

I have given the draggable option for dropped blocks. The problem is whenever I drag connected blocks, the anchors' position does not change.

How to make a change such that whenever I drag any block, its anchor and connecting lines should also drag?

Here's my code:
jsPlumb.ready(function() {

var EndpointOptions = {
    setDragAllowedWhenFull: true,
    endpoint: "Dot",
    maxConnections: 10,

    paintStyle: {
        width: 21,
        height: 21,
        fillStyle: '#666',

    },
    isSource: true,
    connectorStyle: {
        strokeStyle: "#666"
    },
    isTarget: true,
    dropOptions: {
        drop: function(e, ui) {
            alert('drop!');
        }
    }

};

var count = 0;
var x = "";
//Make element draggable
$(".drag").draggable({
    helper: 'clone',
    cursor: 'move',
    tolerance: 'fit',
    revert: true
});

$(".droppable").droppable({
    accept: '.drag',
    activeClass: "drop-area",

    drop: function(e, ui) {
        if ($(ui.draggable)[0].id !== "") {

            x = ui.helper.clone();
            console.log("x" + JSON.stringify(x));
            ui.helper.remove();
            x.draggable({
                helper: 'original',
                cursor: 'move',
                containment: '.droppable',
                tolerance: 'fit',

                drop: function(event, ui) {
                    $(ui.draggable).remove();

                }
            });

            x.appendTo('.droppable');

            x.addClass('clg');
            $(".clg").each(function() {

                //alert("hello");
                jsPlumb.addEndpoint($(this), EndpointOptions);

            });

        }

        jsPlumb.bind('connection', function(e) {
            jsPlumb.select(e).addOverlay(["Arrow", {
                foldback: 0.2,
                location: 0.65,
                width: 25
            }]);
        });
        console.log("out x" + JSON.stringify(x));

    }

});
});

Body:
Here I'm generating an id for each block and adding endpoints based upon respective id.
Here is my changes:

if(null == ui.draggable.attr('id')){
            if( ui.draggable.attr('class').indexOf('rule') != -1){
                clone.attr('id', 'rule_' + i);
                jsPlumb.addEndpoint(clone,{anchors: ["Left"]}, EndpointOptions);
            } else {
                clone.attr('id', 'event_' + i);
                jsPlumb.addEndpoint(clone, {anchors: ["Left"]}, EndpointOptions);
            }
i++;