问:
How to change text color based on specific option?
I want to change the first option's color to #ccc, others remain #000, but it doesn't work.Why? thanks.
 I don't wnat to use change function, which I think it's unnecessary.

something like this:

HTML:

```<code>  <select id="continent">
      <option value="-1">continent</option>
      <option value="1">US</option>
      <option value="2">UK</option>
  </select>
</code>```

JS:

```<code>$("#continent option[value='-1']").css('color','#ccc');
</code>```

答:
Why do you want to use jQuery? This can be done with pure CSS.

#continent option {
  background-color: white; /* on XFCE the default background-color is #CCC! */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="continent">
    <option value="-1" style="color:#cccccc">continent</option>
    <option value="1">US</option>
    <option value="2">UK</option>
</select></code>```

However you probably shouldn't do this, because it looks like the option was disabled, but it isn't. This is counterintuitive and against usability.

Apart from that, it looks different on other operating systems. This is how the snippet from above looks like on ubuntu with XFCE:

And this is what another solution looks like that also changes the color of the <select> to light gray if the 1st option is selected:

That's why you should either use <option value="-1" disabled> or another color.

Body:
I want to change the first option's color to #ccc, others remain #000, but it doesn't work.Why? thanks.
 I don't wnat to use change function, which I think it's unnecessary.

something like this:

HTML:

  <select id="continent">
      <option value="-1">continent</option>
      <option value="1">US</option>
      <option value="2">UK</option>
  </select>

JS:

$("#continent option[value='-1']").css('color','#ccc');

Body:
Why do you want to use jQuery? This can be done with pure CSS.

#continent option {
  background-color: white; /* on XFCE the default background-color is #CCC! */
}

<select id="continent">
    <option value="-1" style="color:#cccccc">continent</option>
    <option value="1">US</option>
    <option value="2">UK</option>
</select>

However you probably shouldn't do this, because it looks like the option was disabled, but it isn't. This is counterintuitive and against usability.

Apart from that, it looks different on other operating systems. This is how the snippet from above looks like on ubuntu with XFCE:

And this is what another solution looks like that also changes the color of the <select> to light gray if the 1st option is selected:

That's why you should either use <option value="-1" disabled> or another color.


来源: stackexchange

问:
A few problems with java input exception handling
I need to handle empty input and remove the stack trace from output.

Here's a snippet of my code:

```<code>public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.println("\n" + "NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }

            if (args.length==0 ||args.length>3||Integer.parseInt(args[i])<0)
                throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
        }
</code>```

I have two problems, first is when a user inputs no value on the command line, it's supposed to throw a IllegalArguementException and the appropriate error message. When I run this code and input no values it runs without throwing the exception. It looks something like this:

C:\Users\XXX\Desktop\Folder>java TestShape

C:\Users\XXX\Desktop\Folder>_

The second problem is when I try out the other exceptions (putting a string instead of an int, negative numbers, exceeding more than 3 numbers etc.) it outputs the proper message but it also prints out the stack trace:

C:\Users\Chef Boi Logro\Desktop\Folder\ICS 112\Lab
  Exercises\LE8\New>java TestShape -1 2 -3

Exception in thread "main" java.lang.IllegalArgumentException:

IllegalArgumentException is caught Please input 1, 2 or 3 valid
  numbers only
          at TestShape.main(TestShape.java:19)

What I need is for the terminal to just display the error messages, without the stack trace.

答:
You can check received values before checking for avoiding exceptions because you have expected numbers for the task (from 0 to 9);

I prefer this approach:

```<code>    public static void main(String args[])
    {
      if(arargs.length < 1 || arargs.length > 3) //firstly check input size
      {
        System.out.println("Please input 1, 2 or 3 valid numbers only.");
        return;
      }
      List<String> allowedNumbers = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); //define allowed numbers (please move to constant in your class for avoid multimple initialization)
        for(int i = 0; i < args.length; i++)
        {
          try
          {
            if(allowedNumbers.contains(args[i]))
            {
              Integer.parseInt(args[i]); //now it's safety parse without exceptions
            }
          }
          catch(NumberFormatException nfe)
          {
            System.err.println(nfe.toString());
          }
        }
      }
</code>```

Hope it's useful info.

ContentLicense: CC BY-SA 3.0

Body:
I need to handle empty input and remove the stack trace from output.

Here's a snippet of my code:

public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.println("\n" + "NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }

            if (args.length==0 ||args.length>3||Integer.parseInt(args[i])<0)
                throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
        }

I have two problems, first is when a user inputs no value on the command line, it's supposed to throw a IllegalArguementException and the appropriate error message. When I run this code and input no values it runs without throwing the exception. It looks something like this:

C:\Users\XXX\Desktop\Folder>java TestShape

C:\Users\XXX\Desktop\Folder>_

The second problem is when I try out the other exceptions (putting a string instead of an int, negative numbers, exceeding more than 3 numbers etc.) it outputs the proper message but it also prints out the stack trace:

C:\Users\Chef Boi Logro\Desktop\Folder\ICS 112\Lab
  Exercises\LE8\New>java TestShape -1 2 -3

Exception in thread "main" java.lang.IllegalArgumentException:

IllegalArgumentException is caught Please input 1, 2 or 3 valid
  numbers only
          at TestShape.main(TestShape.java:19)

What I need is for the terminal to just display the error messages, without the stack trace.

Body:
You can check received values before checking for avoiding exceptions because you have expected numbers for the task (from 0 to 9);

I prefer this approach:

    public static void main(String args[])
    {
      if(arargs.length < 1 || arargs.length > 3) //firstly check input size
      {
        System.out.println("Please input 1, 2 or 3 valid numbers only.");
        return;
      }
      List<String> allowedNumbers = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); //define allowed numbers (please move to constant in your class for avoid multimple initialization)
        for(int i = 0; i < args.length; i++)
        {
          try
          {
            if(allowedNumbers.contains(args[i]))
            {
              Integer.parseInt(args[i]); //now it's safety parse without exceptions
            }
          }
          catch(NumberFormatException nfe)
          {
            System.err.println(nfe.toString());
          }
        }
      }

Hope it's useful info.


问:
Ruby operations on template variables - Chef
I have written following template in my chef cookbook recipe

```<code>template '/etc/app.conf' do
   variables({
   my_id: Chef::HTTP.new(https://example.com).get('/',{header})
})
end
</code>```

And my erb file is

```<code>Output is : <%= @my_id %>
</code>```

I actually want to perform some ruby operations(mainly filter out and count the components of my_id) and then pass those values(count of each component) back to the template and use it further. What should be erb configuration or anything thats need to be added in template block?

(Here, my_id actually has the subnets and I want to get those the count of those subnets and its values so that I can use it further to perform another http request and get the nodes in each of the subnet).

答:
Don't know much about Chef Cookbooks but you can write some ruby within an ERB template. It is not the cleanest solution I believe though.

See here on how to embed code in your ERB

Body:
I have written following template in my chef cookbook recipe

template '/etc/app.conf' do
   variables({
   my_id: Chef::HTTP.new(https://example.com).get('/',{header})
})
end

And my erb file is

Output is : <%= @my_id %>

I actually want to perform some ruby operations(mainly filter out and count the components of my_id) and then pass those values(count of each component) back to the template and use it further. What should be erb configuration or anything thats need to be added in template block?

(Here, my_id actually has the subnets and I want to get those the count of those subnets and its values so that I can use it further to perform another http request and get the nodes in each of the subnet).


问:
Ajax call in cakePhp does not execute the requested php code in controller
I was handed a project written with cakePhp framework and needed to add some additional function. I tried to follow the existing syntax but somehow couldn't get the new function to work.

The original view file has the following script portion (after the html stuff):

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

function printorderpage() {
    window.print();
}

</script>
</code>```

What I wanted to do is to perform certain database operation (mark a record as locked down so it can no longer be edited) when user prints the page.

Here's what I added to the view file:

```<code>(function() {
    var beforePrint = function() {
        //console.log('Functionality to run before printing.');
        //alert('before print test');
    };
    var afterPrint = function() {
        //console.log('Functionality to run after printing');
        alert('lock'+<?=$order_id?>);

        $.ajax({
            url: "/Workorder/ajaxLockOrder/<?=$order_id?>?debug=false",
            type: "post",
            dataType: "json",
            data: post_data
        }).done(function(e) {
            alert(e.message);
        });

        alert('done?');

    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());
</code>```

Basically the afterPrint function is called whenever user prints the page, and this in turn calls the controller function "ajaxLockOrder" to perform some database operations in the backend. By using the alert box, I could verify that the afterPrint function is executed (the alert pop-up successfully showed the $order_id that needs to be locked, in my test case, order_id is "18", alert box showed "lock18"). But then the ajaxLockOrder was not called?

The controller file is named "workorder_controller.php", and here's the ajaxLockOrder function inside the controller:

```<code>function ajaxLockOrder($order_id) {
    //once the order is printed, lock the order so it can not be changed
    error_log("executed", 3, "lockerr.log");
    $this->Order->updateActivityStream($order_id, 5); //data operation
}
</code>```

By using the error_log function, I could verify that this function was not executed since the log file was not created.

On the other hand, when I tried to directly type in this function address (http://myurl/Workorder/ajaxLockOrder/18) in browser window, it worked and generated the log file in the backend and updated the database record for order#18. WHY?

Thanks in advance for any help.

答:
I knew it must be something simple. Turns out this particular view page did not have jquery library loaded (probably because it did not need any ajax call before). I added the jquery library and everything worked just fine!</p>

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</code>```

Body:
I was handed a project written with cakePhp framework and needed to add some additional function. I tried to follow the existing syntax but somehow couldn't get the new function to work.

The original view file has the following script portion (after the html stuff):

What I wanted to do is to perform certain database operation (mark a record as locked down so it can no longer be edited) when user prints the page.

Here's what I added to the view file:

(function() {
    var beforePrint = function() {
        //console.log('Functionality to run before printing.');
        //alert('before print test');
    };
    var afterPrint = function() {
        //console.log('Functionality to run after printing');
        alert('lock'+<?=$order_id?>);

        $.ajax({
            url: "/Workorder/ajaxLockOrder/<?=$order_id?>?debug=false",
            type: "post",
            dataType: "json",
            data: post_data
        }).done(function(e) {
            alert(e.message);
        });

        alert('done?');

    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());

Basically the afterPrint function is called whenever user prints the page, and this in turn calls the controller function "ajaxLockOrder" to perform some database operations in the backend. By using the alert box, I could verify that the afterPrint function is executed (the alert pop-up successfully showed the $order_id that needs to be locked, in my test case, order_id is "18", alert box showed "lock18"). But then the ajaxLockOrder was not called?

The controller file is named "workorder_controller.php", and here's the ajaxLockOrder function inside the controller:

function ajaxLockOrder($order_id) {
    //once the order is printed, lock the order so it can not be changed
    error_log("executed", 3, "lockerr.log");
    $this->Order->updateActivityStream($order_id, 5); //data operation
}

By using the error_log function, I could verify that this function was not executed since the log file was not created.

On the other hand, when I tried to directly type in this function address (http://myurl/Workorder/ajaxLockOrder/18) in browser window, it worked and generated the log file in the backend and updated the database record for order#18. WHY?

Thanks in advance for any help.

Body:
I knew it must be something simple. Turns out this particular view page did not have jquery library loaded (probably because it did not need any ajax call before). I added the jquery library and everything worked just fine!

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


问:
Unable to view value in textbox after binding in angularjs
Hi I am developing Angularjs application. I am trying to bind value to textbox as below.

```<code><ul>
    <li ng-repeat="screen in screenMap">
        <input type="text" ng-model="screenname" value="{{screen.scrn_name}}" />
    </li>
</ul>
</code>```

After binding value to textbox, Textbox does not show any value. But when i see in browser i can see below value is binded

```<code> <input type="text" ng-model="screenname" value="USerProfile" class="ng-pristine ng-untouched ng-valid">
</code>```

May i know why i am not able to see value in textbox? Any help would be appreciated. Thank you.

答:
You are almost there. In Angular model is equal to value.

<input type="text" ng-model="screen.scrn_name" /> should suffice.

Body:
Hi I am developing Angularjs application. I am trying to bind value to textbox as below.

        <input type="text" ng-model="screenname" value="{{screen.scrn_name}}" />

After binding value to textbox, Textbox does not show any value. But when i see in browser i can see below value is binded

 <input type="text" ng-model="screenname" value="USerProfile" class="ng-pristine ng-untouched ng-valid">

May i know why i am not able to see value in textbox? Any help would be appreciated. Thank you.


问:
Connect derby DB to Java
I wanted to connect DB to Java application in Intellij.
I set the classpath correctly, so that javac from cmd is working correct.
I have also downloaded all the jar files needed as a libary, but I still get java.sql.SQLException: No suitable driver found for jdbc:derby

What can be the problem?

```<code>public static void main(String[] args) {
    try {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
    } catch(java.lang.ClassNotFoundException e) {
        e.printStackTrace();
    }

    final String DATABASE_URL = "jdbc:derby:myDB;create=true;user=user;password=pass";

    try (
            Connection connection = DriverManager.getConnection(DATABASE_URL, "user", "pass");
    )
    {
        // ...
    }
    catch (SQLException sqlException)
    {
        sqlException.printStackTrace();
    }

}
</code>```

答:
You can try if org.apache.derby.jdbc.EmbeddedDriver works. And it seems your connection url is wrong.

```<code>    final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
    Connection connection = null;
    try{
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        connection = DriverManager.getConnection(DATABASE_URL );
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
</code>```

Title: Connect derby DB to Java

Body:
I wanted to connect DB to Java application in Intellij.
I set the classpath correctly, so that javac from cmd is working correct.
I have also downloaded all the jar files needed as a libary, but I still get java.sql.SQLException: No suitable driver found for jdbc:derby

What can be the problem?

public static void main(String[] args) {
    try {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
    } catch(java.lang.ClassNotFoundException e) {
        e.printStackTrace();
    }

    final String DATABASE_URL = "jdbc:derby:myDB;create=true;user=user;password=pass";

    try (
            Connection connection = DriverManager.getConnection(DATABASE_URL, "user", "pass");
    )
    {
        // ...
    }
    catch (SQLException sqlException)
    {
        sqlException.printStackTrace();
    }

}

Body:
You can try if org.apache.derby.jdbc.EmbeddedDriver works. And it seems your connection url is wrong.

    final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
    Connection connection = null;
    try{
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        connection = DriverManager.getConnection(DATABASE_URL );
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }


问:
Struts 2 using getText in action class or beans
Is there a way to use getText() in action class or beans? I cannot find example of java coding in google search but can find in JSP coding. My example is as below:

```<code>public class LoanForm extends ActionSupport {

    public void validate(){
        if(this.getNameOfApplicant().equals("")){
            addFieldError(getText("error.card"), getText("error.invalid.name"));
        }
    }
}
</code>```

答:
You can use getText() if your action bean implements TextProvider. If you extend ActionSupport it's already implemented by default.

To use getText() the action should implement TextProvider that
what ActionSupport is for. If your action class extends
ActionSupport then you can use default implementation of
TextProvider and can use the code above.

For other beans you can get the action instance which implements a TextProvider. For example

```<code>ActionSupport action = (ActionSupport)ActionContext.getContext().getActionInvocation().getAction();
String text = action.getText("error.card");
</code>```

But the first parameter in addFieldError(), doesn't need getText(). It's used for the name of the field which would have an error.

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to use getText() in action class or beans? I cannot find example of java coding in google search but can find in JSP coding. My example is as below:

public class LoanForm extends ActionSupport {

    public void validate(){
        if(this.getNameOfApplicant().equals("")){
            addFieldError(getText("error.card"), getText("error.invalid.name"));
        }
    }
}

Body:
You can use getText() if your action bean implements TextProvider. If you extend ActionSupport it's already implemented by default.

To use getText() the action should implement TextProvider that
what ActionSupport is for. If your action class extends
ActionSupport then you can use default implementation of
TextProvider and can use the code above.

For other beans you can get the action instance which implements a TextProvider. For example

ActionSupport action = (ActionSupport)ActionContext.getContext().getActionInvocation().getAction();
String text = action.getText("error.card");

But the first parameter in addFieldError(), doesn't need getText(). It's used for the name of the field which would have an error.


问:
Stripe Elements Google Web Font Not Working
I can't get Stripe Elements to use Google's Lato. I know there are other questions similar to this one but I don't see anything that applies. I tried fixing this for a while with no luck

```<code>var windowHash = getWindowHash();
var stripe = Stripe(stripePubKey);
var elements = stripe.elements({
  fonts: [
    {
      family: "'Lato'",
      src: 'local("Lato"), local("lato"), url(https://fonts.gstatic.com/s/lato/v13/dPJ5r9gl3kK6ijoeP1IRsvY6323mHUZFJMgTvxaG2iE.woff2) format("woff2")',
      weight: 300,
      style: "normal",
      unicodeRange: "U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF"
    }
  ]
});

var card = elements.create('card', {
  iconStyle: 'solid',
  hidePostalCode: true,
  style: {
    base: {
      iconColor: '#3cacce',
      color: '#424B54',
      lineHeight: '36px',
      fontWeight: 300,
      fontFamily: '"Lato", sans-serif',
      fontSize: '13pt',
      fontStyle: "normal",
      '::placeholder': {
        color: '#969696'
      },
    },
    invalid: {
      iconColor: '#b32903',
      color: '#b32903',
    }
  },
  classes: {
    focus: 'is-focused',
    empty: 'is-empty',
  },
});
</code>```

And somewhere else:

```<code>card.mount('.cardElement');
</code>```

Any tips on how I can get this to display properly?

Update:

Found the problem! I was trying to load in Lato Light, but because the normal Lato was added, using 300 wight didn't work. Adding the Lato Light font made it work.

答:
Reason: Have to use latin link and unicode range. Not the latin-ext font face for Lato font (latin and latin-ext)

Use the following fonts parameters

```<code>fonts: [
    {
      family: '"Lato"',
      src: 'local("Lato Regular"), local("Lato-Regular"), url(https://fonts.gstatic.com/s/lato/v13/MDadn8DQ_3oT6kvnUq_2r_esZW2xOQ-xsNqO47m55DA.woff2) format("woff2")',
      weight: 300,
      style: 'normal',
      unicodeRange: 'U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215'
    }
  ]
</code>```

Body:
I can't get Stripe Elements to use Google's Lato. I know there are other questions similar to this one but I don't see anything that applies. I tried fixing this for a while with no luck

var windowHash = getWindowHash();
var stripe = Stripe(stripePubKey);
var elements = stripe.elements({
  fonts: [
    {
      family: "'Lato'",
      src: 'local("Lato"), local("lato"), url(https://fonts.gstatic.com/s/lato/v13/dPJ5r9gl3kK6ijoeP1IRsvY6323mHUZFJMgTvxaG2iE.woff2) format("woff2")',
      weight: 300,
      style: "normal",
      unicodeRange: "U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF"
    }
  ]
});

var card = elements.create('card', {
  iconStyle: 'solid',
  hidePostalCode: true,
  style: {
    base: {
      iconColor: '#3cacce',
      color: '#424B54',
      lineHeight: '36px',
      fontWeight: 300,
      fontFamily: '"Lato", sans-serif',
      fontSize: '13pt',
      fontStyle: "normal",
      '::placeholder': {
        color: '#969696'
      },
    },
    invalid: {
      iconColor: '#b32903',
      color: '#b32903',
    }
  },
  classes: {
    focus: 'is-focused',
    empty: 'is-empty',
  },
});

And somewhere else:

card.mount('.cardElement');

Any tips on how I can get this to display properly?

Update:

Found the problem! I was trying to load in Lato Light, but because the normal Lato was added, using 300 wight didn't work. Adding the Lato Light font made it work.

Body:
Reason: Have to use latin link and unicode range. Not the latin-ext font face for Lato font (latin and latin-ext)

Use the following fonts parameters

fonts: [
    {
      family: '"Lato"',
      src: 'local("Lato Regular"), local("Lato-Regular"), url(https://fonts.gstatic.com/s/lato/v13/MDadn8DQ_3oT6kvnUq_2r_esZW2xOQ-xsNqO47m55DA.woff2) format("woff2")',
      weight: 300,
      style: 'normal',
      unicodeRange: 'U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215'
    }
  ]


问:
MSSQL Query Error: "Cannot insert the value NULL into column <X>."

Following error occurs in /// this coding "

Cannot insert the value NULL into column 'boarding', table 'C:\USERS\VBI SERVER\DOCUMENTS\VISUAL STUDIO 2008\WEBSITES\VOLVO\APP_DATA\ASPNETDB.MDF.dbo.boardingpt'; column does not allow nulls. INSERT fails. The statement has been terminated.

```<code>Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand
        con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True"
        con.Open()
        cmd.Connection = con
        cmd.CommandText = "INSERT INTO boardingpt (service, travelid, bdpt_name, time) VALUES('" & Trim(TextBox3.Text.ToString) & "', '" & Trim(TextBox4.Text.ToString) & "', '" & Trim(TextBox1.Text.ToString) & "','" & Trim(TextBox2.Text.ToString) & "')"
        cmd.ExecuteNonQuery()
        con.Close()

    End Sub
</code>```

答:
You are trying to insert NULL value for the column which is set to NOT NULL.

Solution

Make boarding column to ALLOW NULL and remove Primary key (because primary key never can be null)

or

Set IDENTITY to YES in your table design mode for boarding column

Hope this helps

Thanks
Vivek

Body:
Following error occurs in /// this coding "

Cannot insert the value NULL into column 'boarding', table 'C:\USERS\VBI SERVER\DOCUMENTS\VISUAL STUDIO 2008\WEBSITES\VOLVO\APP_DATA\ASPNETDB.MDF.dbo.boardingpt'; column does not allow nulls. INSERT fails. The statement has been terminated.

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand
        con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True"
        con.Open()
        cmd.Connection = con
        cmd.CommandText = "INSERT INTO boardingpt (service, travelid, bdpt_name, time) VALUES('" & Trim(TextBox3.Text.ToString) & "', '" & Trim(TextBox4.Text.ToString) & "', '" & Trim(TextBox1.Text.ToString) & "','" & Trim(TextBox2.Text.ToString) & "')"
        cmd.ExecuteNonQuery()
        con.Close()

    End Sub

ContentLicense: CC BY-SA 2.5


问:
Data Tables. fix first column so not sort-able
I have a data table. The first column is the position and is a increments so example has 1, 2, 3, 4. Showing the position a row is in. The rest of the columns i want sort-able. So when sorted by number of jobs, or total value the first column stays the same but the rest change.

I have tried using fixed column but this is not that i want.

```<code><table class="datatable">
                        <thead>
                            <tr>
                                <th>Position</th>
                                <th class="no-sort">Name</th>
                                <th class="no-sort">Jobs</th>
                                <th class="no-sort">Labour</th>
                                <th class="no-sort">Total</th>
                            </tr>
                        </thead>
                        @{int count = 1;}
                        @foreach (Model make in Model.Models)
                        {
                            <tr>
                                <td>@(count)</td>
                                <td>@make.Name</td>
                                <td>@make.Jobs</td>
                                <td>@Math.Round(make.Labour, 2)</td>
                                 <td>@Math.Round(make.Total, 2)</td>
                            </tr>
                            { count++; }
                        }
                    </table>

  var Table = $('.datatable').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bScrollCollapse": true,
        "bFilter": false, "bInfo": false,
        "aaSorting": [[2, 'desc']],
        "columnDefs": [ {
            "targets": 'no-sort',
            "orderable": false,
        } ],
        "aoColumns": [
            { "bSearchable": false },
            { "bSearchable": false },
            { "bSearchable": false },
       { "bSearchable": false },
          { "bSearchable": false },
            { "bSearchable": false }
        ]
    });
</code>```

答:
Please try this in your datatable code:</p>

```<code> "columnDefs": [
    { "orderable": false, "targets": 0 }
 ]
</code>```

Body:
I have a data table. The first column is the position and is a increments so example has 1, 2, 3, 4. Showing the position a row is in. The rest of the columns i want sort-able. So when sorted by number of jobs, or total value the first column stays the same but the rest change.

I have tried using fixed column but this is not that i want.

                                Position
                                Name
                                Jobs
                                Labour
                                Total

                        @{int count = 1;}
                        @foreach (Model make in Model.Models)
                        {

                                @(count)
                                @make.Name
                                @make.Jobs
                                @Math.Round(make.Labour, 2)
                                 @Math.Round(make.Total, 2)

                            { count++; }
                        }

  var Table = $('.datatable').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bScrollCollapse": true,
        "bFilter": false, "bInfo": false,
        "aaSorting": [[2, 'desc']],
        "columnDefs": [ {
            "targets": 'no-sort',
            "orderable": false,
        } ],
        "aoColumns": [
            { "bSearchable": false },
            { "bSearchable": false },
            { "bSearchable": false },
       { "bSearchable": false },
          { "bSearchable": false },
            { "bSearchable": false }
        ]
    });

Body:
Please try this in your datatable code:

 "columnDefs": [
    { "orderable": false, "targets": 0 }
 ]


问:
how to configure server Jenkins with github?
In Github i have created webhooks (http://192.168.10.98:8080/github-webhook/) and in Intergration & Services tab,I have added Jenkins (Github Plugin).
In webhooks its showing

```<code> "We couldn’t deliver this payload: Couldn't connect to server".
</code>```

In Jenkins,build trigger (i chooses GitHub hook trigger for GITScm polling)
Code changes are showing in Jenkins dashboard but its not updating in Server.What i need to configure for updating that changed codes through Jenkins?Can anybody help me?

答: Github will have problems if you enter a local IP address as a target for the webhook. It cannot access the given IP.</p>

Body:
In Github i have created webhooks (http://192.168.10.98:8080/github-webhook/) and in Intergration & Services tab,I have added Jenkins (Github Plugin).
In webhooks its showing

 "We couldn’t deliver this payload: Couldn't connect to server".

In Jenkins,build trigger (i chooses GitHub hook trigger for GITScm polling)
Code changes are showing in Jenkins dashboard but its not updating in Server.What i need to configure for updating that changed codes through Jenkins?Can anybody help me?


问:
nodejs equivalent Pattern.compile
this code on java/android work fine to find all texts between <tag> and </tag>

whats equivalent of my code on java on nodejs/javascript?

```<code>private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>");

private void getTagValues(final String str) {
    final Matcher matcher = TAG_REGEX.matcher(str);
    while (matcher.find()) {
        // print found text
    }
}
</code>```

for example:

```<code>var value = "<tag>text 1</tag> aaaaa <tag>text 2</tag>";
var regex = '<tag>(.+?)</tag>';
var match = regex.test(value);
while (matcher.find()) {
    if (match) {
        console.log(value + 'is not a number that has between 1,20 digits');
    }
}
</code>```

答:
I changed your code try this.This code is working as your expectations.Hope this helps for you.

```<code>var express=require('express');
var app=express();
app.get('/tag',function(request,response)
{
var value="<tag>text 1</tag>,aaaaa<tag>text 2</tag>.";
var regex="<tag>(.+?)</tag>.";
var result=value.match(/<tag>(.*?)<\/tag>/g).map(function(val){
var first=val.replace(/<\/?tag>/g,'');
console.log(first);
});
var match=regex.match(/<tag>(.*?)<\/tag>/g).map(function(valy){
var second=valy.replace(/<\/?tag>/g,'');
console.log(second);
});
response.send("data send");
});
app.listen(3000,function(){
console.log("Server is listening on http://localhost:3000");
});
</code>```

See output in a browser as localhost:3000/tag and see the text between tags in terminal.

Title: nodejs equivalent Pattern.compile

Body:
this code on java/android work fine to find all texts between <tag> and </tag>

whats equivalent of my code on java on nodejs/javascript?

private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>");

private void getTagValues(final String str) {
    final Matcher matcher = TAG_REGEX.matcher(str);
    while (matcher.find()) {
        // print found text
    }
}

for example:

var value = "<tag>text 1</tag> aaaaa <tag>text 2</tag>";
var regex = '<tag>(.+?)</tag>';
var match = regex.test(value);
while (matcher.find()) {
    if (match) {
        console.log(value + 'is not a number that has between 1,20 digits');
    }
}

Body:
I changed your code try this.This code is working as your expectations.Hope this helps for you.

var express=require('express');
var app=express();
app.get('/tag',function(request,response)
{
var value="<tag>text 1</tag>,aaaaa<tag>text 2</tag>.";
var regex="<tag>(.+?)</tag>.";
var result=value.match(/<tag>(.*?)<\/tag>/g).map(function(val){
var first=val.replace(/<\/?tag>/g,'');
console.log(first);
});
var match=regex.match(/<tag>(.*?)<\/tag>/g).map(function(valy){
var second=valy.replace(/<\/?tag>/g,'');
console.log(second);
});
response.send("data send");
});
app.listen(3000,function(){
console.log("Server is listening on http://localhost:3000");
});

See output in a browser as localhost:3000/tag and see the text between tags in terminal.


问:
UIButton doesn't resize to fit its titleLabel
I'm working with iOS8 Self-Sizing cell and I want the cell resize to fit its subview, messageBodyButton and profileImageView.

profileImageView's size is fixed. As you can see in the picture below, the messageBodyButton doesn't resize to fit its titleLabel.

Why did this happen? How to fix this bug using Auto Layout?

And when the titleLabel's content changed(say, the model's data changed), how should I update constraints so that the cell height can be calculated correctly?

Here is my code:

RXTChatCell.m:

```<code>@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIImageView *profileImageView;
@property (nonatomic, strong) UIButton *messageBodyButton;

@property (nonatomic, assign) BOOL needUpdateConstraints;
@property (nonatomic, assign) BOOL didSetUpConstraints;

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _timeLabel = [[UILabel alloc] init];
        _timeLabel.text = @"19:00";
        [self.contentView addSubview:_timeLabel];

        _profileImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"placeholder"]];
        [self.contentView addSubview:_profileImageView];

        _messageBodyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_messageBodyButton.titleLabel setLineBreakMode:NSLineBreakByTruncatingTail];
        [_messageBodyButton.titleLabel setTextAlignment:NSTextAlignmentRight];
        _messageBodyButton.titleLabel.numberOfLines = 0;
        _messageBodyButton.titleLabel.backgroundColor = UIColor.grayColor;
        [self.contentView addSubview:_messageBodyButton];

        _timeLabel.backgroundColor = UIColor.redColor;
        _profileImageView.backgroundColor = UIColor.greenColor;
        _messageBodyButton.backgroundColor = UIColor.blueColor;
        self.contentView.backgroundColor = UIColor.orangeColor;
    }
    return self;
}

- (void)updateConstraints
{
    if (!self.didSetUpConstraints) { // set up constraints
        [_timeLabel makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView.topMargin);
            make.centerX.equalTo(self.contentView);
        }];

        [_profileImageView makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_timeLabel.bottom).offset(10);
            make.right.equalTo(self.contentView).offset(-10);
            make.width.and.height.equalTo(50);
            make.bottom.lessThanOrEqualTo(self.contentView.bottomMargin);
        }];

        [_messageBodyButton makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_profileImageView);
            make.right.equalTo(_profileImageView.left).offset(-10);
            make.left.equalTo(self.contentView).offset(10);
            make.bottom.lessThanOrEqualTo(self.contentView.bottomMargin);
        }];
        self.didSetUpConstraints = YES;
    }

    if (self.needUpdateConstraints){
        // here, how should I update constraints?

    }

    [super updateConstraints];
}

- (void)setMessage:(RXTChatMessage *)message
{
    EMTextMessageBody *body = (EMTextMessageBody *)message.messageBody.body;
    [self.messageBodyButton setTitle:body.text forState:UIControlStateNormal];
    self.needUpdateConstraints = YES;
    [self setNeedsUpdateConstraints];
}
</code>```

RXTChatViewController.m:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RXTChatMessage *message = self.messages[indexPath.row];
    RXTChatCell *cell = [tableView dequeueReusableCellWithIdentifier:RXTChatCellId];
    if (cell == nil) {
        cell = [[self alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RXTChatCellId];
    }
    cell.message = message;

    return cell;
}
</code>```

答:
Select Your Button -> Go to Editor -> Size to fit content.

Remove fixed height constraint for your button (only set leading,trailing,top bottom) constraint (Superview should be your cell view).

This should solve your problem

let me know if it solves your issue.

Body:
I'm working with iOS8 Self-Sizing cell and I want the cell resize to fit its subview, messageBodyButton and profileImageView.

profileImageView's size is fixed. As you can see in the picture below, the messageBodyButton doesn't resize to fit its titleLabel.

Why did this happen? How to fix this bug using Auto Layout?

And when the titleLabel's content changed(say, the model's data changed), how should I update constraints so that the cell height can be calculated correctly?

Here is my code:

RXTChatCell.m:

@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIImageView *profileImageView;
@property (nonatomic, strong) UIButton *messageBodyButton;

@property (nonatomic, assign) BOOL needUpdateConstraints;
@property (nonatomic, assign) BOOL didSetUpConstraints;

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _timeLabel = [[UILabel alloc] init];
        _timeLabel.text = @"19:00";
        [self.contentView addSubview:_timeLabel];

        _profileImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"placeholder"]];
        [self.contentView addSubview:_profileImageView];

        _messageBodyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_messageBodyButton.titleLabel setLineBreakMode:NSLineBreakByTruncatingTail];
        [_messageBodyButton.titleLabel setTextAlignment:NSTextAlignmentRight];
        _messageBodyButton.titleLabel.numberOfLines = 0;
        _messageBodyButton.titleLabel.backgroundColor = UIColor.grayColor;
        [self.contentView addSubview:_messageBodyButton];

        _timeLabel.backgroundColor = UIColor.redColor;
        _profileImageView.backgroundColor = UIColor.greenColor;
        _messageBodyButton.backgroundColor = UIColor.blueColor;
        self.contentView.backgroundColor = UIColor.orangeColor;
    }
    return self;
}

- (void)updateConstraints
{
    if (!self.didSetUpConstraints) { // set up constraints
        [_timeLabel makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView.topMargin);
            make.centerX.equalTo(self.contentView);
        }];

        [_profileImageView makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_timeLabel.bottom).offset(10);
            make.right.equalTo(self.contentView).offset(-10);
            make.width.and.height.equalTo(50);
            make.bottom.lessThanOrEqualTo(self.contentView.bottomMargin);
        }];

        [_messageBodyButton makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_profileImageView);
            make.right.equalTo(_profileImageView.left).offset(-10);
            make.left.equalTo(self.contentView).offset(10);
            make.bottom.lessThanOrEqualTo(self.contentView.bottomMargin);
        }];
        self.didSetUpConstraints = YES;
    }

    if (self.needUpdateConstraints){
        // here, how should I update constraints?

    }

    [super updateConstraints];
}

- (void)setMessage:(RXTChatMessage *)message
{
    EMTextMessageBody *body = (EMTextMessageBody *)message.messageBody.body;
    [self.messageBodyButton setTitle:body.text forState:UIControlStateNormal];
    self.needUpdateConstraints = YES;
    [self setNeedsUpdateConstraints];
}

RXTChatViewController.m:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RXTChatMessage *message = self.messages[indexPath.row];
    RXTChatCell *cell = [tableView dequeueReusableCellWithIdentifier:RXTChatCellId];
    if (cell == nil) {
        cell = [[self alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RXTChatCellId];
    }
    cell.message = message;

    return cell;
}


问:
Tool to detect non-dotted relative imports in Python?
It's considered bad Python to use imports like this:

```<code>import my_module
</code>```

When you are doing a relative import and this would work:

```<code>from . import my_module
</code>```

Is there a tool that can detect these non-dotted relative imports in my code and warn me so I could update them to the dotted syntax? My project has hundreds of Python modules and I would like to do this automatically. (Possibly such a tool would override __import__ and detect the bad imports as they happen when I run the program.)

Does anyone know of such tool?

答:
[Reposted as an answer because it apparently did the trick]

2to3 will automatically convert them, because it's compulsory in Python 3.

Here's the relevant source code if you want to modify it for your purposes.

Alternatively, you could just run 2to3 with only that fixer: 2to3 -w -f import myproject/

Body:
It's considered bad Python to use imports like this:

import my_module

When you are doing a relative import and this would work:

from . import my_module

Is there a tool that can detect these non-dotted relative imports in my code and warn me so I could update them to the dotted syntax? My project has hundreds of Python modules and I would like to do this automatically. (Possibly such a tool would override __import__ and detect the bad imports as they happen when I run the program.)

Does anyone know of such tool?


问:
How to handle Python KeyError while implementing automata?
I am implementing a simple automata function using Python.

```<code>def RunAutomata(transition, initial, accepting, s):
    state = initial
    for c in s:
        try:
            state = transition[state][c]
        except KeyError:
            return False
    return state in accepting

dfa = {0:{'a':1, 'b':2},
       1:{'c':3,'d':2},
       2:{'f':3},
       3:{'e':1}}

RunAutomata(dfa, 0, {2}, 'bfecedfedf')
</code>```

Intuition for this piece of code: It checks the dfa and string to find out whether that string is accepted under the given dfa. If accepted return True else return False.

Here you can see, in the dictionary, I have used alphabetic keys, So while traversing, if key not found, it throws KeyError.
I handle it using try-except block, but I want to know if any better alternative available for this to work with out using exception handling funda.

Edit: Got a solution from @omri_sadon. Thank you. Please feel free to post some other different ways as well.

答:
You can use the dict get method .

```<code>transition.get(state) # default for None

transition.get(state, False) # If key not in dict, False is returned
</code>```

The method get() returns the value within a given key.

If key is not in the dict, the default value is returned.

Body:
I am implementing a simple automata function using Python.

def RunAutomata(transition, initial, accepting, s):
    state = initial
    for c in s:
        try:
            state = transition[state][c]
        except KeyError:
            return False
    return state in accepting

dfa = {0:{'a':1, 'b':2},
       1:{'c':3,'d':2},
       2:{'f':3},
       3:{'e':1}}

RunAutomata(dfa, 0, {2}, 'bfecedfedf')

Intuition for this piece of code: It checks the dfa and string to find out whether that string is accepted under the given dfa. If accepted return True else return False.

Here you can see, in the dictionary, I have used alphabetic keys, So while traversing, if key not found, it throws KeyError.
I handle it using try-except block, but I want to know if any better alternative available for this to work with out using exception handling funda.

Edit: Got a solution from @omri_sadon. Thank you. Please feel free to post some other different ways as well.

Body:
You can use the dict get method .

transition.get(state) # default for None

transition.get(state, False) # If key not in dict, False is returned

The method get() returns the value within a given key.

If key is not in the dict, the default value is returned.


问:
Android Bottom Navigation bar not opening activity as linked to it
I am a newbie to Android development. I am learning UI designing as of now. I want a solution where there is a bottom bar with 5 options linked directly to 5 different activities. I got Java solutions from other stack overflow answers (How to change activity on bottom navigation button click? ) - 2nd Answer by sushil, but it has no activity - XML files in it for me to understand.

Bottom bar like this:

Activity to be loaded based on bottom bar:

答:
As per your attached image, you should used Fragment instead of Activity for 5 different MenuItem or options to achieve your desired output.

1. Create 5 different Fragments for 5 different MenuItem.
For example: MatchingFragment, WatchListFragment, RatesFragment, DealsFragment and ListingFragment.

2. Add OnNavigationItemSelectedListener to your NavigationView and  change Fragment as per your selected MenuItem. Use below code to change Fragment:

```<code>// Set action to perform when any menu-item is selected.
bottomNavigationView.setOnNavigationItemSelectedListener(
    new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            // Change Fragment
            selectFragment(item);
            return false;
        }
    });

/**
 * Perform action when any item is selected.
 *
 * @param item Item that is selected.
 */
protected void selectFragment(MenuItem item) {

    item.setChecked(true);

    switch (item.getItemId()) {
        case R.id.action_matching:
            // Action to perform when Matching Menu item is selected.
            pushFragment(new MatchingFragment());
            break;
        case R.id.action_watch_list:
            // Action to perform when WatchList Menu item is selected.
            pushFragment(new WatchListFragment());
            break;
        case R.id.action_rates:
            // Action to perform when Rates Menu item is selected.
            pushFragment(new RatesFragment());
            break;
        case R.id.action_deals:
            // Action to perform when Deals Menu item is selected.
            pushFragment(new DealsFragment());
            break;
        case R.id.action_listing:
            // Action to perform when Listing Menu item is selected.
            pushFragment(new ListingFragment());
            break;
    }
}

/**
 * Method to push any fragment into given id.
 *
 * @param fragment An instance of Fragment to show into the given id.
 */
protected void pushFragment(Fragment fragment) {
    if (fragment == null)
        return;

    FragmentManager fragmentManager = getFragmentManager();
    if (fragmentManager != null) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (ft != null) {
            ft.replace(R.id.rootLayout, fragment);
            ft.commit();
        }
    }
}
</code>```

Here is the complete Tutorial: Android Bottom Navigation View Tutorial With Example

Hope this will help~

Body:
As per your attached image, you should used Fragment instead of Activity for 5 different MenuItem or options to achieve your desired output.

1. Create 5 different Fragments for 5 different MenuItem.
For example: MatchingFragment, WatchListFragment, RatesFragment, DealsFragment and ListingFragment.

2. Add OnNavigationItemSelectedListener to your NavigationView and  change Fragment as per your selected MenuItem. Use below code to change Fragment:

// Set action to perform when any menu-item is selected.
bottomNavigationView.setOnNavigationItemSelectedListener(
    new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            // Change Fragment
            selectFragment(item);
            return false;
        }
    });

/**
 * Perform action when any item is selected.
 *
 * @param item Item that is selected.
 */
protected void selectFragment(MenuItem item) {

    item.setChecked(true);

    switch (item.getItemId()) {
        case R.id.action_matching:
            // Action to perform when Matching Menu item is selected.
            pushFragment(new MatchingFragment());
            break;
        case R.id.action_watch_list:
            // Action to perform when WatchList Menu item is selected.
            pushFragment(new WatchListFragment());
            break;
        case R.id.action_rates:
            // Action to perform when Rates Menu item is selected.
            pushFragment(new RatesFragment());
            break;
        case R.id.action_deals:
            // Action to perform when Deals Menu item is selected.
            pushFragment(new DealsFragment());
            break;
        case R.id.action_listing:
            // Action to perform when Listing Menu item is selected.
            pushFragment(new ListingFragment());
            break;
    }
}

/**
 * Method to push any fragment into given id.
 *
 * @param fragment An instance of Fragment to show into the given id.
 */
protected void pushFragment(Fragment fragment) {
    if (fragment == null)
        return;

    FragmentManager fragmentManager = getFragmentManager();
    if (fragmentManager != null) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (ft != null) {
            ft.replace(R.id.rootLayout, fragment);
            ft.commit();
        }
    }
}

Here is the complete Tutorial: Android Bottom Navigation View Tutorial With Example

Hope this will help~


问:
Spring Instance Factory not working
I started learning spring recently and doing a simple demo of Instance factory but getting error.
Java Bean:

```<code>  package beans;

public class Apache implements Bike
{

    @Override
    public void getSpeed()
    {
        System.out.println("160 KMPH");
    }

}
</code>```

Interface:

```<code>    package beans;

public interface Bike
{
    public void getSpeed();
}
</code>```

Factory:

```<code>package beans;

public class BikeFactory
{
    public String bikename;

    public void setBikename(String bikename) {
        this.bikename = bikename;
    }

    public Bike getInstance() throws Exception
    {
        Bike bike = (Bike) Class.forName("bikename").newInstance();
        return bike;
    }
}
</code>```

Spring config

```<code>    <?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="bf" class="beans.BikeFactory">
    <property name="bikename" value="beans.Apache"></property>
   </bean>

   <bean id="a" factory-bean="bf" factory-method="getInstance"></bean>
</beans>
</code>```

When I run the code by getting Bike Object from context, I get below error:

```<code>    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'a' defined in class path resource [resources/spring-config.xml]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [beans.Bike]: Factory method 'getInstance' threw exception; nested exception is java.lang.ClassNotFoundException: bikename
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at utils.Tester.main(Tester.java:12)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [beans.Bike]: Factory method 'getInstance' threw exception; nested exception is java.lang.ClassNotFoundException: bikename
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 14 more
Caused by: java.lang.ClassNotFoundException: bikename
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
</code>```

Am I missing something here? Please help

答:
Your factory method is incorrect. I guess you want to create instance by class name which you autowire by spring, so you don't need double quotes here:

```<code>public Bike getInstance() throws Exception {
    Bike bike = (Bike) Class.forName(bikename).newInstance();
    return bike;
}
</code>```

Try to change "bikename" to bikename

Title: Spring Instance Factory not working

Body:
I started learning spring recently and doing a simple demo of Instance factory but getting error.
Java Bean:

  package beans;

public class Apache implements Bike
{

    @Override
    public void getSpeed()
    {
        System.out.println("160 KMPH");
    }

}

Interface:

    package beans;

public interface Bike
{
    public void getSpeed();
}

Factory:

package beans;

public class BikeFactory
{
    public String bikename;

    public void setBikename(String bikename) {
        this.bikename = bikename;
    }

    public Bike getInstance() throws Exception
    {
        Bike bike = (Bike) Class.forName("bikename").newInstance();
        return bike;
    }
}

Spring config

    <?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="bf" class="beans.BikeFactory">
    <property name="bikename" value="beans.Apache"></property>
   </bean>

   <bean id="a" factory-bean="bf" factory-method="getInstance"></bean>
</beans>

When I run the code by getting Bike Object from context, I get below error:

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'a' defined in class path resource [resources/spring-config.xml]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [beans.Bike]: Factory method 'getInstance' threw exception; nested exception is java.lang.ClassNotFoundException: bikename
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at utils.Tester.main(Tester.java:12)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [beans.Bike]: Factory method 'getInstance' threw exception; nested exception is java.lang.ClassNotFoundException: bikename
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 14 more
Caused by: java.lang.ClassNotFoundException: bikename
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)

Am I missing something here? Please help

Body:
Your factory method is incorrect. I guess you want to create instance by class name which you autowire by spring, so you don't need double quotes here:

public Bike getInstance() throws Exception {
    Bike bike = (Bike) Class.forName(bikename).newInstance();
    return bike;
}

Try to change "bikename" to bikename


问:
PHPExcel verify if cell has empy value
Hello i have an import of an xls file with multiple rows on it and i want to insert them into database only if the price columns has a value different than nothing else display an error msg. It works on half it only inserts those rows that have a value for price but instead returning the html error msg it returns the sql msg, that means it goes on the else branch.
Here is my code</p>

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

$uploadFilePath = 'uploads/'.basename($_FILES['doc']['name']);
        move_uploaded_file($_FILES['doc']['tmp_name'], $uploadFilePath);

        $inputfilename = 'uploads/'.$_FILES['doc']['name'].'';
//  Read your Excel workbook
try
{
    $inputfiletype = PHPExcel_IOFactory::identify($inputfilename);
    $objReader = PHPExcel_IOFactory::createReader($inputfiletype);
    $objPHPExcel = $objReader->load($inputfilename);
}
catch(Exception $e)
{
    die('Error loading file "'.pathinfo($inputfilename,PATHINFO_BASENAME).'": '.$e->getMessage());
}

//  Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();

$header=$_POST['membership'];

if($header==1)
{
//  Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++)
{

    //  Read a row of data into an array
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
    if ($rowData[0][9]=='')
    {
        echo 'No price for the product '.$rowData[0][1].'';
    }
    else
    {
    $a = array('8', '1', '2', '3', '4', '5','6');
    $b = array($rowData[0][0], $rowData[0][2], $rowData[0][3],$rowData[0][5],$rowData[0][6],$rowData[0][8],$rowData[0][8]);
    $c = array_combine($a, $b);

    $slug = str_replace(" ", "-",$rowData[0][1]);
$slug = str_replace('"', "",$slug);
$slug = str_replace('/', "-",$slug);
    $stmt=$dbh->prepare("INSERT INTO tbl_products (name,slug,description,price)
                    VALUES (:name,:slug,:desc,:pret)");

$stmt->bindParam(":name",$rowData[0][1]);
$stmt->bindParam(":slug",$slug);
$stmt->bindParam(":desc",$rowData[0][10]);
$stmt->bindParam(":pret",$rowData[0][9]);

$stmt->execute();
$id_product=$dbh->lastInsertId();

$stmt=$dbh->prepare("INSERT INTO tbl_products_images_gallery (id_product,name,image,sort_order)
                    VALUES (:id,:name,:image,100)");

$stmt->bindParam(":id",$id_product);
$stmt->bindParam(":name",$rowData[0][4]);
$stmt->bindParam(":image",$slug);

$stmt->execute();

$stmt=$dbh->prepare("SELECT id_category from tbl_catalog_categories where name=:name");
$stmt->bindParam(":name",$rowData[0][2]);
$stmt->execute();
if($row=$stmt->fetch())
{
    $id_cat=$row['id_category'];
}

$stmt=$dbh->prepare("INSERT INTO tbl_products_to_categories (id_category,id_product)
                    VALUES (:id_cat,:id_prod)");

$stmt->bindParam(":id_cat",$id_cat);
$stmt->bindParam(":id_prod",$id_product);

$stmt->execute();

foreach($c as $key => $value)
    {

        $stmt=$dbh->prepare("INSERT INTO tbl_products_attributes_values (id_product,id_attribute,attribute_value)
                    VALUES (:id_product,:id_attribute,:value)");
$stmt->bindParam(":id_product",$id_product);
$stmt->bindParam(":id_attribute",$key);
$stmt->bindParam(":value",$value);
$stmt->execute();
    }

}
}
}
</code>```

答:
if (empty($rowData[0][9])) perhaps?

Or test for null as well as for empty strings - nulls are perfectly valid response from PHPExcel...

especially as

```<code>$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
</code>```

with it's null second argument is telling PHPExcel to return a null value if the cell simply doesn't exist in the spreadsheet

Though you can change the rangeToArray() call to

```<code>$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, '', TRUE, FALSE);
</code>```

to return an empty string instead of a null if the cell doesn't exist

Title: PHPExcel verify if cell has empy value

Body:
Hello i have an import of an xls file with multiple rows on it and i want to insert them into database only if the price columns has a value different than nothing else display an error msg. It works on half it only inserts those rows that have a value for price but instead returning the html error msg it returns the sql msg, that means it goes on the else branch.
Here is my code

$exceldata = array();

$uploadFilePath = 'uploads/'.basename($_FILES['doc']['name']);
        move_uploaded_file($_FILES['doc']['tmp_name'], $uploadFilePath);

        $inputfilename = 'uploads/'.$_FILES['doc']['name'].'';
//  Read your Excel workbook
try
{
    $inputfiletype = PHPExcel_IOFactory::identify($inputfilename);
    $objReader = PHPExcel_IOFactory::createReader($inputfiletype);
    $objPHPExcel = $objReader->load($inputfilename);
}
catch(Exception $e)
{
    die('Error loading file "'.pathinfo($inputfilename,PATHINFO_BASENAME).'": '.$e->getMessage());
}

//  Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();

$header=$_POST['membership'];

if($header==1)
{
//  Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++)
{

    //  Read a row of data into an array
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
    if ($rowData[0][9]=='')
    {
        echo 'No price for the product '.$rowData[0][1].'';
    }
    else
    {
    $a = array('8', '1', '2', '3', '4', '5','6');
    $b = array($rowData[0][0], $rowData[0][2], $rowData[0][3],$rowData[0][5],$rowData[0][6],$rowData[0][8],$rowData[0][8]);
    $c = array_combine($a, $b);

    $slug = str_replace(" ", "-",$rowData[0][1]);
$slug = str_replace('"', "",$slug);
$slug = str_replace('/', "-",$slug);
    $stmt=$dbh->prepare("INSERT INTO tbl_products (name,slug,description,price)
                    VALUES (:name,:slug,:desc,:pret)");

$stmt->bindParam(":name",$rowData[0][1]);
$stmt->bindParam(":slug",$slug);
$stmt->bindParam(":desc",$rowData[0][10]);
$stmt->bindParam(":pret",$rowData[0][9]);

$stmt->execute();
$id_product=$dbh->lastInsertId();

$stmt=$dbh->prepare("INSERT INTO tbl_products_images_gallery (id_product,name,image,sort_order)
                    VALUES (:id,:name,:image,100)");

$stmt->bindParam(":id",$id_product);
$stmt->bindParam(":name",$rowData[0][4]);
$stmt->bindParam(":image",$slug);

$stmt->execute();

$stmt=$dbh->prepare("SELECT id_category from tbl_catalog_categories where name=:name");
$stmt->bindParam(":name",$rowData[0][2]);
$stmt->execute();
if($row=$stmt->fetch())
{
    $id_cat=$row['id_category'];
}

$stmt=$dbh->prepare("INSERT INTO tbl_products_to_categories (id_category,id_product)
                    VALUES (:id_cat,:id_prod)");

$stmt->bindParam(":id_cat",$id_cat);
$stmt->bindParam(":id_prod",$id_product);

$stmt->execute();

foreach($c as $key => $value)
    {

        $stmt=$dbh->prepare("INSERT INTO tbl_products_attributes_values (id_product,id_attribute,attribute_value)
                    VALUES (:id_product,:id_attribute,:value)");
$stmt->bindParam(":id_product",$id_product);
$stmt->bindParam(":id_attribute",$key);
$stmt->bindParam(":value",$value);
$stmt->execute();
    }

}
}
}

Body:
if (empty($rowData[0][9])) perhaps?

Or test for null as well as for empty strings - nulls are perfectly valid response from PHPExcel...

especially as

$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);

with it's null second argument is telling PHPExcel to return a null value if the cell simply doesn't exist in the spreadsheet

Though you can change the rangeToArray() call to

$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, '', TRUE, FALSE);

to return an empty string instead of a null if the cell doesn't exist


问:
React set up error while running npm start :Configuration file found but no entry configured. Use --help to display the CLI options
I am getting error while setting environment for my react app.
I have not done any thing as per coding prospective .
Its just a hello world programme in react.
I have also uploaded my node modules in the below given url .

I have put down my code in Github  : https://github.com/Arpan1089/reactapp

error :

reactapp@1.0.0 start C:\Users\Sumeet\Desktop\reactapp
  webpack-dev-server

Configuration file found but no entry configured.
Use --help to display the CLI options.

```<code>npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\
node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.11.0
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! reactapp@1.0.0 start: `webpack-dev-server`
npm ERR! Exit status 4294967295
npm ERR!
npm ERR! Failed at the reactapp@1.0.0 start script 'webpack-dev-server'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the reactapp package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     webpack-dev-server
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs reactapp
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls reactapp
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\Sumeet\Desktop\reactapp\npm-debug.log
</code>```

答:
Add this in your package.json inside scripts tag

```<code>"scripts": {
   "start": "webpack-dev-server --hot"
},
</code>```

and install webpack-dev-server --hot and webpack-dev-server using

```<code>npm install webpack-dev-server
</code>```

And may be you have another process running on the same port (8080) on localhost which will prevent your app to run.

Body:
I am getting error while setting environment for my react app.
I have not done any thing as per coding prospective .
Its just a hello world programme in react.
I have also uploaded my node modules in the below given url .

I have put down my code in Github  : https://github.com/Arpan1089/reactapp

error :

reactapp@1.0.0 start C:\Users\Sumeet\Desktop\reactapp
  webpack-dev-server

Configuration file found but no entry configured.
Use --help to display the CLI options.

npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\
node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.11.0
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! reactapp@1.0.0 start: `webpack-dev-server`
npm ERR! Exit status 4294967295
npm ERR!
npm ERR! Failed at the reactapp@1.0.0 start script 'webpack-dev-server'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the reactapp package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     webpack-dev-server
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs reactapp
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls reactapp
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\Sumeet\Desktop\reactapp\npm-debug.log

Body:
Add this in your package.json inside scripts tag

"scripts": {
   "start": "webpack-dev-server --hot"
},

and install webpack-dev-server --hot and webpack-dev-server using

npm install webpack-dev-server

And may be you have another process running on the same port (8080) on localhost which will prevent your app to run.


问:
Use asp include to include asp.net page
I have an asp page that uses includes to include certain pages depending on the query string.
I have built an addition to this page in asp.net and want to include my new page in the asp page, but i get this error.</p>

```<code>  Active Server Pages error 'ASP 0140'

    Page Command Out Of Order

    /d//Default.aspx, line 1

    The @ command must be the first command within the Active Server Page.
</code>```

答:
You can't include ASP.NET pages inside of an ASP page. You do, however, have a couple of options.

The easiest would be to include the ASP.NET page as an IFrame on your ASP page. You can use ASP to dynamically set the URL of the IFrame on the server side.

The other option would be to write a wrapper .NET DLL that would render your page via a method. You could then register that DLL in COM+ so that it could be called by VBScript in your ASP pages. Obviously this is more complicated.

If the first option works, go for it. Otherwise you might have to figure out how to implement the second.

Title: Use asp include to include asp.net page

Body:
I have an asp page that uses includes to include certain pages depending on the query string.
I have built an addition to this page in asp.net and want to include my new page in the asp page, but i get this error.

  Active Server Pages error 'ASP 0140'

    Page Command Out Of Order

    /d//Default.aspx, line 1

    The @ command must be the first command within the Active Server Page.


问:
How to cut highlight in iOS Charts only up to the data point?
How can I customize the highlighter in Line Charts? I want to cut the highlight to be drawn only up to the data point. I also want to customize the label on the x-axis where it's highlighted. Below is a reference picture on what I'm trying to achieve.

This is what I've done so far. What I've achieved so far

Below is the code for my Line Chart View Setup

```<code>let lineChartView: LineChartView = {
    let chart = LineChartView(frame: .zero)
    chart.chartDescription = nil
    chart.dragEnabled = true
    chart.scaleYEnabled = false
    chart.scaleXEnabled = true
    chart.pinchZoomEnabled = false
    chart.drawGridBackgroundEnabled = true
    chart.gridBackgroundColor = .clear
    chart.legend.enabled = false
    chart.zoom(scaleX: 2, scaleY: 1, x: 0, y: 0)
    chart.setViewPortOffsets(left: 30, top: 30, right: 30, bottom: 30)

    chart.rightAxis.enabled = false

    let yAxis = chart.leftAxis
    yAxis.enabled = true
    yAxis.drawAxisLineEnabled = false
    yAxis.drawLabelsEnabled = false
    yAxis.gridColor = UIColor(rgba: "#414042")
    yAxis.gridLineWidth = 1
    yAxis.axisMaximum = 6000

    chart.xAxis.enabled = true
    chart.xAxis.drawGridLinesEnabled = false
    chart.xAxis.drawLabelsEnabled = true
    chart.xAxis.drawAxisLineEnabled = true
    chart.xAxis.axisLineColor = .darkGray
    chart.xAxis.axisLineWidth = 1
    chart.xAxis.valueFormatter = IndexAxisValueFormatter(values: ["Jan", "Feb", "Mar", "April", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
    chart.xAxis.labelPosition = .bottom
    chart.xAxis.labelTextColor = .darkGray
    chart.xAxis.labelFont = UIFont.sourceSansProLight(withSize: 15.5)
    chart.xAxis.granularityEnabled = true
    chart.xAxis.granularity = 1

    chart.highlightPerTapEnabled = false

    chart.backgroundColor = .clear

    return chart
}()
</code>```

And this is the code for adding random data points in the chart and the highlight.

```<code>var values: [ChartDataEntry] = []
var highlight: Highlight? = nil

for index in 0..<12 {
    let randomValue = Double(arc4random_uniform(5000))
    values.append(ChartDataEntry(x: Double(index), y: randomValue))

    if index == 4 {
        highlight = Highlight(x: Double(index), y: randomValue, dataSetIndex: 0)
    }
}

let dataSet = LineChartDataSet(values: values, label: "")
dataSet.highlightEnabled = true
dataSet.drawHorizontalHighlightIndicatorEnabled = false
dataSet.highlightColor = UIColor(rgba: "#1899FF")
dataSet.highlightLineWidth = 1
dataSet.mode = .horizontalBezier
dataSet.circleColors = Array(repeating: UIColor(rgba: "#1899FF"), count: 12)
dataSet.fillColor = UIColor(rgba: "#1899FF")
dataSet.drawCircleHoleEnabled = false
dataSet.drawFilledEnabled = true
dataSet.lineWidth = 0.0
dataSet.drawValuesEnabled = true
dataSet.axisDependency = .left
dataSet.valueFormatter = self

let data = LineChartData(dataSet: dataSet)
data.setDrawValues(true)
data.setValueFont(UIFont.sourceSansProLight(withSize: 15.5))
data.setValueTextColor(UIColor(rgba: "#1899FF"))

lineChartView.data = data
lineChartView.highlightValue(highlight)
</code>```

答:
For Highlight Area of data point you can use below property and achieve this

All property can use through dataSet so for that you can create LineChartDataSet like below and use different property as per your requirement.

```<code>//DataSet
LineChartDataSet *set = [[LineChartDataSet alloc] initWithValues:values label:@"closed"];
set.lineWidth = 2;
</code>```

Set ChartFill property with your fill color :

```<code> set.fill = [ChartFill fillWithColor:<Your Legend Color>];
 [set setColor:<Your Legend Color>];
 [set setCircleColor:<Your Legend Color>];
 [set setCircleHoleColor:<Your Legend Color>];
</code>```

You need to enable drawfill :

```<code>set.drawFilledEnabled = YES;
</code>```

You can Enable circle with this property :

```<code>[set setDrawCirclesEnabled:YES];
</code>```

You can enable highlight Indicator which dat point is selected will highlight with Vertical Line :

```<code>[set setDrawHighlightIndicators:YES];
</code>```

You can set Circle radius as per your requirement :

```<code>[set setCircleRadius:5.0f];
[set setCircleHoleRadius:4.0f];
</code>```

You can specify line with of highlighted data point also :

```<code>[set setHighlightLineWidth:1.0];
[set setHighlightColor:kAppLegend3GraphColorForCAP];
</code>```

Edit:

for changing font color & type you need to change xAxis color and font as mention below

```<code>lineChartView.xAxis.labelFont = UIFont.systemFont(ofSize: 20.0, weight: UIFontWeightRegular)
lineChartView.xAxis.labelTextColor = .orange
</code>```

For Line limit to data point value I think we can not limit this in current version.

Hope this will help you to achieve your requirement.

Body:
How can I customize the highlighter in Line Charts? I want to cut the highlight to be drawn only up to the data point. I also want to customize the label on the x-axis where it's highlighted. Below is a reference picture on what I'm trying to achieve.

This is what I've done so far. What I've achieved so far

Below is the code for my Line Chart View Setup

let lineChartView: LineChartView = {
    let chart = LineChartView(frame: .zero)
    chart.chartDescription = nil
    chart.dragEnabled = true
    chart.scaleYEnabled = false
    chart.scaleXEnabled = true
    chart.pinchZoomEnabled = false
    chart.drawGridBackgroundEnabled = true
    chart.gridBackgroundColor = .clear
    chart.legend.enabled = false
    chart.zoom(scaleX: 2, scaleY: 1, x: 0, y: 0)
    chart.setViewPortOffsets(left: 30, top: 30, right: 30, bottom: 30)

    chart.rightAxis.enabled = false

    let yAxis = chart.leftAxis
    yAxis.enabled = true
    yAxis.drawAxisLineEnabled = false
    yAxis.drawLabelsEnabled = false
    yAxis.gridColor = UIColor(rgba: "#414042")
    yAxis.gridLineWidth = 1
    yAxis.axisMaximum = 6000

    chart.xAxis.enabled = true
    chart.xAxis.drawGridLinesEnabled = false
    chart.xAxis.drawLabelsEnabled = true
    chart.xAxis.drawAxisLineEnabled = true
    chart.xAxis.axisLineColor = .darkGray
    chart.xAxis.axisLineWidth = 1
    chart.xAxis.valueFormatter = IndexAxisValueFormatter(values: ["Jan", "Feb", "Mar", "April", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
    chart.xAxis.labelPosition = .bottom
    chart.xAxis.labelTextColor = .darkGray
    chart.xAxis.labelFont = UIFont.sourceSansProLight(withSize: 15.5)
    chart.xAxis.granularityEnabled = true
    chart.xAxis.granularity = 1

    chart.highlightPerTapEnabled = false

    chart.backgroundColor = .clear

    return chart
}()

And this is the code for adding random data points in the chart and the highlight.

var values: [ChartDataEntry] = []
var highlight: Highlight? = nil

for index in 0..<12 {
    let randomValue = Double(arc4random_uniform(5000))
    values.append(ChartDataEntry(x: Double(index), y: randomValue))

    if index == 4 {
        highlight = Highlight(x: Double(index), y: randomValue, dataSetIndex: 0)
    }
}

let dataSet = LineChartDataSet(values: values, label: "")
dataSet.highlightEnabled = true
dataSet.drawHorizontalHighlightIndicatorEnabled = false
dataSet.highlightColor = UIColor(rgba: "#1899FF")
dataSet.highlightLineWidth = 1
dataSet.mode = .horizontalBezier
dataSet.circleColors = Array(repeating: UIColor(rgba: "#1899FF"), count: 12)
dataSet.fillColor = UIColor(rgba: "#1899FF")
dataSet.drawCircleHoleEnabled = false
dataSet.drawFilledEnabled = true
dataSet.lineWidth = 0.0
dataSet.drawValuesEnabled = true
dataSet.axisDependency = .left
dataSet.valueFormatter = self

let data = LineChartData(dataSet: dataSet)
data.setDrawValues(true)
data.setValueFont(UIFont.sourceSansProLight(withSize: 15.5))
data.setValueTextColor(UIColor(rgba: "#1899FF"))

lineChartView.data = data
lineChartView.highlightValue(highlight)

Body:
For Highlight Area of data point you can use below property and achieve this

All property can use through dataSet so for that you can create LineChartDataSet like below and use different property as per your requirement.

//DataSet
LineChartDataSet *set = [[LineChartDataSet alloc] initWithValues:values label:@"closed"];
set.lineWidth = 2;

Set ChartFill property with your fill color :

 set.fill = [ChartFill fillWithColor:<Your Legend Color>];
 [set setColor:<Your Legend Color>];
 [set setCircleColor:<Your Legend Color>];
 [set setCircleHoleColor:<Your Legend Color>];

You need to enable drawfill :

set.drawFilledEnabled = YES;

You can Enable circle with this property :

[set setDrawCirclesEnabled:YES];

You can enable highlight Indicator which dat point is selected will highlight with Vertical Line :

[set setDrawHighlightIndicators:YES];

You can set Circle radius as per your requirement :

[set setCircleRadius:5.0f];
[set setCircleHoleRadius:4.0f];

You can specify line with of highlighted data point also :

[set setHighlightLineWidth:1.0];
[set setHighlightColor:kAppLegend3GraphColorForCAP];

Edit:

for changing font color & type you need to change xAxis color and font as mention below

lineChartView.xAxis.labelFont = UIFont.systemFont(ofSize: 20.0, weight: UIFontWeightRegular)
lineChartView.xAxis.labelTextColor = .orange

For Line limit to data point value I think we can not limit this in current version.

Hope this will help you to achieve your requirement.


问:
Java String quote delimiter
Is there any way in Java to use a special delimiter at the start and the end of a String to avoid having to backslash all of the quotes within that String?

i.e. not have to do this:

```<code>String s = "Quote marks like this \" are just the best, here are a few more \" \" \""
</code>```

答: The only way to achive this is to put your strings in some other file and read it from Java. For instance a resource bundle.</p>

Title: Java String quote delimiter

Body:
Is there any way in Java to use a special delimiter at the start and the end of a String to avoid having to backslash all of the quotes within that String?

i.e. not have to do this:

String s = "Quote marks like this \" are just the best, here are a few more \" \" \""


问:
create csv and write to it using Photoshop-script
I want to create an excel file with the contents using Photoshop script. Any hints on how to create a sheet and write to the cell?</p>

答:
Creating a CSV file which can be opened in any spreadsheet (including Excel) is fairly simple. While scripting in Photoshop (or any adobe software with scripting support) you can you Extended Script's File object.

CSV file

CSV (Comma-Separated Values) is a simple text file where each cell in a row is separated by comma (other separators also possible). Cell values might be also enclosed in quotation marks.

Before you start

So first and foremost you need to have your data ready. Since I don't know what you want to write I cannot help you with this. But let's assume you have your data in an array of arrays. Each array being a single row. In that case you could simply do the following.

Writing file

```<code>/**
    data is an array of arrays, example:
    data = [
            ['first layer', 400, 500],
            ['second layer', 300, 500],
            ['awesome layer', 500, 500],
           ]
**/

var file = new File('D:\path\to\file.csv');
file.open('w');
for (var i = 0; i < data.length; i++) {
    file.writeln('"' + data[i].join('","') + '"');
}
file.close();
</code>```

Simple as that.

File contents would be:

```<code>"first layer","400","500"
"second layer","300","500"
"awesome layer","500","500"
</code>```

I'm using comma separator and enclose data in quotations marks but quotation marks might not be needed if for example all data will be numbers. Also please remember that if float values are going to be written with comma as decimal separator (depending on local options) you can also use semicolon as separ

However depending on permissions and/or existence of files/folders on certain path - both open method and writeln method might return false. So you should update following code to detect those scenarios if necessary.

Body:
Creating a CSV file which can be opened in any spreadsheet (including Excel) is fairly simple. While scripting in Photoshop (or any adobe software with scripting support) you can you Extended Script's File object.

CSV file

CSV (Comma-Separated Values) is a simple text file where each cell in a row is separated by comma (other separators also possible). Cell values might be also enclosed in quotation marks.

Before you start

So first and foremost you need to have your data ready. Since I don't know what you want to write I cannot help you with this. But let's assume you have your data in an array of arrays. Each array being a single row. In that case you could simply do the following.

Writing file

/**
    data is an array of arrays, example:
    data = [
            ['first layer', 400, 500],
            ['second layer', 300, 500],
            ['awesome layer', 500, 500],
           ]
**/

var file = new File('D:\path\to\file.csv');
file.open('w');
for (var i = 0; i < data.length; i++) {
    file.writeln('"' + data[i].join('","') + '"');
}
file.close();

Simple as that.

File contents would be:

"first layer","400","500"
"second layer","300","500"
"awesome layer","500","500"

I'm using comma separator and enclose data in quotations marks but quotation marks might not be needed if for example all data will be numbers. Also please remember that if float values are going to be written with comma as decimal separator (depending on local options) you can also use semicolon as separ

However depending on permissions and/or existence of files/folders on certain path - both open method and writeln method might return false. So you should update following code to detect those scenarios if necessary.


问:
sudo: ./install.sh: command not found is not working on Lion
I've been following this tutorial in order to get SimpleOpenNI installed on my mac but I keep getting stuck at installing the OpenNI and NITE components because it requires me to navigate to the folders in Terminal and then run "sudo ./install.sh". I do this and I get this error:

sudo: ./install.sh: command not found

I've installed Command Line Tools in Xcode and everything.

Thanks

答:
You need to run VBoxLinuxAdditions.run as root, not autorun.sh

Once you've inserted the Guest Additions ISO, open Files and open the disc from the sidebar. Then, right-click in the background of the window where autorun.sh is and select

Open in > Terminal

Now you can run the following command to install the Guest Additions:

sudo ./VboxLinuxAdditions.run


问:
PHP database not able to log in
I need some assistance with my database, I am not able to log in to it even though it's making a connection to the db.

This is my Connection.php

```<code>$servername = "localhost";
$username = "root";
$password = "";
$database = "tools4ever"";
$conn = new PDO("mysql:host=$servername;dbname=". $database, $username,
$password);
</code>```

And this is in my login script:

require "connection.php";
    $rol = $_GET["k"];

```<code>if (isset($_POST["terug"])) {
    header("Location:index.php");
}

if (isset($_POST["registreren"])) {
    if ($rol == "klant") {
        header("Location:registreren.php");
    } else {
        header("Location:medewerkertoevoegen.php");

    }
 }
$persoon = "";
$rol = -1;
$error = 0;
$rol = $_GET["k"];
    if($rol == "medewerker") {
        $gebruikersnaam= $_POST["gebruikersnaam"];
        $wachtwoord = sha1($_POST["wachtwoord"]);
        $stmt = $conn->prepare("select * from medewerker where gebruikersnaam=? and wachtwoord=?");
        $stmt->execute(array($gebruikersnaam, $wachtwoord));
        $aantalRijen = $stmt->rowCount();
        if ($aantalRijen==1) {
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $result = $stmt->fetch();
            $_SESSION["medewerkercode"] = $result["medewerkercode"];
            $tvs = ($result["voorletters"] =="") ? "" : $result["voorletters"]." ";
            $_SESSION["naam"] = $result["voorletters"] ." ". $tvs. " " .$result["achternaam"];
            $_SESSION["medewerkercode"] = $result["medewerkercode"];
             header("Location:overzichtArtikelen.php?k=medewerker");
            $_SESSION["rol"]= "medewerker";
            }
        else {
            $error =-1;
        }

    }
</code>```

And this is how my database currently looks. http://i.imgur.com/qU3JUme.png

Does anyone here know the answer? Much appreciated!

Tom

答:
$conn = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);

try this you are concating the String that PDO doesn't accept.

EDIT

For index fix you have to set the name attribute to your form input for both username and password

somthing like this

<input type="text" name="username"/>
<input type="password" name="password"/>

then you can access them in your login script as

$username = $_POST['username'];
$password = $_POST['password'];

that's it!!!

Title: PHP database not able to log in

Body:
I need some assistance with my database, I am not able to log in to it even though it's making a connection to the db.

This is my Connection.php

$servername = "localhost";
$username = "root";
$password = "";
$database = "tools4ever"";
$conn = new PDO("mysql:host=$servername;dbname=". $database, $username,
$password);

And this is in my login script:

require "connection.php";
    $rol = $_GET["k"];

if (isset($_POST["terug"])) {
    header("Location:index.php");
}

if (isset($_POST["registreren"])) {
    if ($rol == "klant") {
        header("Location:registreren.php");
    } else {
        header("Location:medewerkertoevoegen.php");

    }
 }
$persoon = "";
$rol = -1;
$error = 0;
$rol = $_GET["k"];
    if($rol == "medewerker") {
        $gebruikersnaam= $_POST["gebruikersnaam"];
        $wachtwoord = sha1($_POST["wachtwoord"]);
        $stmt = $conn->prepare("select * from medewerker where gebruikersnaam=? and wachtwoord=?");
        $stmt->execute(array($gebruikersnaam, $wachtwoord));
        $aantalRijen = $stmt->rowCount();
        if ($aantalRijen==1) {
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $result = $stmt->fetch();
            $_SESSION["medewerkercode"] = $result["medewerkercode"];
            $tvs = ($result["voorletters"] =="") ? "" : $result["voorletters"]." ";
            $_SESSION["naam"] = $result["voorletters"] ." ". $tvs. " " .$result["achternaam"];
            $_SESSION["medewerkercode"] = $result["medewerkercode"];
             header("Location:overzichtArtikelen.php?k=medewerker");
            $_SESSION["rol"]= "medewerker";
            }
        else {
            $error =-1;
        }

    }

And this is how my database currently looks. http://i.imgur.com/qU3JUme.png

Does anyone here know the answer? Much appreciated!

Tom


问:
How to update a global variable inside RDD map operation
I have RDD[(Int, Array[Double])] and after that, I called a classFunction

```<code>val rdd = spark.sparkContext.parallelize(Seq(
        (1, Array(2.0,5.0,6.3)),
        (5, Array(1.0,3.3,9.5)),
        (1, Array(5.0,4.2,3.1)),
        (2, Array(9.6,6.3,2.3)),
        (1, Array(8.5,2.5,1.2)),
        (5, Array(6.0,2.4,7.8)),
        (2, Array(7.8,9.1,4.2))
      )
    )
 val new_class = new ABC
 new_class.demo(data)
</code>```

Inside class, declared a global variable value =0. Inside the demo() the new variable  new_value = 0 is declared. After the map operation, the new_value get updated and it prints the updated value inside the map.

```<code>class ABC extends Serializable {
        var value  = 0
        def demo(data_new : RDD[(Int ,Array[Double])]): Unit ={
            var new_value = 0
            data_new.coalesce(1).map(x => {
                if(x._1 == 1)
                    new_value = new_value + 1
                println(new_value)
                value = new_value
            }).count()
            println("Outside-->" +value)
        }
    }
</code>```

OUTPUT:-

```<code>1
1
2
2
3
3
3
Outside-->0
</code>```

How can I update the global variable value after the map operation?.

答:
No you can't change the global variables from inside the map.

If you are trying to count the number of one in the function than you can use filter

```<code>val value = data_new.filter(x => (x._1 == 1)).count
println("Outside-->" +value)
</code>```

Output:

```<code>Outside-->3
</code>```

Also it is not recommended to use mutable variables var. You should always try to use immutable as val

I hope this helps!

Body:
I have RDD[(Int, Array[Double])] and after that, I called a classFunction

val rdd = spark.sparkContext.parallelize(Seq(
        (1, Array(2.0,5.0,6.3)),
        (5, Array(1.0,3.3,9.5)),
        (1, Array(5.0,4.2,3.1)),
        (2, Array(9.6,6.3,2.3)),
        (1, Array(8.5,2.5,1.2)),
        (5, Array(6.0,2.4,7.8)),
        (2, Array(7.8,9.1,4.2))
      )
    )
 val new_class = new ABC
 new_class.demo(data)

Inside class, declared a global variable value =0. Inside the demo() the new variable  new_value = 0 is declared. After the map operation, the new_value get updated and it prints the updated value inside the map.

class ABC extends Serializable {
        var value  = 0
        def demo(data_new : RDD[(Int ,Array[Double])]): Unit ={
            var new_value = 0
            data_new.coalesce(1).map(x => {
                if(x._1 == 1)
                    new_value = new_value + 1
                println(new_value)
                value = new_value
            }).count()
            println("Outside-->" +value)
        }
    }

OUTPUT:-

1
1
2
2
3
3
3
Outside-->0

How can I update the global variable value after the map operation?.

Body:
No you can't change the global variables from inside the map.

If you are trying to count the number of one in the function than you can use filter

val value = data_new.filter(x => (x._1 == 1)).count
println("Outside-->" +value)

Output:

Outside-->3

Also it is not recommended to use mutable variables var. You should always try to use immutable as val

I hope this helps!