问:
How to see what query is being passed to SQL from VB.net code
I have a GetUSerID function that runs a SQL query to get the UserID.The query works and returns a userID, but I don't think it is applying the WHERE condition. IT simply returns the highest UserID in the Users table. (I tested this by adding a new user (thus the highest userID changed) then logging in again- and the displayed userId increased top the NOW highest userID. I believe it is just doing "seclect userID from users" and grapping the first result and the "WHERE username=" is not being applied. I know the process I am using for getting the username works- as when I declare that as a varibale and just display it straight away- the username is correct- but it doesn't display the useRID that goes along with that username.

i'm looking for a way to see the exact query that is being passed to SQL while i'm running the app. Is there anyway in visual studio 2015 to run a SQL trace or something while in debug mode?

The code is...

Private Function GetUserID(userName As String) As Integer
    Dim userId As Integer
    Using con As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\BandDatabase.mdf;Integrated Security=True")
        Dim comm As New SqlCommand("select UserID from Users where username = userName", con)
        comm.Parameters.AddWithValue("userName", userName)
        comm.CommandType = CommandType.Text
        con.Open()
        Try
            Dim reader As SqlDataReader = comm.ExecuteReader()
            If reader.HasRows Then
                While (reader.Read)
                    userId = reader.GetInt32(0)
                End While
                reader.Close()
                Return userId
            Else
                'no user found
                Return -1
            End If
        Catch e As Exception
            Throw New Exception("An exception has occurred: " + e.Message)
        Finally
            con.Close()
        End Try
    End Using
End Function
```

<p>I know the username works, becuase I can call it this way...</p>

<pre class="lang-vb prettyprint-override"><code>userName = System.Web.HttpContext.Current.User.Identity.Name
</code>```

And it picks up the right name.

However, when I call my function in page load to display....(as shown below) it is only picking up the highest userID...

Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim userID As Integer = GetUserID(System.Web.HttpContext.Current.User.Identity.Name)

    'Displays a correct looking userID but not sure it is updating correctly
    lblStudent.Text = userID
End Sub
```

答:
To continue using parameters, use parameters properly. Note the added @

Dim comm As New SqlCommand("select UserID from Users where username = @userName", con)
comm.Parameters.AddWithValue("@userName", userName)
```

<p>Without the <code>@</code>, your query is simply in the form</p>

<pre class="lang-sql prettyprint-override"><code>SELECT A.B FROM A WHERE A.C = A.C
</code>```

which would just return the entire table, and in your code since you iterate the results and return the last one, it would just return UserID of the last row in the table.

Body:
I have a GetUSerID function that runs a SQL query to get the UserID.The query works and returns a userID, but I don't think it is applying the WHERE condition. IT simply returns the highest UserID in the Users table. (I tested this by adding a new user (thus the highest userID changed) then logging in again- and the displayed userId increased top the NOW highest userID. I believe it is just doing "seclect userID from users" and grapping the first result and the "WHERE username=" is not being applied. I know the process I am using for getting the username works- as when I declare that as a varibale and just display it straight away- the username is correct- but it doesn't display the useRID that goes along with that username.

i'm looking for a way to see the exact query that is being passed to SQL while i'm running the app. Is there anyway in visual studio 2015 to run a SQL trace or something while in debug mode?

The code is...

Private Function GetUserID(userName As String) As Integer
    Dim userId As Integer
    Using con As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\BandDatabase.mdf;Integrated Security=True")
        Dim comm As New SqlCommand("select UserID from Users where username = userName", con)
        comm.Parameters.AddWithValue("userName", userName)
        comm.CommandType = CommandType.Text
        con.Open()
        Try
            Dim reader As SqlDataReader = comm.ExecuteReader()
            If reader.HasRows Then
                While (reader.Read)
                    userId = reader.GetInt32(0)
                End While
                reader.Close()
                Return userId
            Else
                'no user found
                Return -1
            End If
        Catch e As Exception
            Throw New Exception("An exception has occurred: " + e.Message)
        Finally
            con.Close()
        End Try
    End Using
End Function

I know the username works, becuase I can call it this way...

userName = System.Web.HttpContext.Current.User.Identity.Name

And it picks up the right name.

However, when I call my function in page load to display....(as shown below) it is only picking up the highest userID...

Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim userID As Integer = GetUserID(System.Web.HttpContext.Current.User.Identity.Name)

    'Displays a correct looking userID but not sure it is updating correctly
    lblStudent.Text = userID
End Sub

Body:
To continue using parameters, use parameters properly. Note the added @

Dim comm As New SqlCommand("select UserID from Users where username = @userName", con)
comm.Parameters.AddWithValue("@userName", userName)

Without the @, your query is simply in the form

SELECT A.B FROM A WHERE A.C = A.C

which would just return the entire table, and in your code since you iterate the results and return the last one, it would just return UserID of the last row in the table.


来源: stackexchange

问:
How do I return a PDF document from TCPDF as a string?
The TCPDF documentation is very useful:

Output( $name = 'doc.pdf', $dest = 'I' )

Send the document to a given destination: string, local file or browser. In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.

The method first calls Close() if necessary to terminate the document.

... very useful indeed. It tells me that what I want is possible, but doesn’t begin to tell me how. Is there any documentation on the various options for $dest, what they are and what they do?

答:
I used tcpdf many times and saved it :). Just check:

I : send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.

D : send to the browser and force a file download with the name given by name.

F : save to a local server file with the name given by name.

S : return the document as a string (name is ignored).

FI : equivalent to F + I option

FD : equivalent to F + D option

E : return the document as base64 mime multi-part email attachment (RFC 2045)

ContentLicense: CC BY-SA 3.0


问:
Python CSV files: Printing all a user's details
I am writing a piece of code wherein my user does a quiz and all that information is stored in a CSV file. I then, in another program, have the user input a username and, if it matches, it will print the scores etc for that user. However, I had the same user do the quiz again and, instead of printing all the quizzes and scores that user did, it just prints the latest one.

To show:
My CSV file looks like this

Ser15 A Sci-Med

Ser15 C Sci-Med

These are the rows. I want my program to print all the quizzes and grades 'Ser15' had, but it just prints the lastest.
How do I make my program print all of them? Here is my code below...

```<code>     def Report1():
        found=False
        UserFind=input("Please enter a username")
        with open("Report.csv","r") as c:
            for row in c:
                details=row.split(",")
                if UserFind in details[0]:
                    found=True
                else:
                  pass
            if found==True:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
            else:
                print("User doesn't exist or wrong details...")
</code>```

This is my result:

```<code>Please enter a choice: 3
Please enter a usernameSer15
Ser15
C
Sci-Med

These are your user's details!
</code>```

As you can see it prints their latest information, not all of them...

This is part of my project so any help is much appreciated!

答:
the issue is simply that

```<code>        for row in c:
            details=row.split(",")
            if UserFind in details[0]:
                found=True
</code>```

doesn't stop the loop, so you'll get whatever is in the last row.

Just add break after found=True to stop at the matching row

Note that this linear search is not optimal if you want to perform several searches. Better build a dictionary out of csv rows:

```<code>import csv
with open("Report.csv","r") as c:
    cr=csv.reader(c)
    database = {row[0]:row[1:] for row in c}
</code>```

now query database with name in database or/and database.get(name) to get the rest of the info.

Body:
I am writing a piece of code wherein my user does a quiz and all that information is stored in a CSV file. I then, in another program, have the user input a username and, if it matches, it will print the scores etc for that user. However, I had the same user do the quiz again and, instead of printing all the quizzes and scores that user did, it just prints the latest one.

To show:
My CSV file looks like this

Ser15 A Sci-Med

Ser15 C Sci-Med

These are the rows. I want my program to print all the quizzes and grades 'Ser15' had, but it just prints the lastest.
How do I make my program print all of them? Here is my code below...

     def Report1():
        found=False
        UserFind=input("Please enter a username")
        with open("Report.csv","r") as c:
            for row in c:
                details=row.split(",")
                if UserFind in details[0]:
                    found=True
                else:
                  pass
            if found==True:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
            else:
                print("User doesn't exist or wrong details...")

This is my result:

Please enter a choice: 3
Please enter a usernameSer15
Ser15
C
Sci-Med

These are your user's details!

As you can see it prints their latest information, not all of them...

This is part of my project so any help is much appreciated!

Body:
the issue is simply that

        for row in c:
            details=row.split(",")
            if UserFind in details[0]:
                found=True

doesn't stop the loop, so you'll get whatever is in the last row.

Just add break after found=True to stop at the matching row

Note that this linear search is not optimal if you want to perform several searches. Better build a dictionary out of csv rows:

import csv
with open("Report.csv","r") as c:
    cr=csv.reader(c)
    database = {row[0]:row[1:] for row in c}

now query database with name in database or/and database.get(name) to get the rest of the info.


问:
Rails 5 query in related models

1st model is Encuesta it has many Preguntas

2nd model is Pregunta belongs to Encuesta, among other attributes it has one called date

In my PreguntasController I have my method index

```<code>def index
    @preguntas = @encuesta.preguntas
end
</code>```

So my variable @preguntas contains all the preguntas that belongs to a specific Encuesta, and this is working fine.

Now I want to select all the preguntas that belong to specific encuestas by "date"(attribute of Pregunta). this is my attempt, but it is not working:

```<code> @preguntas = @encuesta.preguntas.where(date: paramas[:date])
</code>```

How should I build the query correctly?? thanks

答:
First lets see something about Date. Working with dates could be a really extense
topic (and I know just the very basics) but you are trying to do (something like) this:

```<code>t = Pregunta.where(date: "2017-03-09")
  Pregunta Load (0.2ms)  SELECT "Preguntas".* FROM "Preguntas" WHERE "Preguntas"."date" = ?  [["date", "2017-03-09"]]
=> []
</code>```

If you check in your DB, you will probably find that your date is a timestamp. In you project directory type:

```<code>$ rails db
> select * from preguntas;
</code>```

Or any other select that shows you a record, and you will find that the value is in thie form:

```<code>2017-03-09 13:24:42.452593
</code>```

Now, is easier to see why you are not getting any record, is because you are missing the exact value of the field. Now try this,
with one value that you see in the select * from preguntas:

```<code># replace with one date of your DB!!!
t = Pregunta.where(date: "2017-03-09 13:24:42.480866")
  Pregunta Load (0.3ms)  SELECT "Preguntas".* FROM "Preguntas" WHERE "Preguntas"."date" = ?  [["date", "2017-03-09 13:24:42.480866"]]
=> [#<Pregunta:0x00000002d41258
id: 3,
field1: "now",
field2: "body",
... >]
</code>```

Finally, What you want to search (probably) are the dates in that particular day, so try something like:

```<code>t = Pregunta.where(date: @date.beginning_of_day..@date.end_of_day)
  Pregunta Load (0.4ms)  SELECT "Preguntas".* FROM "Preguntas" WHERE ("Preguntas"."date" BETWEEN '2017-03-09 03:00:00.000000' AND '2017-03-10 02:59:59.999999')
=> [#<Pregunta:0x000000021a2e88 id: 3, field1: "now", field1: "body", date: Thu, 09 Mar 2017 10:24:42 BRT -03:00>,
</code>```

Where @date is the day you need to search (created with something similar to @date = Date.new(2017, 3, 9))

Here you can see the Select Statement that it is a BETWEEN of the dates '2017-03-09 03:00:00.000000' and '2017-03-10 02:59:59.999999'

Title: Rails 5 query in related models

Body:
1st model is Encuesta it has many Preguntas

2nd model is Pregunta belongs to Encuesta, among other attributes it has one called date

In my PreguntasController I have my method index

def index
    @preguntas = @encuesta.preguntas
end

So my variable @preguntas contains all the preguntas that belongs to a specific Encuesta, and this is working fine.

Now I want to select all the preguntas that belong to specific encuestas by "date"(attribute of Pregunta). this is my attempt, but it is not working:

 @preguntas = @encuesta.preguntas.where(date: paramas[:date])

How should I build the query correctly?? thanks

Body:
First lets see something about Date. Working with dates could be a really extense
topic (and I know just the very basics) but you are trying to do (something like) this:

t = Pregunta.where(date: "2017-03-09")
  Pregunta Load (0.2ms)  SELECT "Preguntas".* FROM "Preguntas" WHERE "Preguntas"."date" = ?  [["date", "2017-03-09"]]
=> []

If you check in your DB, you will probably find that your date is a timestamp. In you project directory type:

$ rails db
> select * from preguntas;

Or any other select that shows you a record, and you will find that the value is in thie form:

2017-03-09 13:24:42.452593

Now, is easier to see why you are not getting any record, is because you are missing the exact value of the field. Now try this,
with one value that you see in the select * from preguntas:

# replace with one date of your DB!!!
t = Pregunta.where(date: "2017-03-09 13:24:42.480866")
  Pregunta Load (0.3ms)  SELECT "Preguntas".* FROM "Preguntas" WHERE "Preguntas"."date" = ?  [["date", "2017-03-09 13:24:42.480866"]]
=> [#<Pregunta:0x00000002d41258
id: 3,
field1: "now",
field2: "body",
... >]

Finally, What you want to search (probably) are the dates in that particular day, so try something like:

t = Pregunta.where(date: @date.beginning_of_day..@date.end_of_day)
  Pregunta Load (0.4ms)  SELECT "Preguntas".* FROM "Preguntas" WHERE ("Preguntas"."date" BETWEEN '2017-03-09 03:00:00.000000' AND '2017-03-10 02:59:59.999999')
=> [#<Pregunta:0x000000021a2e88 id: 3, field1: "now", field1: "body", date: Thu, 09 Mar 2017 10:24:42 BRT -03:00>,

Where @date is the day you need to search (created with something similar to @date = Date.new(2017, 3, 9))

Here you can see the Select Statement that it is a BETWEEN of the dates '2017-03-09 03:00:00.000000' and '2017-03-10 02:59:59.999999'


问:
Intellij IDEA debugger not working on Gradle Vert.X project
I'm developing a project using Vert.X framework using Gradle build tool. The problem I have is that breakpoints in IntelliJ simply doesn't work in any way I've tried.

Here is a run configuration for Vert.X which I use in Gradle:

```<code>run {
    args = [
            'run', mainVerticleName,
            "-conf", confPath,
            "--redeploy=$project.ext.watchForChange",
            "--launcher-class=$mainClassName",
            "--on-redeploy=$project.ext.doOnChange"
    ]
}
</code>```

So the deployment is done using Gradle, runs without any issues, IntelliJ debugger is connected, but breakpoints are not working.

The ways I've tried to make it work:

1) Gradle run configuration. Here is a run configuration for Intellij IDEA:

Tried to use a Remote debugging tool, started application with the following VM options:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000

But this didn't work.

2) Application configuration:

In this case I just can't start the project as I get the following message on the startup:

Error: Could not find or load main class io.vertx.core.Launcher

Vert.X Core library is in the classpath and configuration seems to be correct, so can't get were is the problem.

The source code of the project is public and can be found on GitHub:

vertx-gradle-architecture-starter

Vert.X version - 3.4.0. Gradle version - 3.4.1. IntelliJ IDEA version - 2016.3.5. OS - MacOS Sierra 10.12.3.

Interesting fact is when I deploy Vert.X from tests - breakpoints work. Any ideas why breakpoints doesn't work in cases I've described above?

答:
I had the exact same issue and following worked for me. redeploy, launcher and  on-redeploy options are not necessary in intelliJ. if we remove those the debug works after application is up.</p>

```<code>run {
    args = [
        'run', mainVerticleName,
        "-conf", confPath
    ]
}
</code>```

Body:
I'm developing a project using Vert.X framework using Gradle build tool. The problem I have is that breakpoints in IntelliJ simply doesn't work in any way I've tried.

Here is a run configuration for Vert.X which I use in Gradle:

run {
    args = [
            'run', mainVerticleName,
            "-conf", confPath,
            "--redeploy=$project.ext.watchForChange",
            "--launcher-class=$mainClassName",
            "--on-redeploy=$project.ext.doOnChange"
    ]
}

So the deployment is done using Gradle, runs without any issues, IntelliJ debugger is connected, but breakpoints are not working.

The ways I've tried to make it work:

1) Gradle run configuration. Here is a run configuration for Intellij IDEA:

Tried to use a Remote debugging tool, started application with the following VM options:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000

But this didn't work.

2) Application configuration:

In this case I just can't start the project as I get the following message on the startup:

Error: Could not find or load main class io.vertx.core.Launcher

Vert.X Core library is in the classpath and configuration seems to be correct, so can't get were is the problem.

The source code of the project is public and can be found on GitHub:

vertx-gradle-architecture-starter

Vert.X version - 3.4.0. Gradle version - 3.4.1. IntelliJ IDEA version - 2016.3.5. OS - MacOS Sierra 10.12.3.

Interesting fact is when I deploy Vert.X from tests - breakpoints work. Any ideas why breakpoints doesn't work in cases I've described above?

Body:
I had the exact same issue and following worked for me. redeploy, launcher and  on-redeploy options are not necessary in intelliJ. if we remove those the debug works after application is up.

run {
    args = [
        'run', mainVerticleName,
        "-conf", confPath
    ]
}


问:
C#/Visual Studio 2008 assigning "TopItem" property in "ListView" does not work
I am currently supporting a C# desktop application using Visual Studio 2008 (plan to upgrade soon).

I have a “List View” that gets populated with over 3000 items. Due to this large number of items, I created a “TextBox” in order for the user to start typing and have the matching “ListView” item scroll to the top of the “ListView”.

I have seen numerous posts on how this can be accomplished, the problem, the one that supposedly accomplishes this requirement does not work consistently. There are no “Groups” and property “ShowGroups” set to “false” for the "ListView". I read a “true” for the “ShowGroups” property may cause issues.

The code I found that should accomplish the task is as follows.

```<code>private void txtSearchCompany_TextChanged(object sender, EventArgs e)
{
  // Call FindItemWithText with the contents of the textbox.

   ListViewItem foundItem =
     lvCompany.FindItemWithText(txtSearchCompany.Text, true, 0, true);

   if (foundItem != null)
   {
      lvCompany.TopItem = foundItem;
   }
 }
</code>```

I have stepped through the code and I am baffled by the fact that the assignment statement only works occasionally.

For example, typing “02” into the “TextBox”, here is the break point at the assignment statement and the values before executing the assignment statement.

lvCompany.topItem {Text = "00000"}

foundItem         {Text = "02057"}

Before assignment statement

Now the values after the assignment statement.

lvCompany.topItem {Text = "01563"}

foundItem         {Text = "02057"}

After assignment statement

Why would “lvCompany.TopItem” be set to “01563”????

Here is the "ListView" after typing "02" in the "TextBox". The top item in the "ListView" does not have "02" in it. The "TopItem" is "01563".

ListView display

答:
Pretend for a second that you have a listview with 4 rows visible. You populate that listview with 10 rows of information (1 through 10). Since there are 4 rows showing, the listview can only ever show 1 through 7 at the top because 7,8,9 and 10 are needed to show a full listview when there are more than 4 total rows in it. Since 8 cannot move to the top, the TopItem will still contain what is actually showing in the top of the listview which in this case would be 7. So 7, 8, 9 and 10 would all show 7 as the TopItem because the listview cannot move the rows up any further. </p>

<p>The same goes for if the listview is not full or has only 4 items to begin with. So taking that same listivew, let's populate it with only 4 items. For this, TopItem will always return 1 as there is no other rows below 4 to shift up. </p>

Body:
I am currently supporting a C# desktop application using Visual Studio 2008 (plan to upgrade soon).

I have a “List View” that gets populated with over 3000 items. Due to this large number of items, I created a “TextBox” in order for the user to start typing and have the matching “ListView” item scroll to the top of the “ListView”.

I have seen numerous posts on how this can be accomplished, the problem, the one that supposedly accomplishes this requirement does not work consistently. There are no “Groups” and property “ShowGroups” set to “false” for the "ListView". I read a “true” for the “ShowGroups” property may cause issues.

The code I found that should accomplish the task is as follows.

private void txtSearchCompany_TextChanged(object sender, EventArgs e)
{
  // Call FindItemWithText with the contents of the textbox.

   ListViewItem foundItem =
     lvCompany.FindItemWithText(txtSearchCompany.Text, true, 0, true);

   if (foundItem != null)
   {
      lvCompany.TopItem = foundItem;
   }
 }

I have stepped through the code and I am baffled by the fact that the assignment statement only works occasionally.

For example, typing “02” into the “TextBox”, here is the break point at the assignment statement and the values before executing the assignment statement.

lvCompany.topItem {Text = "00000"}

foundItem         {Text = "02057"}

Before assignment statement

Now the values after the assignment statement.

lvCompany.topItem {Text = "01563"}

foundItem         {Text = "02057"}

After assignment statement

Why would “lvCompany.TopItem” be set to “01563”????

Here is the "ListView" after typing "02" in the "TextBox". The top item in the "ListView" does not have "02" in it. The "TopItem" is "01563".

ListView display

Body:
Pretend for a second that you have a listview with 4 rows visible. You populate that listview with 10 rows of information (1 through 10). Since there are 4 rows showing, the listview can only ever show 1 through 7 at the top because 7,8,9 and 10 are needed to show a full listview when there are more than 4 total rows in it. Since 8 cannot move to the top, the TopItem will still contain what is actually showing in the top of the listview which in this case would be 7. So 7, 8, 9 and 10 would all show 7 as the TopItem because the listview cannot move the rows up any further.

The same goes for if the listview is not full or has only 4 items to begin with. So taking that same listivew, let's populate it with only 4 items. For this, TopItem will always return 1 as there is no other rows below 4 to shift up.


答:
The documentation on the project’s own site is lacking, but the documentation for the Ruby gem has the information we need:

@param string :dest

Destination where to send the document. It can take one of the following values:

I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the “Save as” option on the link generating the PDF.

D: send to the browser and force a file download with the name given by name.

F: save to a local server file with the name given by name.

S: return the document as a string. name is ignored.

FI: equivalent to F + I option

FD: equivalent to F + D option

So to return it as a string, we want Output('ignored.pdf', 'S');.

Title: How do I return a PDF document from TCPDF as a string?

Body:
The TCPDF documentation is very useful:

Output( $name = 'doc.pdf', $dest = 'I' )

Send the document to a given destination: string, local file or browser. In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.

The method first calls Close() if necessary to terminate the document.

... very useful indeed. It tells me that what I want is possible, but doesn’t begin to tell me how. Is there any documentation on the various options for $dest, what they are and what they do?


问:
code design in spring mvc controller
Hi just want to ask a design question in Spring MVC Controller.
A request URL will have multiple parameters, eg. type=v1&par2=v2&par3=v3&par4=v4. Among the 4 parameters, 'type' will decide the transaction mode and the other parameters will be the input for each transaction.

How will you organize the controller code?
Traditionally, you may write something like the following,

```<code>if (type.equals('1'))
{
   callMode1(par2,par3, par4);
}
else if (type.equals('2')
{
    callMode2(par2, par3, par4);
}
else if (type.equals('3'))
{
    callMode3(par2, par3, par4);
}
</code>```

callMode1 - callMode2 are private methods in the controller.

Just wondering if there is any better way to write the code here?

Thanks in advance!

答:
I find this as a good use case for an enum:

```<code>public enum Type {
    T1 {
        @Override
        public void call(String par1, String par2, String par3) {
            callMode1(par1, par2, par3);
        }
    },
    T2 {
        @Override
        public void call(String par1, String par2, String par3) {
            callMode2(par1, par2, par3);
        }
    },
    T3 {
        @Override
        public void call(String par1, String par2, String par3) {
            callMode3(par1, par2, par3);
        }
    },

    public abstract void call(String par1, String par2, String par3);

    public static Type valueOfNumber(String number) {
        return valueOf("T" + number);
    }

}
</code>```

Then, your controller will simply get the corresponding Type and invoke call on it:

```<code>Type t = Type.valueOfNumber(type);
t.call(par1, par2, par3);
</code>```

ContentLicense: CC BY-SA 2.5

Title: code design in spring mvc controller

Body:
Hi just want to ask a design question in Spring MVC Controller.
A request URL will have multiple parameters, eg. type=v1&par2=v2&par3=v3&par4=v4. Among the 4 parameters, 'type' will decide the transaction mode and the other parameters will be the input for each transaction.

How will you organize the controller code?
Traditionally, you may write something like the following,

if (type.equals('1'))
{
   callMode1(par2,par3, par4);
}
else if (type.equals('2')
{
    callMode2(par2, par3, par4);
}
else if (type.equals('3'))
{
    callMode3(par2, par3, par4);
}

callMode1 - callMode2 are private methods in the controller.

Just wondering if there is any better way to write the code here?

Thanks in advance!

Body:
I find this as a good use case for an enum:

public enum Type {
    T1 {
        @Override
        public void call(String par1, String par2, String par3) {
            callMode1(par1, par2, par3);
        }
    },
    T2 {
        @Override
        public void call(String par1, String par2, String par3) {
            callMode2(par1, par2, par3);
        }
    },
    T3 {
        @Override
        public void call(String par1, String par2, String par3) {
            callMode3(par1, par2, par3);
        }
    },

    public abstract void call(String par1, String par2, String par3);

    public static Type valueOfNumber(String number) {
        return valueOf("T" + number);
    }

}

Then, your controller will simply get the corresponding Type and invoke call on it:

Type t = Type.valueOfNumber(type);
t.call(par1, par2, par3);


问:
Stop KeyboardInterrupt reaching batch file processor
I'm writing some code in Python 3 on Windows that looks like this:

```<code>try:
    do something that takes a long time
    (training a neural network in TensorFlow, as it happens)
except KeyboardInterrupt:
    print('^C')
print a summary of results
still useful even if the training was cut short early
</code>```

This works perfectly if run directly from the console with python foo.py.

However, if the call to Python was within a batch file, it ends up doing all the above but then still spamming the console with the 'terminate batch job' prompt.

Is there a way to stop that happening? By fully eating the ^C within Python, jumping all the way out of the batch file or otherwise?

答:
Use the break (More info here) command in the batch file, which will disable CTRL+C halting the file

EDIT: According to this site of the break command

Newer versions of Windows (Windows ME, Windows 2000, Windows XP, and higher) only include this command for backward compatibility and turning the break off has no effect.

I personally tested this, and can confirm, I will edit when I find a workaround

EDIT #2: If you could have a second batch script that runs start "" /b /wait cmd /c "yourfile.bat" although, this is known to cause glitches with other nested batch files

The flag to disable Ctrl+C is inherited by child processes, so Python will no longer raise a KeyboardInterrupt. Plus we still have bugs here in Python if reading from the console gets interrupted by Ctrl+C without getting a SIGINT from the CRT. The Python script should manually enable Ctrl+C via ctypes. Use import ctypes; kernel32 = ctypes.WinDLL('kernel32', use_last_error=True); success = kernel32.SetConsoleCtrlHandler(None, False)

EDIT #3 As pointed by Eryksyn (in the comments), you can use cytpes to ENABLE it;

```<code>import ctypes;
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True); success = kernel32.SetConsoleCtrlHandler(None, False)
</code>```

EDIT #4: I think I found it, try this (Although it may not work) Can you use the threading import?

```<code>import time
from threading import Thread

def noInterrupt():
    for i in xrange(4):
        print i
        time.sleep(1)

a = Thread(target=noInterrupt)
a.start()
a.join()
print "done"
</code>```

Body:
I'm writing some code in Python 3 on Windows that looks like this:

try:
    do something that takes a long time
    (training a neural network in TensorFlow, as it happens)
except KeyboardInterrupt:
    print('^C')
print a summary of results
still useful even if the training was cut short early

This works perfectly if run directly from the console with python foo.py.

However, if the call to Python was within a batch file, it ends up doing all the above but then still spamming the console with the 'terminate batch job' prompt.

Is there a way to stop that happening? By fully eating the ^C within Python, jumping all the way out of the batch file or otherwise?

Body:
Use the break (More info here) command in the batch file, which will disable CTRL+C halting the file

EDIT: According to this site of the break command

Newer versions of Windows (Windows ME, Windows 2000, Windows XP, and higher) only include this command for backward compatibility and turning the break off has no effect.

I personally tested this, and can confirm, I will edit when I find a workaround

EDIT #2: If you could have a second batch script that runs start "" /b /wait cmd /c "yourfile.bat" although, this is known to cause glitches with other nested batch files

The flag to disable Ctrl+C is inherited by child processes, so Python will no longer raise a KeyboardInterrupt. Plus we still have bugs here in Python if reading from the console gets interrupted by Ctrl+C without getting a SIGINT from the CRT. The Python script should manually enable Ctrl+C via ctypes. Use import ctypes; kernel32 = ctypes.WinDLL('kernel32', use_last_error=True); success = kernel32.SetConsoleCtrlHandler(None, False)

EDIT #3 As pointed by Eryksyn (in the comments), you can use cytpes to ENABLE it;

import ctypes;
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True); success = kernel32.SetConsoleCtrlHandler(None, False)

EDIT #4: I think I found it, try this (Although it may not work) Can you use the threading import?

import time
from threading import Thread

def noInterrupt():
    for i in xrange(4):
        print i
        time.sleep(1)

a = Thread(target=noInterrupt)
a.start()
a.join()
print "done"


问:
Watching the output of a bash script
I'm trying to use watch to look at the output of a shell script, executing /bin/bash and holding the script itself in a heredoc.

The booger is only executing once though. It gives the correct output, then watch refreshes and the screen goes blank. Upon exiting watch there are no errors listed.

I can't figure out where the issue is since it's getting difficult to debug with watch > bash > heredoc > ugly code.

The good news is that ugly code in the heredoc works fine.

```<code>function show_users {

    [[ -z $1 ]] && watchtime=1 || watchtime=$1
    [[ -z $2 ]] && export userToShow="mydefaultuser" || export userToShow=$2

    echo "Setting up watch for user ${userToShow}"

    watch -n $watchtime --no-title /bin/bash <<-'EOF'
        #Show finger results of requested user
        finger ${userToShow}

        #show list of users su'd into requested user
        echo "************************************************************************************"
        echo "users logged in as ${userToShow}"

        #get the parent PIDS of any process belonging to requested user
        #into a list that can be read by grep
        parentPIDs=$(ps -ef | grep "su - ${userToShow}" | grep -v 'grep\|finger' | awk 'NR>1{printf " %s \\|",parentpid}{parentpid=$3}END{printf " %s\n", parentpid}')

        #get usersnames associated to those parent PIDS
        parentUsers=$(ps -ef | grep "${parentPIDs}" | grep -v "grep\|${userToShow}" | awk '{print $1}' | sort | uniq)

        #finger each of these users and get their full name
        while IFS= read -r line ; do
            printf "%s: " $line
            parentName=$(finger $line | awk -F":" 'NR==1{print $3}')
            echo $parentName
        done <<< "${parentUsers}"

        #show tree for all proceses being run by requested user up to root.
        echo "************************************************************************************"
        ps -ef --forest | egrep -e "sshd:|-ksh|$userToShow" | grep -v grep | awk 'root==1{print ""} NR>1{print line} {line=$0;root=($1=="root") ? 1 : 0}'
    EOF
}
</code>```

called like:

```<code>show_users 2 "username"
</code>```

答:
watch repeatedly runs a specified command with its arguments.
The heredoc, and more generally the effect of redirect operators are not part of the command.
So watch cannot re-generate the heredoc.
And once the heredoc is consumed by the first run of bash,
well, there will be nothing left for the second.

There's a dirty hack you could try at the bottom of this answer.
But my recommended solution is to save the content of the heredoc in a temporary file.
That's reasonably simple to do and robust.

Save the file in a temporary file, created by mktemp.
Setup a trap to catch the interrupt and perhaps other signals to make sure the temporary file gets cleaned up.
Run watch bash "$tmpfile".
This is simple and will work.

Dirty "solution" with (severe) caveats, don't do this!

You could put a script in a variable and then run with watch like this:

```<code>watch "bash -c '$var'"
</code>```

Or like this:

```<code>watch "bash -c \"$var\""
</code>```

But the severe caveat is that the first version will break if var contains ', and the second version will break if var contains ".
So these would work with only the most basic kind of scripts,
and certainly not the one in your example.

This is clearly not an option, I just added here for the sake of completeness.

Title: Watching the output of a bash script

Body:
I'm trying to use watch to look at the output of a shell script, executing /bin/bash and holding the script itself in a heredoc.

The booger is only executing once though. It gives the correct output, then watch refreshes and the screen goes blank. Upon exiting watch there are no errors listed.

I can't figure out where the issue is since it's getting difficult to debug with watch > bash > heredoc > ugly code.

The good news is that ugly code in the heredoc works fine.

function show_users {

    [[ -z $1 ]] && watchtime=1 || watchtime=$1
    [[ -z $2 ]] && export userToShow="mydefaultuser" || export userToShow=$2

    echo "Setting up watch for user ${userToShow}"

    watch -n $watchtime --no-title /bin/bash <<-'EOF'
        #Show finger results of requested user
        finger ${userToShow}

        #show list of users su'd into requested user
        echo "************************************************************************************"
        echo "users logged in as ${userToShow}"

        #get the parent PIDS of any process belonging to requested user
        #into a list that can be read by grep
        parentPIDs=$(ps -ef | grep "su - ${userToShow}" | grep -v 'grep\|finger' | awk 'NR>1{printf " %s \\|",parentpid}{parentpid=$3}END{printf " %s\n", parentpid}')

        #get usersnames associated to those parent PIDS
        parentUsers=$(ps -ef | grep "${parentPIDs}" | grep -v "grep\|${userToShow}" | awk '{print $1}' | sort | uniq)

        #finger each of these users and get their full name
        while IFS= read -r line ; do
            printf "%s: " $line
            parentName=$(finger $line | awk -F":" 'NR==1{print $3}')
            echo $parentName
        done <<< "${parentUsers}"

        #show tree for all proceses being run by requested user up to root.
        echo "************************************************************************************"
        ps -ef --forest | egrep -e "sshd:|-ksh|$userToShow" | grep -v grep | awk 'root==1{print ""} NR>1{print line} {line=$0;root=($1=="root") ? 1 : 0}'
    EOF
}

called like:

show_users 2 "username"

Body:
watch repeatedly runs a specified command with its arguments.
The heredoc, and more generally the effect of redirect operators are not part of the command.
So watch cannot re-generate the heredoc.
And once the heredoc is consumed by the first run of bash,
well, there will be nothing left for the second.

There's a dirty hack you could try at the bottom of this answer.
But my recommended solution is to save the content of the heredoc in a temporary file.
That's reasonably simple to do and robust.

Save the file in a temporary file, created by mktemp.
Setup a trap to catch the interrupt and perhaps other signals to make sure the temporary file gets cleaned up.
Run watch bash "$tmpfile".
This is simple and will work.

Dirty "solution" with (severe) caveats, don't do this!

You could put a script in a variable and then run with watch like this:

watch "bash -c '$var'"

Or like this:

watch "bash -c \"$var\""

But the severe caveat is that the first version will break if var contains ', and the second version will break if var contains ".
So these would work with only the most basic kind of scripts,
and certainly not the one in your example.

This is clearly not an option, I just added here for the sake of completeness.


问:
how to paste something in textbox without overwriting
hi i created a little app for my business. Now i have a little problem.
I want to paste one code of textbox2 to textbox4 without erasing previous data of textbox4..

I tried these codes but it doesn't work

for copy==>

```<code> private void button3_Click(object sender, EventArgs e)
    {
        Clipboard.SetText(textBox2.Text);
    }
</code>```

for paste ===>

```<code> private void button6_Click(object sender, EventArgs e)
    {
        textBox4.Text =Clipboard.GetText()+Environment.NewLine;
    }
</code>```

this paste code is overwriting. I want a method for paste button to keep previous data when pasting new data..

Help me plz

答:
Because you're setting the value of the text:

```<code>textBox4.Text = ...
</code>```

If you only want to append the value, use the += operator:

```<code>textBox4.Text += ...
</code>```

Or, more explicitly:

```<code>textBox4.Text = textBox4.Text + ...
</code>```

Body:
hi i created a little app for my business. Now i have a little problem.
I want to paste one code of textbox2 to textbox4 without erasing previous data of textbox4..

I tried these codes but it doesn't work

for copy==>

 private void button3_Click(object sender, EventArgs e)
    {
        Clipboard.SetText(textBox2.Text);
    }

for paste ===>

 private void button6_Click(object sender, EventArgs e)
    {
        textBox4.Text =Clipboard.GetText()+Environment.NewLine;
    }

this paste code is overwriting. I want a method for paste button to keep previous data when pasting new data..

Help me plz

Body:
Because you're setting the value of the text:

textBox4.Text = ...

If you only want to append the value, use the += operator:

textBox4.Text += ...

Or, more explicitly:

textBox4.Text = textBox4.Text + ...


问:
Run a shell file in java
In Java you can call a shell file like this:

```<code>public class Shell {
    private static Shell rootShell = null;
    private final Process proc;
    private final OutputStreamWriter writer;

    private Shell(String cmd) throws IOException {
        this.proc = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
    }

    public void cmd(String command)  {
        try {
            writer.write(command+'\n');
            writer.flush();
        } catch (IOException e) {   }
    }

    public void close() {
        try {
            if (writer != null) {
                writer.close();
                if(proc != null) {
                    proc.destroy();
                }
            }
        } catch (IOException ignore) {}
    }

    public static void exec(String command) {
        Shell.get().cmd(command);
    }

    public static Shell get() {
        if (Shell.rootShell == null) {
            while (Shell.rootShell == null) {
                try {
                    Shell.rootShell = new Shell("su"); //Open with Root Privileges
                } catch (IOException e) {   }
            }
        }
        return Shell.rootShell;
    }
}

Shell.exec("echo " + bt.getLevel() + " > "+ flashfile);
</code>```

right.

but I have a shell which giving an argument after executing it.

how can I pass that argument?  I don't want user type anything to run this shell file. in another word, I want to fully automate a shell file.

答:
If you want to automate a shell file with a Java programme, this can be done. You could even pipe a series of commands to this programme saved in a file and executing these as a batch.

You can execute commands batches of commands from like this:

```<code>java -cp experiments-1.0-SNAPSHOT.jar ConsoleReader < commands.txt
</code>```

commands.txt is a file with a series of commands:

```<code>cmd /k date
cmd /k dir
netstat
ipconfig
</code>```

Or you can with the same programme allow the user to execute commands on the command line.

Below you can find a sample programme which you can compile and be run in the above described manner.

What does it do?

It hooks a java.util.Scanner to the console input and consumes each line.

Then it spawns two threads which listen to the error and input streams and write out either to stderr or stdin.

Empty lines on the console are ignored

If you type "read " it will execute the commands on that file.

Source:

```<code>public class ConsoleReader {

    public static void main(String[] args) throws IOException, DatatypeConfigurationException {
        try(Scanner scanner = new Scanner(new BufferedInputStream(System.in), "UTF-8")) {
            readFromScanner(scanner);
        }
    }

    private static final Pattern FILE_INPUT_PAT = Pattern.compile("read\\s*([^\\s]+)");

    private static void readFromScanner(Scanner scanner) {
        while (scanner.hasNextLine()) {
            try {
                String command = scanner.nextLine();
                if(command != null && !command.trim().isEmpty()) {
                    command = command.trim();
                    if("exit".equals(command)) {
                        break; // exit shell
                    }
                    else if(command.startsWith("read")) { // read from file whilst in the shell.
                        readFile(command);
                    }
                    else {
                        Process p = Runtime.getRuntime().exec(command);
                        Thread stdout = readFromStream(p.getInputStream(), System.out, "in");
                        Thread stderr = readFromStream(p.getErrorStream(), System.err, "err");
                        stdout.join(200);
                        stderr.join(200);
                    }
                }
            }
            catch(Exception e) {
                Logger.getLogger("ConsoleReader").log(Level.SEVERE, String.format("Failed to execute command %s", e));
            }
        }
    }

    private static void readFile(String command) throws FileNotFoundException {
        Matcher m = FILE_INPUT_PAT.matcher(command);
        if(m.matches()) {
            String file = m.group(1);
            File f = new File(file);
            if (f.exists()) {
                try (Scanner subScanner = new Scanner(f)) {
                    readFromScanner(subScanner);
                }
            }
        }
        else {
            System.err.printf("Oops, could not find '%s'%n", command);
        }
    }

    private static Thread readFromStream(InputStream stdin, PrintStream out, String name) throws IOException {
        Thread thread = new Thread(() -> {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(stdin))) {
                String line;
                while ((line = in.readLine()) != null) {
                    out.println(line);
                }
            } catch (IOException e) {
                Logger.getLogger("ConsoleReader").log(Level.SEVERE, "Failed to read from stream.", e);
            }
        }, name);
        thread.setDaemon(true);
        thread.start();
        return thread;
    }
}
</code>```

Title: Run a shell file in java

Body:
In Java you can call a shell file like this:

public class Shell {
    private static Shell rootShell = null;
    private final Process proc;
    private final OutputStreamWriter writer;

    private Shell(String cmd) throws IOException {
        this.proc = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
    }

    public void cmd(String command)  {
        try {
            writer.write(command+'\n');
            writer.flush();
        } catch (IOException e) {   }
    }

    public void close() {
        try {
            if (writer != null) {
                writer.close();
                if(proc != null) {
                    proc.destroy();
                }
            }
        } catch (IOException ignore) {}
    }

    public static void exec(String command) {
        Shell.get().cmd(command);
    }

    public static Shell get() {
        if (Shell.rootShell == null) {
            while (Shell.rootShell == null) {
                try {
                    Shell.rootShell = new Shell("su"); //Open with Root Privileges
                } catch (IOException e) {   }
            }
        }
        return Shell.rootShell;
    }
}

Shell.exec("echo " + bt.getLevel() + " > "+ flashfile);

right.

but I have a shell which giving an argument after executing it.

how can I pass that argument?  I don't want user type anything to run this shell file. in another word, I want to fully automate a shell file.

Body:
If you want to automate a shell file with a Java programme, this can be done. You could even pipe a series of commands to this programme saved in a file and executing these as a batch.

You can execute commands batches of commands from like this:

java -cp experiments-1.0-SNAPSHOT.jar ConsoleReader < commands.txt

commands.txt is a file with a series of commands:

cmd /k date
cmd /k dir
netstat
ipconfig

Or you can with the same programme allow the user to execute commands on the command line.

Below you can find a sample programme which you can compile and be run in the above described manner.

What does it do?

It hooks a java.util.Scanner to the console input and consumes each line.

Then it spawns two threads which listen to the error and input streams and write out either to stderr or stdin.

Empty lines on the console are ignored

If you type "read " it will execute the commands on that file.

Source:

public class ConsoleReader {

    public static void main(String[] args) throws IOException, DatatypeConfigurationException {
        try(Scanner scanner = new Scanner(new BufferedInputStream(System.in), "UTF-8")) {
            readFromScanner(scanner);
        }
    }

    private static final Pattern FILE_INPUT_PAT = Pattern.compile("read\\s*([^\\s]+)");

    private static void readFromScanner(Scanner scanner) {
        while (scanner.hasNextLine()) {
            try {
                String command = scanner.nextLine();
                if(command != null && !command.trim().isEmpty()) {
                    command = command.trim();
                    if("exit".equals(command)) {
                        break; // exit shell
                    }
                    else if(command.startsWith("read")) { // read from file whilst in the shell.
                        readFile(command);
                    }
                    else {
                        Process p = Runtime.getRuntime().exec(command);
                        Thread stdout = readFromStream(p.getInputStream(), System.out, "in");
                        Thread stderr = readFromStream(p.getErrorStream(), System.err, "err");
                        stdout.join(200);
                        stderr.join(200);
                    }
                }
            }
            catch(Exception e) {
                Logger.getLogger("ConsoleReader").log(Level.SEVERE, String.format("Failed to execute command %s", e));
            }
        }
    }

    private static void readFile(String command) throws FileNotFoundException {
        Matcher m = FILE_INPUT_PAT.matcher(command);
        if(m.matches()) {
            String file = m.group(1);
            File f = new File(file);
            if (f.exists()) {
                try (Scanner subScanner = new Scanner(f)) {
                    readFromScanner(subScanner);
                }
            }
        }
        else {
            System.err.printf("Oops, could not find '%s'%n", command);
        }
    }

    private static Thread readFromStream(InputStream stdin, PrintStream out, String name) throws IOException {
        Thread thread = new Thread(() -> {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(stdin))) {
                String line;
                while ((line = in.readLine()) != null) {
                    out.println(line);
                }
            } catch (IOException e) {
                Logger.getLogger("ConsoleReader").log(Level.SEVERE, "Failed to read from stream.", e);
            }
        }, name);
        thread.setDaemon(true);
        thread.start();
        return thread;
    }
}


问:
Why C++ does not move to a 'unversioned model' like HTML/HTML5?
First, i must say that i write this from the bottom of my dark, envious heart:

After reading this: http://blog.whatwg.org/html-is-the-new-html5

i wonder, what is up that C++ has become so fosilized that they will take 10 years to get a new standard.

I mean, embedded/ancient platforms don't even notice when a new release of the C++ standard come up because guess what? they are constrained by the platform and compiler vendors, so they for the most part, won't be able to take advantage of the new features anyway. So all this weight dragging seems more self-immolation than desire or respect for backward compatibility and such and such

答: Beyond @Konrad's answer, C++ is an ISO standard, and therefore has to deal with all the bureaucratic stuff that all ISO standards require. That takes time. HTML is not an ISO standard, and therefore has a much easier time creating a new standard.</p>


问:
okHttp3 response.code() won't return 304
I'm using OkHttp3 on an android app for listening to web services, keeping the question basic, the following is what does the trik:

```<code>try(Response response = client.newCall(request).execute()) {
    responseBody = response.body().string();
    responseHeaders = response.headers();

    serviceContent = responseBody; // store response content in class' property
    serviceHeaders = responseHeaders; // store response headers in class' property
    serviceStatusCode = response.code(); // store response status code in class' property
} catch(IOException e) {
    e.printStackTrace();
}
</code>```

then in my activity I'm using serviceStatusCode for handling the web service response in different ways.

One of the services I'm listening to is SkyScanner which may return 304 indicating that the response has already been created and you must use the previous response stored locally.

I'm doing everything ok but when SkyScanner returns 304 I'm unable to catch it, this is the way I use to handle the response based on it's code in my activity:

```<code>switch(statusCode) {
    case 304: {
        // Get data from local DB
        break;
    }
    case 200: {}
    // And so on
}
</code>```

The problem is that statusCode is 200 (filled by response.code()) even when Fiddler says it is 304. Why response.code() won't return 304 if a 304 is returned?

答:
Have a look here (section 'Reduce processing'):

On a 304 status, Retrofit2 and OkHttp3 will pretend this response was
  equal to the last response; the cached response is returned. To notice
  the 304, check the raw response code:

```<code>if (response.isSuccessful() &&
    response.raw().networkResponse() != null &&
    response.raw().networkResponse().code() ==
           HttpURLConnection.HTTP_NOT_MODIFIED) {
    // not modified, no need to do anything.
    return;
}

// parse response here
</code>```

Getting the normal (not raw) response code would give you the cached
  status code, probably 200 OK

Body:
I'm using OkHttp3 on an android app for listening to web services, keeping the question basic, the following is what does the trik:

try(Response response = client.newCall(request).execute()) {
    responseBody = response.body().string();
    responseHeaders = response.headers();

    serviceContent = responseBody; // store response content in class' property
    serviceHeaders = responseHeaders; // store response headers in class' property
    serviceStatusCode = response.code(); // store response status code in class' property
} catch(IOException e) {
    e.printStackTrace();
}

then in my activity I'm using serviceStatusCode for handling the web service response in different ways.

One of the services I'm listening to is SkyScanner which may return 304 indicating that the response has already been created and you must use the previous response stored locally.

I'm doing everything ok but when SkyScanner returns 304 I'm unable to catch it, this is the way I use to handle the response based on it's code in my activity:

switch(statusCode) {
    case 304: {
        // Get data from local DB
        break;
    }
    case 200: {}
    // And so on
}

The problem is that statusCode is 200 (filled by response.code()) even when Fiddler says it is 304. Why response.code() won't return 304 if a 304 is returned?

Body:
Have a look here (section 'Reduce processing'):

On a 304 status, Retrofit2 and OkHttp3 will pretend this response was
  equal to the last response; the cached response is returned. To notice
  the 304, check the raw response code:

if (response.isSuccessful() &&
    response.raw().networkResponse() != null &&
    response.raw().networkResponse().code() ==
           HttpURLConnection.HTTP_NOT_MODIFIED) {
    // not modified, no need to do anything.
    return;
}

// parse response here

Getting the normal (not raw) response code would give you the cached
  status code, probably 200 OK


问:
Making John, john and JOHN mean the same variable in python lists?
My question is this.

How do I make it so users can not make a new user_name John if JOHN or john are already in use.

Can I make user_name.upper() = user_name.lower() or something like that.

These names are been iterated through a loop of current_users. I want the loop to detect current users and disallow the use of a name if it has already been used in its upper() or title() forms.

Edit: If possible could I get the most 'pythonic' way of doing this. Thanks.

答:
```<code>   for username in current_user_names:
            if ip_username.lower() == username.lower():
                Flag = 1
                print ‘match found’
            else:
                Flag = 0
                current_user_names.append(username)
</code>```

Or simply just while you add your usernames add them in lower case.

```<code>your_userlist.append(username.lower())
</code>```

And you can simply use the IN keyword to check

```<code>if current_user.lower() IN your_userlist:
</code>```

Body:
   for username in current_user_names:
            if ip_username.lower() == username.lower():
                Flag = 1
                print ‘match found’
            else:
                Flag = 0
                current_user_names.append(username)

Or simply just while you add your usernames add them in lower case.

your_userlist.append(username.lower())

And you can simply use the IN keyword to check

if current_user.lower() IN your_userlist:


问:
Eclipse keyboard command to add import statement
I am a C# developer who is doing some Android development in Eclipse. One of my favorite keyboard shortcuts in Visual Studio is CTRL + . which brings up the SmartTag menu. This is incredibly useful for adding using statements on the fly.

As an example if I don't have an import statement for System.Xml.Linq but create a variable of type XDocument I can quickly add the appropriate using with the keyboard command.

Is there a similar keyboard command available in Eclipse?

答: The easiest thing to do is to start typing the type name, then press Ctrl + Space to get the completions. Selecting the completion will complete the type name that you are typing and will also add the import statement. Short of that, there is Ctrl + 1, which will bring up quick fixes when you are over a piece of code with problem. There is typically a quick fix to import type.


问:
Left weighted fast search on large text dataset - Mysql
I have a large dataset that I would like to use for autocomplete (>1M records) on mysql.

As an example I am typing "Methanol" and wanting typeahead suggestions..

Currently I have

```<code>select AgentReferenceName as name
from tblAgentReference
where AgentReferenceName like '%methan%'
order by instr(AgentReferenceName,'methan'), char_length(AgentReferenceName)
limit 10;
</code>```

This does the job nicely, but is a bit slow

```<code>+-------------+
| name        |
+-------------+
| Methan      |
| Methane     |
| Methane     |
| Methane     |
| Methanal    |
| Methanol    |
| Methanol    |
| Methanide   |
| Methanamine |
| Methanamine |
+-------------+
10 rows in set (3.52 sec)
</code>```

I have a fulltext index on the field but when I run the usual fulltext weighted search - it bumps up the larger words so I get

```<code>select AgentReferenceName as name  from tblAgentReference  where match(AgentReferenceName) against ('methano*' in boolean mode)   order by match(AgentReferenceName) against ('methano*') limit 10;
+----------------------------------------------------------------------------------------------------------+
| name                                                                                |
+----------------------------------------------------------------------------------------------------------+
| 2,4-Methanoacridin-9-amine, 8-fluoro-1,2,3,4-tetrahydro-, 2-hydroxy-1,2,3-propanetricarboxylate (3:2)    |
| 9-Amino-8-fluoro-1,2,3,4-tetrahydro-2,4-methanoacridine                                                  |
| 9-Amino-8-fluoro-1,2,3,4-tetrahydro-2,4-methanoacridine                                                  |
| 2,4-Methanoadamantane                                                                                |
| 2,4-Methanoadamantane                                                                                |
| 2-Amino-4,5-methanoadipate                                                                               |
| 1,4-Methanoanthra(2,3-c)oxepin-7,12-dione, 1,3,4,5-tetrahydro-4,6,13-trihydroxy-3,11-dimethoxy-3-methyl- |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4-tetrahydro-                                                    |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4-tetrahydro-                                                    |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4,4a,9a-hexahydro-                                               |
+----------------------------------------------------------------------------------------------------------+
10 rows in set (0.13 sec)
</code>```

So speed is good, but results are terrible

My question - how to do a fast search that returns similar to the like query, but nearer to the speed of the fulltext one?

答:
I've dealt with this exact problem. Here's what I did.

When the user furnished autocomplete string is one or two characters long, ignore it. Don't attempt to autocomplete (unless you have a record of the user's own previous searches).

When the user furnished autocomplete string is relatively short (try six characters) use   WHERE name LIKE CONCAT(:userstring, '%') and thereby search for strings beginning with what the user wants. That can exploit the index. The user may find the string she wants and choose it, and you're done.

When the user furnished string is longer, use a different query with WHERE name LIKE CONCAT('%', :userstring, '%'). Only for a longer string offer the performance killing search with the leading %. Performance will still stink, but the feature will get used less often.

Your best bet is, like Rick James mentioned, creating a table containing strings that start with the search terms you most often expect. Then you can always use LIKE 'searchterm%' and avoid the leading % altogether.

FULLTEXT has, as you've discovered, some limitations when you use it for autocomplete.

Body:
I have a large dataset that I would like to use for autocomplete (>1M records) on mysql.

As an example I am typing "Methanol" and wanting typeahead suggestions..

Currently I have

select AgentReferenceName as name
from tblAgentReference
where AgentReferenceName like '%methan%'
order by instr(AgentReferenceName,'methan'), char_length(AgentReferenceName)
limit 10;

This does the job nicely, but is a bit slow

+-------------+
| name        |
+-------------+
| Methan      |
| Methane     |
| Methane     |
| Methane     |
| Methanal    |
| Methanol    |
| Methanol    |
| Methanide   |
| Methanamine |
| Methanamine |
+-------------+
10 rows in set (3.52 sec)

I have a fulltext index on the field but when I run the usual fulltext weighted search - it bumps up the larger words so I get

select AgentReferenceName as name  from tblAgentReference  where match(AgentReferenceName) against ('methano*' in boolean mode)   order by match(AgentReferenceName) against ('methano*') limit 10;
+----------------------------------------------------------------------------------------------------------+
| name                                                                                |
+----------------------------------------------------------------------------------------------------------+
| 2,4-Methanoacridin-9-amine, 8-fluoro-1,2,3,4-tetrahydro-, 2-hydroxy-1,2,3-propanetricarboxylate (3:2)    |
| 9-Amino-8-fluoro-1,2,3,4-tetrahydro-2,4-methanoacridine                                                  |
| 9-Amino-8-fluoro-1,2,3,4-tetrahydro-2,4-methanoacridine                                                  |
| 2,4-Methanoadamantane                                                                                |
| 2,4-Methanoadamantane                                                                                |
| 2-Amino-4,5-methanoadipate                                                                               |
| 1,4-Methanoanthra(2,3-c)oxepin-7,12-dione, 1,3,4,5-tetrahydro-4,6,13-trihydroxy-3,11-dimethoxy-3-methyl- |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4-tetrahydro-                                                    |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4-tetrahydro-                                                    |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4,4a,9a-hexahydro-                                               |
+----------------------------------------------------------------------------------------------------------+
10 rows in set (0.13 sec)

So speed is good, but results are terrible

My question - how to do a fast search that returns similar to the like query, but nearer to the speed of the fulltext one?


问:
How to implement strictNullChecks in angular 4
I have tried to implement strictNullChecks in angular 4 application.

I have just added  "strictNullChecks": true  in tsconfig.json

When I run the application ng serve I got this below error.

```<code>ERROR in [at-loader] ./node_modules/@angular/forms/src/model.d.ts:244:39
TS2459: Type '{ onlySelf?: boolean | undefined; emitEvent?: boolean |
undefined; } | undefined' has no property 'emitEvent' and no string index signature.
</code>```

What's going wrong? How can we implement strictNullChecks in angular 4?

答:
Angular 2.x-4x

When you enable strictNullChecks, it enables it for all TypeScript files, which includes libraries.

To enable strictNullChecks in an Angular CLI project set skipLibCheck to true in your tsConfig.

Angular 5.x+ has addressed this issue.

Body:
I have tried to implement strictNullChecks in angular 4 application.

I have just added  "strictNullChecks": true  in tsconfig.json

When I run the application ng serve I got this below error.

ERROR in [at-loader] ./node_modules/@angular/forms/src/model.d.ts:244:39
TS2459: Type '{ onlySelf?: boolean | undefined; emitEvent?: boolean |
undefined; } | undefined' has no property 'emitEvent' and no string index signature.

What's going wrong? How can we implement strictNullChecks in angular 4?


答:
When you are looping through the CSV file, you should check if it is found and print it within the loop.

```<code>with open("Report.csv","r") as c:
    for row in c:
        details=row.split(",")
        if UserFind in details[0]:
            found=True
            print(details[0])
            print(details[1])
            print(details[2])
            print("These are your user's details!")
    if not found:
        print("User doesn't exist or wrong details...")
</code>```

Hope this helps.

Title: Python CSV files: Printing all a user's details

Body:
I am writing a piece of code wherein my user does a quiz and all that information is stored in a CSV file. I then, in another program, have the user input a username and, if it matches, it will print the scores etc for that user. However, I had the same user do the quiz again and, instead of printing all the quizzes and scores that user did, it just prints the latest one.

To show:
My CSV file looks like this

Ser15 A Sci-Med

Ser15 C Sci-Med

These are the rows. I want my program to print all the quizzes and grades 'Ser15' had, but it just prints the lastest.
How do I make my program print all of them? Here is my code below...

     def Report1():
        found=False
        UserFind=input("Please enter a username")
        with open("Report.csv","r") as c:
            for row in c:
                details=row.split(",")
                if UserFind in details[0]:
                    found=True
                else:
                  pass
            if found==True:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
            else:
                print("User doesn't exist or wrong details...")

This is my result:

Please enter a choice: 3
Please enter a usernameSer15
Ser15
C
Sci-Med

These are your user's details!

As you can see it prints their latest information, not all of them...

This is part of my project so any help is much appreciated!

Body:
When you are looping through the CSV file, you should check if it is found and print it within the loop.

with open("Report.csv","r") as c:
    for row in c:
        details=row.split(",")
        if UserFind in details[0]:
            found=True
            print(details[0])
            print(details[1])
            print(details[2])
            print("These are your user's details!")
    if not found:
        print("User doesn't exist or wrong details...")

Hope this helps.


问:
Windows kernel driver for direct I/O - anyone been there?
I need to handle direct I/O to a parallel port in a better way that we are doing it at the moment - presently we use a kernel driver that 'opens up' useable addresses using the I/O protection map. This works ok but is getting more and more left behind. We still wish to continue using a parallel port and there are very satisfactory parallel port card vendors for CardBus ExpressCard etc. I'd like to create a driver that knew about the address assigned to the device by the bus enumerator and allowed me to write to this address from my (Delphi) app. Due to the appernt complexity of this topic I'm struggling with where to start. Has anyone been this route please?</p>

答: You may try the WinIO library on www.internals.com</p>

OwnerDisplayName: Brian Frost

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: Malkocoglu

LastEditorDisplayName: Malkocoglu


问:
Drupal multi-site setup with sub-directories
I have a multi-site setup with a single codebase.
Is it possible to have my sites directory set up like this with sub folders:
mysite.com in /home/drupal/sites/mysite.com

othersite1.com  in  /home/drupal/sites/cluster1/othersite1.com

othersite2.com  in  /home/drupal/sites/cluster1/othersite2.com

othersite3.com  in  /home/drupal/sites/cluster2/othersite3.com

othersite4.com  in  /home/drupal/sites/cluster2/othersite4.com

I'm trying to find a way to organize all my sites.

thanks

答:
You can do this if you are using Drupal 7.  There is a file called sites.php in sites folder that you can alias the paths to your sites. If you are using < Drupal 7 you can make the directories as you propose and create symbolic links

```<code> ln -s /home/drupal/sites/cluster1/othersite1.com othersite1.com
</code>```

The way Drupal finds the site folder is explained in settings.php, read that.

Body:
You can do this if you are using Drupal 7.  There is a file called sites.php in sites folder that you can alias the paths to your sites. If you are using < Drupal 7 you can make the directories as you propose and create symbolic links

 ln -s /home/drupal/sites/cluster1/othersite1.com othersite1.com

The way Drupal finds the site folder is explained in settings.php, read that.


问:
setOnClickListener Not working in particular class
Here is my code for a one of many buttons within my UserActivity class that don't seem to work even though they have exactly the same implementation in other classes and work there.

```<code>Button test = findViewById(R.id.btn_test);
    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(UserActivity.this, "An error occurred.", Toast.LENGTH_LONG).show();
}
});
</code>```

Here is the same implementation that works in SignUp class

```<code>    Button btnLinkToLogIn = findViewById(R.id.btn_link_login);
    btnLinkToLogIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    });
</code>```

If any other code is needed please let me know, I am new to this site as well so please be nice and thanks for your help and taking time to read through this!

UserActivity.java

SignUpActivty.java

Project Zip

答: I have checked your project everything is working fine. You must check your device internet connection, rest everything is working fine.</p>

Body:
Here is my code for a one of many buttons within my UserActivity class that don't seem to work even though they have exactly the same implementation in other classes and work there.

Button test = findViewById(R.id.btn_test);
    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(UserActivity.this, "An error occurred.", Toast.LENGTH_LONG).show();
}
});

Here is the same implementation that works in SignUp class

    Button btnLinkToLogIn = findViewById(R.id.btn_link_login);
    btnLinkToLogIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    });

If any other code is needed please let me know, I am new to this site as well so please be nice and thanks for your help and taking time to read through this!

UserActivity.java

SignUpActivty.java

Project Zip


问:
addEventListener: "Argument types do not match parameters"
I've had this code for a while but just today I noticed this:

I'm not sure what I would have changed that could have caused this...

答: Please vote for WEB-30082 to be notified on any progress with it</p>


问:
How can I execute the lua file in init script?
I have a problem in init script.

```<code>reload_service() {
    echo "####################### restart##################" > /dev/ttyS0
    lua /root/proto.lua
    lua /root/ft.lua
    /etc/init.d/network reload
}
</code>```

From that code, everything is fine, but I can't see the result of the two lua files(In those files, I put the print function. When i typed the lua command in command line, I can see the print function's result).
In init script, can i use the lua command?

答:
You can use syslog for logging, print statement wont be visible in console.
Or in place of print dump the logs in some file.</p>

Body:
I have a problem in init script.

reload_service() {
    echo "####################### restart##################" > /dev/ttyS0
    lua /root/proto.lua
    lua /root/ft.lua
    /etc/init.d/network reload
}

From that code, everything is fine, but I can't see the result of the two lua files(In those files, I put the print function. When i typed the lua command in command line, I can see the print function's result).
In init script, can i use the lua command?


问:
Changing the content in the anychart loader
I am trying to show some text in anychart loader method instead of the default columns red,orange,green. I have created new .css file using (https://cdn.anychart.com/releases/8.0.1/css/anychart-ui.min.css) as suggested in the example and tried to change the loader portion with text and image but could see the changes, I want to show text or image (Eg:-loading..) instead of default columns.Can anyone tell me how can i make the changes in the Anychart loader.</p>

答:
Currently, it is not possible via API, but we can offer you to work with the CSS directly, e.g.

```<code>document.getElementsByClassName(' anychart-loader-rotating-cover')[0].innerHTML = 'Loading...';
</code>```

See the full sample here: http://jsfiddle.net/eo0a6cmf/

Body:
Currently, it is not possible via API, but we can offer you to work with the CSS directly, e.g.

document.getElementsByClassName(' anychart-loader-rotating-cover')[0].innerHTML = 'Loading...';

See the full sample here: http://jsfiddle.net/eo0a6cmf/


问:
Atom is changing my whitespace against my will - how do I stop it?
Every time I diff a change from a file I've edited, I see things like this change (where a tab has been removed automagically):

Where is the setting to stop this from happening?

答: Disable the whitespace package entirely. Worked for me.</p>


问:
Accessing a class from MainPage.xaml.cs
Forgive me, I am still new to C#. I have done some searching but cannot find anything about .xaml.cs and this particular issue that I am having.

I have a project in which I need to access some variables from my MeasureLengthDevice class from my MainPage.xaml.cs.

Here is some of my code in my MeasureLengthDevice.cs class in which I am currently trying to access (the unitsToUse variable):

```<code>private string unitsToUse;

public MeasureLengthDevice()
{
    unitsToUse = CboMeasure.ToString();
}
</code>```

And here is what I have in my MainPage.xaml.cs:

```<code>public MeasureLengthDevice()
{
    MeasureLengthDevice myMLDInstance = new MeasureLengthDevice();
    mld = myMLDInstance.MeasureLengthDevice();
}

private void startButton_Click(object sender, RoutedEventArgs e)
{
     currentMeasurement.Text = unitsToUse;
}
</code>```

My issue is, when the application runs and I click the "startButton", I want the currentMeasurement textbox to display what the unitsToUse variable holds. However, I cannot get access to my variable from my MeasureLengthDevice.cs from my MainPage.xaml.cs.

If I have not provided any information needed for assistance please let me know!

UPDATED CODE

I have changed my MainPage.xaml.cs to:

```<code>public sealed partial class MainPage : Page
{
    MeasureLengthDevice myMLDInstance;
    public MainPage()
    {
        myMLDInstance = new MeasureLengthDevice();
        myMLDInstance.SetMeasureLengthDevice();
    }

    private void startButton_Click(object sender, RoutedEventArgs e)
    {
            currentMeasurement.Text = myMLDInstance.unitsToUse;
    }
</code>```

And have changed MeasureLengthDevice.cs to:

```<code>public class MeasureLengthDevice : Device, IMeasuringDevice
{
    private string unitsToUse { get; set; }

    public void SetMeasureLengthDevice()
    {
        unitsToUse = CboMeasure.ToString();
    }
</code>```

I have updated my initial post to show the changes made. The only issue I am having now is the protection level for unitsToUse, I need to keep the string private in the MeasureLengthDevice class though. If I switch it to public it does work but I need it to stay private.

答:
you are new to c# but variable scoping is not new to programming language, here you are declaring variable in one method and try to acess it in antoher method but variable you declared is in scope of first method only so you cannot access it in other method of your class.

so its better to increase scrop of variable to both the method by putting variable in larger scope i.e at class leavel so both method can access variable

following is you code

```<code>MeasureLengthDevice myMLDInstance;
public MeasureLengthDevice()
{
  myMLDInstance = new MeasureLengthDevice();
    mld = myMLDInstance.MeasureLengthDevice();
}

private void startButton_Click(object sender, RoutedEventArgs e)
{
    if(myMLDInstance!=null)
     currentMeasurement.Text = myMLDInstance.unitsToUse;
}
</code>```

MeasureLengthDevice.cs

```<code>public class MeasureLengthDeviceInfo
{
 public string unitsToUse {get; set;}

  public void SetMeasureLengthDevice()
  {
    unitsToUse = CboMeasure.ToString();
  }
}
</code>```

MainPage.xaml.cs:

```<code>public class MainPage
{
 MeasureLengthDeviceInfo myMLDInstance;
 public MainPage()
 {
    myMLDInstance = new MeasureLengthDeviceInfo();
    myMLDInstance.SetMeasureLengthDevice();
 }

 private void startButton_Click(object sender, RoutedEventArgs e)
 {
     currentMeasurement.Text = myMLDInstance.unitsToUse;
 }
}
</code>```

Title: Accessing a class from MainPage.xaml.cs

Body:
Forgive me, I am still new to C#. I have done some searching but cannot find anything about .xaml.cs and this particular issue that I am having.

I have a project in which I need to access some variables from my MeasureLengthDevice class from my MainPage.xaml.cs.

Here is some of my code in my MeasureLengthDevice.cs class in which I am currently trying to access (the unitsToUse variable):

private string unitsToUse;

public MeasureLengthDevice()
{
    unitsToUse = CboMeasure.ToString();
}

And here is what I have in my MainPage.xaml.cs:

public MeasureLengthDevice()
{
    MeasureLengthDevice myMLDInstance = new MeasureLengthDevice();
    mld = myMLDInstance.MeasureLengthDevice();
}

private void startButton_Click(object sender, RoutedEventArgs e)
{
     currentMeasurement.Text = unitsToUse;
}

My issue is, when the application runs and I click the "startButton", I want the currentMeasurement textbox to display what the unitsToUse variable holds. However, I cannot get access to my variable from my MeasureLengthDevice.cs from my MainPage.xaml.cs.

If I have not provided any information needed for assistance please let me know!

UPDATED CODE

I have changed my MainPage.xaml.cs to:

public sealed partial class MainPage : Page
{
    MeasureLengthDevice myMLDInstance;
    public MainPage()
    {
        myMLDInstance = new MeasureLengthDevice();
        myMLDInstance.SetMeasureLengthDevice();
    }

    private void startButton_Click(object sender, RoutedEventArgs e)
    {
            currentMeasurement.Text = myMLDInstance.unitsToUse;
    }

And have changed MeasureLengthDevice.cs to:

public class MeasureLengthDevice : Device, IMeasuringDevice
{
    private string unitsToUse { get; set; }

    public void SetMeasureLengthDevice()
    {
        unitsToUse = CboMeasure.ToString();
    }

I have updated my initial post to show the changes made. The only issue I am having now is the protection level for unitsToUse, I need to keep the string private in the MeasureLengthDevice class though. If I switch it to public it does work but I need it to stay private.

Body:
you are new to c# but variable scoping is not new to programming language, here you are declaring variable in one method and try to acess it in antoher method but variable you declared is in scope of first method only so you cannot access it in other method of your class.

so its better to increase scrop of variable to both the method by putting variable in larger scope i.e at class leavel so both method can access variable

following is you code

MeasureLengthDevice myMLDInstance;
public MeasureLengthDevice()
{
  myMLDInstance = new MeasureLengthDevice();
    mld = myMLDInstance.MeasureLengthDevice();
}

private void startButton_Click(object sender, RoutedEventArgs e)
{
    if(myMLDInstance!=null)
     currentMeasurement.Text = myMLDInstance.unitsToUse;
}

MeasureLengthDevice.cs

public class MeasureLengthDeviceInfo
{
 public string unitsToUse {get; set;}

  public void SetMeasureLengthDevice()
  {
    unitsToUse = CboMeasure.ToString();
  }
}

MainPage.xaml.cs:

public class MainPage
{
 MeasureLengthDeviceInfo myMLDInstance;
 public MainPage()
 {
    myMLDInstance = new MeasureLengthDeviceInfo();
    myMLDInstance.SetMeasureLengthDevice();
 }

 private void startButton_Click(object sender, RoutedEventArgs e)
 {
     currentMeasurement.Text = myMLDInstance.unitsToUse;
 }
}


问:
three.js r88 meshdepthmaterial there is no effect
I'm a new three.js men, and below is my code snippet...
In three.js docs said that the MeshDepthMaterial is drawing geometry by depth. Depth is based off of the camera near and far plane. White is nearest, black is farthest. But in my case, there is no effect for three.js r88, but three.js r 67. Can anybody please tell me why? Thanks very much...

<!DOCTYPE html>

    <title>示例 04.02 - MeshDepthMaterial</title>

```

答:
When you change camera.near or camera.far you need to call:

```<code>camera.updateProjectionMatrix();
</code>```

three.js r.88

Body:
When you change camera.near or camera.far you need to call:

camera.updateProjectionMatrix();

three.js r.88


问:
Sanitizing user input for a message box
I am developing a crypto-related application and since those people who deal in crypto will always try some sort of scam or script kiddie "hack" I'd like to figure out the best way to clean up content in user-to-user chat boxes and comments fields.

I don't want any HTML/CSS/JS in there.

I want to leave email addresses, URLs, phone numbers and "normal" text untouched.

Right now I am doing a .gsub(/[^0-9a-zA-Z\@\;\:\-\_\,\.\ ]/i, '') before_save but it removes the newlines.

I tried adding .gsub(/[^0-9a-zA-Z\R\@\;\:\-\_\,\.\ ]/i, '') to make it leave newlines alone but it does not seem to work.

Would prefer not having to add any gems.

答:
Rails has an excellent sanitizer built in, that I would recommend you use instead of trying to figure out your own regular expressions.

See:

http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

Before you render any user's input out the page wrap it in santize

```<code><%= sanitize @comment.body %>
</code>```

If you want to sanitize before saving to the database, you can include the helper into your controller

```<code>class MyController < ApplicationController
  include ActionView::Helpers::SanitizeHelper

  def create
    content = sanitize(params[:content])
    Thing.save(content: content)
  end
end
</code>```

Title: Sanitizing user input for a message box

Body:
Rails has an excellent sanitizer built in, that I would recommend you use instead of trying to figure out your own regular expressions.

See:

http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

Before you render any user's input out the page wrap it in santize

<%= sanitize @comment.body %>

If you want to sanitize before saving to the database, you can include the helper into your controller

class MyController < ApplicationController
  include ActionView::Helpers::SanitizeHelper

  def create
    content = sanitize(params[:content])
    Thing.save(content: content)
  end
end


问:
Accessing the outer scope in Python 2.6
Say, I have some scope with variables, and a function called in this scope wants to change some immutable variables:

```
def outer():
    s = 'qwerty'
    n = 123
    modify()

def modify():
    s = 'abcd'
    n = 456
```

Is it possible somehow to access the outer scope? Something like nonlocal variables from Py3k.

Sure I can do s,n = modify(s,n) in this case, but what if I need some generic 'injection' which executes there and must be able to reassign to arbitrary variables?

I have performance in mind, so, if possible, eval & stack frame inspection is not welcome :)

UPD: It's impossible. Period. However, there are some options how to access variables in the outer scope:

Use globals. By the way, func.__globals__ is a mutable dictionary ;)

Store variables in a dict/class-instance/any other mutable container

Give variables as arguments & get them back as a tuple: a,b,c = innerfunc(a,b,c)

Inject other function's bytecode. This is possible with byteplay python module.

答:
Define the variables outside of the functions and use the global keyword.

```<code>s, n = "", 0

def outer():
    global n, s
    n = 123
    s = 'qwerty'
    modify()

def modify():
    global n, s
    s = 'abcd'
    n = 456
</code>```

Title: Accessing the outer scope in Python 2.6

Body:
Say, I have some scope with variables, and a function called in this scope wants to change some immutable variables:

def outer():
    s = 'qwerty'
    n = 123
    modify()

def modify():
    s = 'abcd'
    n = 456

Is it possible somehow to access the outer scope? Something like nonlocal variables from Py3k.

Sure I can do s,n = modify(s,n) in this case, but what if I need some generic 'injection' which executes there and must be able to reassign to arbitrary variables?

I have performance in mind, so, if possible, eval & stack frame inspection is not welcome :)

UPD: It's impossible. Period. However, there are some options how to access variables in the outer scope:

Use globals. By the way, func.__globals__ is a mutable dictionary ;)

Store variables in a dict/class-instance/any other mutable container

Give variables as arguments & get them back as a tuple: a,b,c = innerfunc(a,b,c)

Inject other function's bytecode. This is possible with byteplay python module.

Body:
Define the variables outside of the functions and use the global keyword.

s, n = "", 0

def outer():
    global n, s
    n = 123
    s = 'qwerty'
    modify()

def modify():
    global n, s
    s = 'abcd'
    n = 456


问:
Postgres quoted macro syntax error
Attempting to use a quoted psql SET value:

```<code> $ psql db_name -v x=y
 => select :x;
 ERROR: column "y" does not exist # this is correct and expected
  => select UPPER(:'x');
 ERROR:  syntax error at or near ":"
 LINE 1: select UPPER(:'x');
</code>```

that last query should return

```<code>  upper
----------
 Y
(1 row)
</code>```

but doesn't on one box but not another? (Not sure what this kind of SET value use is referred to as).

答:
Turns out my client version was old:

```<code># psql --version
psql (PostgreSQL) 8.4.20
contains support for command-line editing
</code>```

Needed a 9.x client version.  Pesky old distros :\

Title: Postgres quoted macro syntax error

Body:
Attempting to use a quoted psql SET value:

 $ psql db_name -v x=y
 => select :x;
 ERROR: column "y" does not exist # this is correct and expected
  => select UPPER(:'x');
 ERROR:  syntax error at or near ":"
 LINE 1: select UPPER(:'x');

that last query should return

  upper
----------
 Y
(1 row)

but doesn't on one box but not another? (Not sure what this kind of SET value use is referred to as).

Body:
Turns out my client version was old:

# psql --version
psql (PostgreSQL) 8.4.20
contains support for command-line editing

Needed a 9.x client version.  Pesky old distros :\


问:
how to paste something in textbox without overwriting
hi i created a little app for my business. Now i have a little problem.
I want to paste one code of textbox2 to textbox4 without erasing previous data of textbox4..

I tried these codes but it doesn't work

for copy==>

```<code> private void button3_Click(object sender, EventArgs e)
    {
        Clipboard.SetText(textBox2.Text);
    }
</code>```

for paste ===>

```<code> private void button6_Click(object sender, EventArgs e)
    {
        textBox4.Text =Clipboard.GetText()+Environment.NewLine;
    }
</code>```

this paste code is overwriting. I want a method for paste button to keep previous data when pasting new data..

Help me plz

答:
For pasting the new value without removing the old text, you can do it like below in your button6 click event :

```<code>private void button6_Click(object sender, EventArgs e)
{
    textBox4.Text += Clipboard.GetText() + Environment.NewLine;
}
</code>```

Body:
hi i created a little app for my business. Now i have a little problem.
I want to paste one code of textbox2 to textbox4 without erasing previous data of textbox4..

I tried these codes but it doesn't work

for copy==>

 private void button3_Click(object sender, EventArgs e)
    {
        Clipboard.SetText(textBox2.Text);
    }

for paste ===>

 private void button6_Click(object sender, EventArgs e)
    {
        textBox4.Text =Clipboard.GetText()+Environment.NewLine;
    }

this paste code is overwriting. I want a method for paste button to keep previous data when pasting new data..

Help me plz

Body:
For pasting the new value without removing the old text, you can do it like below in your button6 click event :

private void button6_Click(object sender, EventArgs e)
{
    textBox4.Text += Clipboard.GetText() + Environment.NewLine;
}


问:
Bitbucket issue tracker in PhpStorm
I want to link Tasks to our Bitbucket server. However, when I try to add the server (Tools > Tasks & Content > Configure servers), it wants me to choose a server type.

Q1. I have no idea what type to select. I haven't found any reference for this question.

Q2. If a type is chosen, it asks for the server url. Do I need just https://bitbucket.org or do I need something more specific?

答:
Adding to the accepted answer, please note that version 2.0 of the Bitbucket API uses a different format for parameters noted here: Bitbucket API 2.0: Filter and sort API objects

The Task List URL should be: {serverUrl}/issues?q=%28state+%3D+%22new%22+OR+state+%3D+%22open%22%29

Title: Bitbucket issue tracker in PhpStorm


问:
How do I use CultureInfo to get the 12-hour or 24-hour time (without the date)

I would like to use C# to format a time of day in the proper cultural format.

For example, if the current culture is en-US I would like to show 1:00 PM, and if the current culture is fr-FR I would like to show 13:00. I just want the time of day, I do not want the date.

```<code>//timeOfDay is a DateTime object.

//This will return the 12 hour clock regardless of culture:
time = timeOfDay.ToString("h:mm tt", CultureInfo.CurrentCulture);
//This will return the 24 hour clock regardless of culture
time = timeOfDay.ToString("H:mm tt", CultureInfo.CurrentCulture);
//This will return the correct clock for the culture, but the date will also be present
time = timeOfDay.ToString(CultureInfo.CurrentCulture);
</code>```

Note that the "tt" is for AM/PM, and it is culturally sensitive (in France it is blank, as it should be).

How do I acquire the appropriate clock format for the current culture, without the date?

答:
I don't see any other option to check CurrentCulture information and format timeOfDay differently (because your strings have different formats) based on that culture.

```<code>if (CultureInfo.CurrentCulture == new CultureInfo("en-US"))
{
    time = timeOfDay.ToString("h:mm tt", CultureInfo.CurrentCulture);
}

if (CultureInfo.CurrentCulture == new CultureInfo("fr-FR"))
{
    time = timeOfDay.ToString("HH:mm", CultureInfo.CurrentCulture);
}
</code>```

Body:
I would like to use C# to format a time of day in the proper cultural format.

For example, if the current culture is en-US I would like to show 1:00 PM, and if the current culture is fr-FR I would like to show 13:00. I just want the time of day, I do not want the date.

//timeOfDay is a DateTime object.

//This will return the 12 hour clock regardless of culture:
time = timeOfDay.ToString("h:mm tt", CultureInfo.CurrentCulture);
//This will return the 24 hour clock regardless of culture
time = timeOfDay.ToString("H:mm tt", CultureInfo.CurrentCulture);
//This will return the correct clock for the culture, but the date will also be present
time = timeOfDay.ToString(CultureInfo.CurrentCulture);

Note that the "tt" is for AM/PM, and it is culturally sensitive (in France it is blank, as it should be).

How do I acquire the appropriate clock format for the current culture, without the date?

Body:
I don't see any other option to check CurrentCulture information and format timeOfDay differently (because your strings have different formats) based on that culture.

if (CultureInfo.CurrentCulture == new CultureInfo("en-US"))
{
    time = timeOfDay.ToString("h:mm tt", CultureInfo.CurrentCulture);
}

if (CultureInfo.CurrentCulture == new CultureInfo("fr-FR"))
{
    time = timeOfDay.ToString("HH:mm", CultureInfo.CurrentCulture);
}


问:
Repetable, global Custom fields in Wordpress Theme
quick question, what is the best approach in your opinion to make /parts files content editable to the user from the Wordpress admin?

myTheme:

parts

some-block.php ( hero banner in example with some short content )

templates

template-homepage.php  <-- get_template_part('parts/some', 'block' )

template-page.php  <-- get_template_part('parts/some', 'block' )

Usually if I have a section unique for certain page I am using Advanced Custom Fields to do the job, but I don't think it will be a good choice in this case.

I am looking for a clean solution that will allow Wordpress users globally define parts content from the administration panel.

Any tips?

Thanks in advance

List item

答: If you are an Advanced Custom Fields Pro plugin user the ACF Options page will do the job for you. Using it you can easily define section repetable across the whole theme: in ex. footer content or some CTA sections like signup for newsletter or etc.</p>