答:
section {
  display: flex;
  flex-flow: column;
  height: 100vh;          /* the container always has full height of the viewport */
}
header {
  background: tomato;
}
div {
  flex: 1;                /* the content div always consumes all free space */
  background: gold;
  overflow: auto;
}
footer {
  margin-top: auto;       /* the footer is always pinned to the bottom */
  background: lightgreen;
  min-height: 60px;
}

body { margin: 0; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <header>
    header: sized to content
      <br/>(but is it really?)
  </header>
  <div>
    main content: fills remaining space<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
  </div>
  <footer>
    footer: fixed height in px
  </footer>
</section></code>```

Title: Fill available space without overflowing

Body:
I am trying to create a desktop application user interface with html and what i want to achieve is having a fixed header and footer with content filling the remaining (whatever) space the window is. Been trying to use flex but not quite understand how it works with almost all of my trials ending up with an overflow.

Fiddle
http://jsfiddle.net/4dxperkp/

section {
  display: flex;
  flex-flow: column;
}

header {
  background: tomato;
}

div {
  background: gold;

  height: 100vh;
}

footer {
  background: tomato;
}

I also came accross -webkit-fill-available but it end up causing an overflow as well.

Body:
section {
  display: flex;
  flex-flow: column;
  height: 100vh;          /* the container always has full height of the viewport */
}
header {
  background: tomato;
}
div {
  flex: 1;                /* the content div always consumes all free space */
  background: gold;
  overflow: auto;
}
footer {
  margin-top: auto;       /* the footer is always pinned to the bottom */
  background: lightgreen;
  min-height: 60px;
}

body { margin: 0; }

<section>
  <header>
    header: sized to content
      <br/>(but is it really?)
  </header>
  <div>
    main content: fills remaining space<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
  </div>
  <footer>
    footer: fixed height in px
  </footer>
</section>


来源: stackexchange

问:
JQuery Tools tabs conflicts with JQuery UI
I'm using JQuery tools' tabs feature and at the same time I use JQuery UI.

If I include both JS libraries, Jquery tools with tabs does not work.

How to fix this conflict? Any help is appreciated.

Thanks in advance.

答:
There is an easier method. Whenever you use jquery with other libraries (Tools | Prototype | MooTools | etc.) you can use a special noConflict function to re-assign the $ to another variable. For example:

```<code>var $j = jQuery.noConflict();    // assign the main jQuery object to $j
$j("#tabs-container").tabs();    // use $j as you would normally use $
</code>```

Or you can be more explicit and use jQuery.someFunction() instead of $.someFunction.

ContentLicense: CC BY-SA 2.5

Body:
There is an easier method. Whenever you use jquery with other libraries (Tools | Prototype | MooTools | etc.) you can use a special noConflict function to re-assign the $ to another variable. For example:

var $j = jQuery.noConflict();    // assign the main jQuery object to $j
$j("#tabs-container").tabs();    // use $j as you would normally use $

Or you can be more explicit and use jQuery.someFunction() instead of $.someFunction.


问:
soundcloud API - JSON track count does not match profile track count
I'm building a web app using the soundcloud JavaScript SDK that should only return profiles that contain one or more tracks.

My GET request returns an array of user profiles, each including the track_count property and associated value, as expected.

However, when I follow the link to each profile, the number of tracks is often different from the value listed in the JSON (see example in images below). Crucially, in relation to my purpose, this means that it sometimes returns profiles with 0 tracks.

From my tests so far, I've found that if the values are different then the profile track count is always less than in the JSON. Could this mean that's it's including tracks that have been deleted or removed (e.g. because of copyright infringement)?

I would really appreciate if someone could shed some light on this.

Thanks!

$(document).ready(function() {
          SC.initialize({
            client_id: 'xxxx',
            redirect_uri: 'http://localhost/callback.html'
          });

          SC.get('/users/12490371/followers', {

            limit: page_size,
            linked_partitioning: 1

          }).then(function(followers) {

            $(followers.collection).each(function(i) {
              //console.log(followers.collection[i].track_count)

              if (followers.collection[i].track_count > 10 && followers.collection[i].followers_count < 500) {
                $("#list").append(
                  "
" +
                  "
" + this.username + "
" +
                  "
" + this.followers_count + "
" +
                  "
" + this.track_count + "
" +
                  "
GO" + "
" +
                  "
"
                );
              }

            });
          });
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="list">
  <ul>
    <li class='username'>Username</li>
    <li>Followers</li>
    <li>Track count</li>
    <li>Profile</li>
  </ul>
</div></code>```

profile view
JSON view

答:
To answer your question, it definitely seems that the SoundCloud API returns all tracks from the artist, no matter what state those tracks are in (public, private, etc.).

As far as the rest goes, Sound Cloud is notorious for being strict with how artists' content is handled in terms of embedding or having it used on other sites. It is usually up to the artist from my understanding, but in general, they want artists' content to be protected, especially if they are under a contract with a record company or something.

As for your web app, you'll either have to work around it or just ditch it completely, unless you can create some sort of scraper that can get more relevant info. If your site wants to play music directly from the site, however, you may be at a loss.

ContentLicense: CC BY-SA 3.0

Body:
I'm building a web app using the soundcloud JavaScript SDK that should only return profiles that contain one or more tracks.

My GET request returns an array of user profiles, each including the track_count property and associated value, as expected.

However, when I follow the link to each profile, the number of tracks is often different from the value listed in the JSON (see example in images below). Crucially, in relation to my purpose, this means that it sometimes returns profiles with 0 tracks.

From my tests so far, I've found that if the values are different then the profile track count is always less than in the JSON. Could this mean that's it's including tracks that have been deleted or removed (e.g. because of copyright infringement)?

I would really appreciate if someone could shed some light on this.

Thanks!

$(document).ready(function() {
          SC.initialize({
            client_id: 'xxxx',
            redirect_uri: 'http://localhost/callback.html'
          });

          SC.get('/users/12490371/followers', {

            limit: page_size,
            linked_partitioning: 1

          }).then(function(followers) {

            $(followers.collection).each(function(i) {
              //console.log(followers.collection[i].track_count)

              if (followers.collection[i].track_count > 10 && followers.collection[i].followers_count < 500) {
                $("#list").append(
                  "
" +
                  "
" + this.username + "
" +
                  "
" + this.followers_count + "
" +
                  "
" + this.track_count + "
" +
                  "
GO" + "
" +
                  "
"
                );
              }

            });
          });
        });

Username

Followers

Track count

Profile

profile view
JSON view


问:
Which takes precedence: Rails type casting or validation?
I am very curious about what this expected behavior is for Rails 4.2 and I have not been able to find an answer to my question.

I'm adding validation to a model on all the time attributes. I want them to ONLY accept integers, not numerical strings. The data type in my schema for this attribute is an integer. I have my validation like so:

```<code>RANGE = 0..59
validates :start_minute,   inclusion: { in: RANGE }, numericality: true
</code>```

I've tried these other validations as well. I get the same result.

```<code>validates_numericality_of :start_minute, inclusion: { 0..59, only_integer: true }

validates :start_minute, inclusion: { in: 0..59 }, numericality: { only_integer: true }
</code>```

When I pass my params to my controller from the request spec, start_minute is "12". BUT when I look at the created object, the start_minute  is 12.

According to this article by ThoughtBot:

"This is because Active Record automatically type casts all input so that it matches the database schema. Depending on the type, this may be incredibly simple, or extremely complex."

Shouldn't the object not be able to be created? Is the typecasting taking precedence of my validation? Or is there something wrong with my validation? I appreciate any insight to this as I haven't been able to determine what is happening here. I've also created a model spec for this and I'm still able to create a new object with numerical strings.

Thank you for any insight you can give on this. I am still learning the magic of Rails under the hood.

答:
From the rails docs it says,

If you set :only_integer to true, then it will use the

/\A[+-]?\d+\z/

What it(only_integer validator) does is that it validates that the format of value matches the regex above and a string value that contains only numbers like '12' is a match(returns a truthy value which is 0 and passes the validation).

```<code>2.3.1 :001 > '12' =~ /\A[+-]?\d+\z/
 => 0
</code>```

Body:
I am very curious about what this expected behavior is for Rails 4.2 and I have not been able to find an answer to my question.

I'm adding validation to a model on all the time attributes. I want them to ONLY accept integers, not numerical strings. The data type in my schema for this attribute is an integer. I have my validation like so:

RANGE = 0..59
validates :start_minute,   inclusion: { in: RANGE }, numericality: true

I've tried these other validations as well. I get the same result.

validates_numericality_of :start_minute, inclusion: { 0..59, only_integer: true }

validates :start_minute, inclusion: { in: 0..59 }, numericality: { only_integer: true }

When I pass my params to my controller from the request spec, start_minute is "12". BUT when I look at the created object, the start_minute  is 12.

According to this article by ThoughtBot:

"This is because Active Record automatically type casts all input so that it matches the database schema. Depending on the type, this may be incredibly simple, or extremely complex."

Shouldn't the object not be able to be created? Is the typecasting taking precedence of my validation? Or is there something wrong with my validation? I appreciate any insight to this as I haven't been able to determine what is happening here. I've also created a model spec for this and I'm still able to create a new object with numerical strings.

Thank you for any insight you can give on this. I am still learning the magic of Rails under the hood.

Body:
From the rails docs it says,

If you set :only_integer to true, then it will use the

/\A[+-]?\d+\z/

What it(only_integer validator) does is that it validates that the format of value matches the regex above and a string value that contains only numbers like '12' is a match(returns a truthy value which is 0 and passes the validation).

2.3.1 :001 > '12' =~ /\A[+-]?\d+\z/
 => 0


问:
Unable to fetch links from website
Getting results like "https://bmovies.to/"a class="

but I want https://bmovies.to/movie_title?

Here is my code

```<code>   foreach($html->find('a[class=name]') as $head)

  {

    $head->href;

    $pre = 'https://bmovies.to/';
    $movie=$pre.$head;

    echo '<a href="'.$pre.$head.'</a>';

    $count++;

}
</code>```

答:
Like what @Bytewave said you're missing a character on your anchor from this line

echo '';

Make a correction for your link and put some text inside of your anchor tag as below.

echo 'href="'.$pre.$head.'">some-text-here';

Title: Unable to fetch links from website

Body:
Getting results like "https://bmovies.to/"a class="

but I want https://bmovies.to/movie_title?

Here is my code

   foreach($html->find('a[class=name]') as $head)

  {

    $head->href;

    $pre = 'https://bmovies.to/';
    $movie=$pre.$head;

    echo '<a href="'.$pre.$head.'';

    $count++;

}

Body:
Like what @Bytewave said you're missing a character on your anchor from this line

echo '<a href="'.$pre.$head.'</a>';

Make a correction for your link and put some text inside of your anchor tag as below.

echo '<a href="'.$pre.$head.'">some-text-here</a>';


问:
Team City Build and Octopus deploy
Team city is often used for building and then use Octopus for deploy. I wonder if I can use a successful octopus deploy to trigger a team city build? If it is possible, how to do this? Thanks. </p>

答:
You could use an integration between Octopus Subscriptions (basically webhooks) to call off to TeamCity's API, but you'd have to create that manually, there's no built-in "connectors".

I'd question why you want to do this though?

Title: Team City Build and Octopus deploy


问:
Behavior of array as index in JS
Index of array may be array by itself (tested in Chrome):

```<code>a = [1, 2, 3]
index = [1]
a[index] // returns 2
</code>```

Is there any official documentation of this behavior?

答:
Is there any official documentation of this behavior?

12.3.2.1Runtime Semantics: Evaluation

defines the following 3 steps

3 Let propertyNameReference be the result of evaluating Expression.

4 Let propertyNameValue be ? GetValue(propertyNameReference).

6 Let propertyKey be ? ToPropertyKey(propertyNameValue).

Then 7.1.14ToPropertyKey ( argument ) is defined as

Let key be ? ToPrimitive(argument, hint String).

If Type(key) is Symbol, then

a. Return key.

Return ! ToString(key).

Which effectively means, that unless the expression returns a Symbol - it (the key) would be converted to a string.

Title: Behavior of array as index in JS

Body:
Index of array may be array by itself (tested in Chrome):

a = [1, 2, 3]
index = [1]
a[index] // returns 2

Is there any official documentation of this behavior?


问:
How to use RecyclerView inside NestedScrollView
I have this layout:

```<code> <android.support.v4.widget.NestedScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

            <--There is some layouts here-->
            <RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
    </LinearLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

It works well. I can scroll RecyclerView smoothly without scrolling parent view.

Now I have to put the RecyclerView inside a FrameLayout like this:

```<code> <android.support.v4.widget.NestedScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
 <--There is some layouts here-->
        <FrameLayout
            android:id="@+id/review_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <include
                android:id="@+id/empty_view"
                layout="@layout/review_empty_view"
                android:visibility="gone" />
        </FrameLayout>
    </LinearLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

Now I cannot scroll the RecyclerView smoothly.
All I want is: scroll RecyclerView smoothly without scrolling parent view. What should I do?

EDIT: Here is my review_empty layout:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal"
    android:padding="16dp">

    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/shopping_review_empty" />

    <android.support.v4.widget.Space
        android:layout_width="32dp"
        android:layout_height="0dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/shopping_no_review_message" />
</LinearLayout>
</code>```

答:
All you have to do is use below line in your activity class:

```<code>ViewCompat.setNestedScrollingEnabled(recycler_view, false);
</code>```

its compatible for lower versions also. and if you want to give compatible to API >21 only then use;

```<code>  recycler_view.setNestedScrollingEnabled(false);
</code>```

Body:
I have this layout:

 <android.support.v4.widget.NestedScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

            <--There is some layouts here-->
            <RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

It works well. I can scroll RecyclerView smoothly without scrolling parent view.

Now I have to put the RecyclerView inside a FrameLayout like this:

 <android.support.v4.widget.NestedScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
 <--There is some layouts here-->
        <FrameLayout
            android:id="@+id/review_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <include
                android:id="@+id/empty_view"
                layout="@layout/review_empty_view"
                android:visibility="gone" />
        </FrameLayout>
    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

Now I cannot scroll the RecyclerView smoothly.
All I want is: scroll RecyclerView smoothly without scrolling parent view. What should I do?

EDIT: Here is my review_empty layout:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal"
    android:padding="16dp">

    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/shopping_review_empty" />

    <android.support.v4.widget.Space
        android:layout_width="32dp"
        android:layout_height="0dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/shopping_no_review_message" />
</LinearLayout>

Body:
All you have to do is use below line in your activity class:

ViewCompat.setNestedScrollingEnabled(recycler_view, false);

its compatible for lower versions also. and if you want to give compatible to API >21 only then use;

  recycler_view.setNestedScrollingEnabled(false);


问:
Select onchange, trying run script to load separate text into 2 textareas
I have a table and within it is a set of select values which auto populate a textarea based on which of the options is selected. What I am trying to do is make it populate two pieces of information into separate text areas when an option is chosen, The first being text into Bar_green and the second being a URL into Top_green2. Is this possible?  I just can't wrap my brain around this. Here is the code I am using:</p>

```<code><html>
<head>
<title></title>
<HTA:APPLICATION id="" applicationname="" border="thick" caption="yes" icon="c:\windows\system32\write.exe" showintaskbar="yes" singleinstance="no" sysmenu="yes" windowstate="normal" contextmenu="yes">
<style>

</style>
</head>
<body>

<table border=0 cellpadding=0 cellspacing=0 height="100%" width="100%">
<tr>

<td class="top_area" id="top_green">

<script type="text/javascript">
        function showText_green(){
           var value = document.getElementById('options_green').value;
           if(value != ""){
             document.getElementById('bar_green').innerHTML = value;
             document.getElementById('bar_green').style.display = "block";
           }
        }
    </script>

<!--<script type="text/javascript">
        function showLink_green(){
           var value = document.getElementById('options_green').value;
           if(value != ""){
             document.getElementById('top_green2').innerHTML = value;
             document.getElementById('top_green2').style.display = "block";
           }
        }-->
    </script>
        <select id="options_green" onchange="showText_green(); showLink_green()">
            <option value="">Select an option</option>
            <option value="text 1">Option 1</option>
            <option value="text 2">Option 2</option>
            <option value="text 3">Option 3</option>
            <option value="text 4">Option 4</option>
            <option value="text 5">Option 5</option>
            <option value="text 6">Option 6</option>
            <option value="text 7">Option 7</option>
       </select>

</td>

    <tr>
        <td class="top_area2"><textarea id="top_green2"></textarea></td>
    </tr>
        <td class="bar_area"><textarea id="bar_green"></textarea></td>
    </tr>
</table>

</body>
</html>
</code>```

答:
You can populate the url with whatever logic you want</p>

```<code>var urls = {
    'text 1': 'url 1',
    'text 2': 'url 2'
};

var select = $("#options_green");

select.off("change");
select.on("change", function() {
    $("#bar_green").text($(this).val());
    $("#top_green2").text(urls[$(this).val()]);
});
</code>```

Body:
I have a table and within it is a set of select values which auto populate a textarea based on which of the options is selected. What I am trying to do is make it populate two pieces of information into separate text areas when an option is chosen, The first being text into Bar_green and the second being a URL into Top_green2. Is this possible?  I just can't wrap my brain around this. Here is the code I am using:

<title></title>
<HTA:APPLICATION id="" applicationname="" border="thick" caption="yes" icon="c:\windows\system32\write.exe" showintaskbar="yes" singleinstance="no" sysmenu="yes" windowstate="normal" contextmenu="yes">

Body:
You can populate the url with whatever logic you want

var urls = {
    'text 1': 'url 1',
    'text 2': 'url 2'
};

var select = $("#options_green");

select.off("change");
select.on("change", function() {
    $("#bar_green").text($(this).val());
    $("#top_green2").text(urls[$(this).val()]);
});


问:
Passing values to MySQL IN operation in PDO prepared statement?
I have a form field that is returning a comma-delimited string that I want to pass in to a PHP PDO MySQL query IN operation, but the IN operation requires that the values be comma-delimited (as opposed to my string of delimited values).

How do I do this?

```<code>$values = $_POST['values']; # '10,5,4,3' (string)
$query = "SELECT * FROM table WHERE id IN (:values)";
$data = array( ':values' => $values );
</code>```

答:
You can't pass in multiple values in a single placeholder. You will have to enter a different placeholder for each value to be passed into IN (). Since you don't know how many there will be, use ? instead of named parameters.

```<code>$values = explode(',', $values) ;

$placeholders = rtrim(str_repeat('?, ', count($values)), ', ') ;
$query = "SELECT * FROM table WHERE id IN ($placeholders)";

$stm = $db->prepare($query) ;
$stm->execute($values) ;
</code>```

Body:
I have a form field that is returning a comma-delimited string that I want to pass in to a PHP PDO MySQL query IN operation, but the IN operation requires that the values be comma-delimited (as opposed to my string of delimited values).

How do I do this?

$values = $_POST['values']; # '10,5,4,3' (string)
$query = "SELECT * FROM table WHERE id IN (:values)";
$data = array( ':values' => $values );

Body:
You can't pass in multiple values in a single placeholder. You will have to enter a different placeholder for each value to be passed into IN (). Since you don't know how many there will be, use ? instead of named parameters.

$values = explode(',', $values) ;

$placeholders = rtrim(str_repeat('?, ', count($values)), ', ') ;
$query = "SELECT * FROM table WHERE id IN ($placeholders)";

$stm = $db->prepare($query) ;
$stm->execute($values) ;


问:
CodeIgniter Form Validation matches got too many error messages
I have an error message problem about form validation matches.
Here is what I set:

```<code>$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');
</code>```

and of course, I have a form with two password input field.

```<code>form_password('password');
form_password('cpassword');
</code>```

I am dealing with error messages using validation_errors() function.

if I let two password fields blank, i got:

```<code>The Password field is required.
The Confirm Password field is required.
</code>```

And if I type something in password and let the Confirm Password field blank, I got:

```<code>The Confirm Password field is required.
</code>```

so far so good until:

I type something in Confirm Password field and let the Password field blank, I got:

```<code>The Password field is required.
The Confirm Password field does not match the Password field.
</code>```

I got two messages instead of one.
I just need the "The Password field is required." only.

What can I do for this? Please help, thanks.

答:
As James Lalor said above. here is the working code.</p>

```<code>$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim');

if (!empty($this->input->post('password'))) {
    $this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');
}
</code>```

Body:
I have an error message problem about form validation matches.
Here is what I set:

$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');

and of course, I have a form with two password input field.

form_password('password');
form_password('cpassword');

I am dealing with error messages using validation_errors() function.

if I let two password fields blank, i got:

The Password field is required.
The Confirm Password field is required.

And if I type something in password and let the Confirm Password field blank, I got:

The Confirm Password field is required.

so far so good until:

I type something in Confirm Password field and let the Password field blank, I got:

The Password field is required.
The Confirm Password field does not match the Password field.

I got two messages instead of one.
I just need the "The Password field is required." only.

What can I do for this? Please help, thanks.

Body:
As James Lalor said above. here is the working code.

$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim');

if (!empty($this->input->post('password'))) {
    $this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');
}


问:
Big-Oh proof feedback
I'm currently reading about Big-Oh and the way to prove the statements.

However, I need a feedback or just direction for proving.

So, I want to prove that for all real numbers a and b,

if b > a and a > 1, then b^n not in O(a^n).

I want to prove by contradiction, since b>a. Let b^n be in O(a^n), then

by definition of Big-oh, there is a constant c and natural number n0, such

that b^n <= ca^n, for all n >= n0. Thus n > max(n0, c) which is

contradiction.

I'm little bit lost and my last sentence, and looking for some feedback if it's possible.

答:
The conclusion follows pretty closely from the definitions you've given, so the proof is not much more than you're already written.  You need to get:

b^n ∈ O(a^n) ⇒ ∃ c,n0 : (b/a)^n < c for all n > n0

and

b > a > 1 ⇒  (b/a) > 1, and (b/a)^n grows without bound.

If you actually want to construct a contradiction you can show that for any c > 0, you can choose n > log(c) / log(b/a)

Title: Big-Oh proof feedback


问:
How to use z-index in svg elements?
I'm using the svg circles in my project like this,

```<code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
    <g>
        <g id="one">
            <circle fill="green" cx="100" cy="105" r="20" />
        </g>
        <g id="two">
            <circle fill="orange" cx="100" cy="95" r="20" />
        </g>
    </g>
</svg>
</code>```

And I'm using the z-index in the g tag to show the elements the first. In my project I need to use only z-index value, but I can't use the z-index to my svg elements. I have googled a lot but I didn't find anything relatively.
So please help me to use z-index in my svg.

Here is the DEMO.

答:
As discussed, svgs render in order and don't take z-index into account (for now). Maybe just send the specific element to the bottom of its parent so that it'll render last.

```<code>function bringToTop(targetElement){
  // put the element at the bottom of its parent
  let parent = targetElement.parentNode;
  parent.appendChild(targetElement);
}

// then just pass through the element you wish to bring to the top
bringToTop(document.getElementById("one"));
</code>```

Worked for me.

Update

If you have a nested SVG, containing groups, you'll need to bring the item out of its parentNode.

```<code>function bringToTopofSVG(targetElement){
  let parent = targetElement.ownerSVGElement;
  parent.appendChild(targetElement);
}
</code>```

A nice feature of SVG's is that each element contains it's location regardless of what group it's nested in :+1:

Title: How to use z-index in svg elements?

Body:
I'm using the svg circles in my project like this,

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
    <g>
        <g id="one">
            <circle fill="green" cx="100" cy="105" r="20" />
        </g>
        <g id="two">
            <circle fill="orange" cx="100" cy="95" r="20" />
        </g>
    </g>
</svg>

And I'm using the z-index in the g tag to show the elements the first. In my project I need to use only z-index value, but I can't use the z-index to my svg elements. I have googled a lot but I didn't find anything relatively.
So please help me to use z-index in my svg.

Here is the DEMO.

Body:
As discussed, svgs render in order and don't take z-index into account (for now). Maybe just send the specific element to the bottom of its parent so that it'll render last.

function bringToTop(targetElement){
  // put the element at the bottom of its parent
  let parent = targetElement.parentNode;
  parent.appendChild(targetElement);
}

// then just pass through the element you wish to bring to the top
bringToTop(document.getElementById("one"));

Worked for me.

Update

If you have a nested SVG, containing groups, you'll need to bring the item out of its parentNode.

function bringToTopofSVG(targetElement){
  let parent = targetElement.ownerSVGElement;
  parent.appendChild(targetElement);
}

A nice feature of SVG's is that each element contains it's location regardless of what group it's nested in :+1:

ContentLicense: CC BY-SA 4.0


问:
Efficient Prime Number Computing Program Java
So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.

One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.

However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.

For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.

So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.

Here's my code, I can't figure out why it's not working

```<code>    Scanner sc = new Scanner (System.in);
    System.out.print ("Enter the upper limit: ");
    int high = sc.nextInt();

    boolean isPrime = true;
    int[] primearray = new int[0];

    for (int num = 1; num <= high; num++)
    {
        for (int x: primearray)
        {
            if (num%x==0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime == true) {
            int size = primearray.length;
            primearray = new int[size+1];
            primearray [size] = num;

            System.out.println (num);
        }
    }
</code>```

答:
You have wrong in logic

```<code>boolean isPrime = true;
</code>```

this variable should be declared in for loop, let 's imagine, if you find out 4 is not prime then isPrime = false, then you check 5 but there is not any code block that set isPrime = true.

And this block:

```<code>if (isPrime == true) {
    int size = primearray.length;
    primearray = new int[size+1];
    primearray [size] = num;

    System.out.println (num);
}
</code>```

You created new array of prime number, primearray with size increased by 1, so primearray does not contain any old prime number, that will make wrong while checking prime. So you need to copy old prime numbers to new array.

And because the prime numbers start by 2, so your code should be:

```<code>Scanner sc = new Scanner(System.in);
System.out.print("Enter the upper limit: ");
int high = sc.nextInt();

int[] primeArray = new int[0];
for (int num = 2; num <= high; num++)
{
    boolean isPrime = true;
    for (int x : primeArray)
    {
        if (num % x == 0)
        {
            isPrime = false;
            break;
        }
    }

    if (isPrime == true)
    {
        primeArray = Arrays.copyOf(primeArray, primeArray.length + 1);
        primeArray[primeArray.length - 1] = num;
        System.out.println(num);
    }
}
</code>```

Body:
So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.

One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.

However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.

For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.

So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.

Here's my code, I can't figure out why it's not working

    Scanner sc = new Scanner (System.in);
    System.out.print ("Enter the upper limit: ");
    int high = sc.nextInt();

    boolean isPrime = true;
    int[] primearray = new int[0];

    for (int num = 1; num <= high; num++)
    {
        for (int x: primearray)
        {
            if (num%x==0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime == true) {
            int size = primearray.length;
            primearray = new int[size+1];
            primearray [size] = num;

            System.out.println (num);
        }
    }

Body:
You have wrong in logic

boolean isPrime = true;

this variable should be declared in for loop, let 's imagine, if you find out 4 is not prime then isPrime = false, then you check 5 but there is not any code block that set isPrime = true.

And this block:

if (isPrime == true) {
    int size = primearray.length;
    primearray = new int[size+1];
    primearray [size] = num;

    System.out.println (num);
}

You created new array of prime number, primearray with size increased by 1, so primearray does not contain any old prime number, that will make wrong while checking prime. So you need to copy old prime numbers to new array.

And because the prime numbers start by 2, so your code should be:

Scanner sc = new Scanner(System.in);
System.out.print("Enter the upper limit: ");
int high = sc.nextInt();

int[] primeArray = new int[0];
for (int num = 2; num <= high; num++)
{
    boolean isPrime = true;
    for (int x : primeArray)
    {
        if (num % x == 0)
        {
            isPrime = false;
            break;
        }
    }

    if (isPrime == true)
    {
        primeArray = Arrays.copyOf(primeArray, primeArray.length + 1);
        primeArray[primeArray.length - 1] = num;
        System.out.println(num);
    }
}


问:
I'm trying getting an error when trying to integrate Google Sign In to my Android app: Cannot Resolve Symbol GoogleSignIn
I'm trying to integrate Google Sign In to my Android up but i'm getting an error that the symbol GoogleSignIn cannot be resolved: https://snag.gy/R2Mg3L.jpg

Here is the code and Gradle files for the project; I'm following the instructions provided by Google at: https://developers.google.com/identity/sign-in/android/

```<code>package com.example.GSTest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.auth.api.signin.GoogleSignIn;

import com.google.android.gms.auth.api.signin.GoogleSignInOptions;

public class loginActivity extends AppCompatActivity implements View.OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    Button gButton = findViewById(R.id.sign_in_button);
    gButton.setOnClickListener(this);
}

@Override
public void onClick(View v){

    switch (v.getId()) {
        case R.id.sign_in_button:
            signIn();
            break;
        // ...
    }

}

private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

//end of main class
}
</code>```

Gradle (Project):

```<code>// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath 'com.google.gms:google-services:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

Gradle (Module):

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.GSTest"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.gms:google-services:3.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
apply plugin: 'com.google.gms.google-services'
}
</code>```

答: You need to import the package that contains GoogleSignIn. I assume you're using this one.</p>

Body:
I'm trying to integrate Google Sign In to my Android up but i'm getting an error that the symbol GoogleSignIn cannot be resolved: https://snag.gy/R2Mg3L.jpg

Here is the code and Gradle files for the project; I'm following the instructions provided by Google at: https://developers.google.com/identity/sign-in/android/

package com.example.GSTest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.auth.api.signin.GoogleSignIn;

import com.google.android.gms.auth.api.signin.GoogleSignInOptions;

public class loginActivity extends AppCompatActivity implements View.OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    Button gButton = findViewById(R.id.sign_in_button);
    gButton.setOnClickListener(this);
}

@Override
public void onClick(View v){

    switch (v.getId()) {
        case R.id.sign_in_button:
            signIn();
            break;
        // ...
    }

}

private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

//end of main class
}

Gradle (Project):

// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath 'com.google.gms:google-services:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

Gradle (Module):

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.GSTest"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.gms:google-services:3.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
apply plugin: 'com.google.gms.google-services'
}


问:
How to use where condition multiple times within one single sql query
In my table1 there is date like:

```<code>id      value
1       500
2       400
3       300
4       200
5       100
</code>```

I want to set the data above within the show table:

```<code>d1      d2      d3      d4      d5
500     400     300     200     100
</code>```

I am using the following sql query.

```<code>"SELECT `value` as d1 from `table1` WHERE `id`=1"
"SELECT `value` as d2 from `table1` WHERE `id`=2"
"SELECT `value` as d3 from `table1` WHERE `id`=3"
"SELECT `value` as d4 from `table1` WHERE `id`=4"
"SELECT `value` as d5 from `table1` WHERE `id`=5"
</code>```

How will I make all the queries within single sql query?

答:
I would use aggregation:</p>

```<code>select max(case when id = 1 then value end) as d1,
       max(case when id = 2 then value end) as d2,
       max(case when id = 3 then value end) as d3,
       max(case when id = 4 then value end) as d4,
       max(case when id = 5 then value end) as d5
from t;
</code>```

Body:
In my table1 there is date like:

id      value
1       500
2       400
3       300
4       200
5       100

I want to set the data above within the show table:

d1      d2      d3      d4      d5
500     400     300     200     100

I am using the following sql query.

"SELECT `value` as d1 from `table1` WHERE `id`=1"
"SELECT `value` as d2 from `table1` WHERE `id`=2"
"SELECT `value` as d3 from `table1` WHERE `id`=3"
"SELECT `value` as d4 from `table1` WHERE `id`=4"
"SELECT `value` as d5 from `table1` WHERE `id`=5"

How will I make all the queries within single sql query?

Body:
I would use aggregation:

select max(case when id = 1 then value end) as d1,
       max(case when id = 2 then value end) as d2,
       max(case when id = 3 then value end) as d3,
       max(case when id = 4 then value end) as d4,
       max(case when id = 5 then value end) as d5
from t;


问:
Conditional formatting multiple rules to single cell
I have used one formula to change the font colour if a cell contains the text "complete" & another formula to add a light blue fill to the entire row if the word "odd" appears in a cell which is in a different column to the first formula.

The conditions seem to clash & although I have changed and played with the order of the conditions & checked there is no conflict in the fill/background or the font colour, even when changing the font colour manually again the fill from the second formula returns the font the cell to black although it is set to automatic in the conditional formatting rule with the fill ?

I wonder where i am going wrong as everything suggests the two conditions should work fine together though when the fill is applied the font goes back to black when it should be green ?

Have you any suggestions ?

答: From my experience with conditional formatting, I believe that it applies a format to the entire cell rather than individually modifying fill or font colour, so formats will not combine. I had a similar situation and solved it by creating an additional rule. In your case, one that applies your desired font colour and background fill to the 'complete' cell if the same row also contains 'odd' using the AND() function.</p>


问:
Minimum development environment for sharepoint 2007 webparts
I know there are already a couple of questions out there about sharepoint development environments, but I was wondering if there's a shortcut if all I want to do is develop a relatively simple webpart. Do I still have to create a virtual machine with windows server, install sharepoint, sql server, wss etc., etc. or is there some easy way to get up and running more quickly?

In short, what's the absolute minimum environment I need to develop a webpart for sharepoint 2007?

答:
The Environment you need to have for developing simple web part is:

Visual studio with WSP Builder add on.

Develop The webpart and build it. When you build the webpart you get the webpartname.wsp.

Take this file to the machine where you have the Sharepoint installed and you can Deploy it using sstadm.

If anyone wants detailed info, please let me know.
Hari Gillala


问:
powershell script works in run.exe but doesn't work as scheduled task
I scheduled this task below and when I click run in Task Scheduler it doesn't throw any errors but the script doesn't execute:
Program:

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "& S:\Scripts\Download-USPTO-Forms.ps1 -destinationFolder 'S:\Scripts\USPTO Forms'"
</code>```

When I open Run.exe and run this cmd then the Powershell window opens and the script executes:

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "& S:\Scripts\Download-USPTO-Forms.ps1 -destinationFolder 'S:\Scripts\USPTO Forms'"
</code>```

Why is that? Any ideas? The task seems to be scheduled correctly.

答:
Why are you using the call operator?

```<code>powershell -File "S:\Scripts\Download-USPTO-Forms.ps1" -destinationFolder "S:\Scripts\USPTO Forms"
</code>```

Furthermore, ensure the task has properly mapped drives and permissions.

Body:
I scheduled this task below and when I click run in Task Scheduler it doesn't throw any errors but the script doesn't execute:
Program:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "& S:\Scripts\Download-USPTO-Forms.ps1 -destinationFolder 'S:\Scripts\USPTO Forms'"

When I open Run.exe and run this cmd then the Powershell window opens and the script executes:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "& S:\Scripts\Download-USPTO-Forms.ps1 -destinationFolder 'S:\Scripts\USPTO Forms'"

Why is that? Any ideas? The task seems to be scheduled correctly.

Body:
Why are you using the call operator?

powershell -File "S:\Scripts\Download-USPTO-Forms.ps1" -destinationFolder "S:\Scripts\USPTO Forms"

Furthermore, ensure the task has properly mapped drives and permissions.


问:
New line button && submit button
In my TextInput I need to show a "New Line" key and also the "Done" key.

Currently I am only able to get one or the other. I can get the "New Line" key but setting <TextInput returnKeyType="none" multiline>, however I don't get the "Done" key anymore:

Is it posible to get both? I am testing on Android, I haven't tested on iOS yet.

答:
Unfortunately, the short answer is no.

For the returnKeyType the documentation states can only one of the enum values...

```<code>returnKeyType?: enum('done', 'go', 'next', 'search', 'send', 'none', 'previous', 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo')

Determines how the return key should look. On Android you can also use returnKeyLabel.
</code>```

Cross platform

```<code>The following values work across platforms:

done
go
next
search
send
</code>```

Android Only

```<code>The following values work on Android only:

none
previous
</code>```

iOS Only

```<code>The following values work on iOS only:

default
emergency-call
google
join
route
yahoo
</code>```

Title: New line button && submit button

Body:
Unfortunately, the short answer is no.

For the returnKeyType the documentation states can only one of the enum values...

returnKeyType?: enum('done', 'go', 'next', 'search', 'send', 'none', 'previous', 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo')

Determines how the return key should look. On Android you can also use returnKeyLabel.

Cross platform

The following values work across platforms:

done
go
next
search
send

Android Only

The following values work on Android only:

none
previous

iOS Only

The following values work on iOS only:

default
emergency-call
google
join
route
yahoo


答:
As @Ryan and @4castle mentioned, javascript convert key(inside []) to string using [].join(',').
You can test it in this snippet.

var abc = {
  "1,2": "ddd"
  };
 console.log(abc[[1,2]]);```

Title: Behavior of array as index in JS

Body:
Index of array may be array by itself (tested in Chrome):

a = [1, 2, 3]
index = [1]
a[index] // returns 2

Is there any official documentation of this behavior?


问:
Invalid columns names Insert statement
I am trying to create add button in the gridview. I have 3 joining tables and 3 drop-down lists.

That is the error that I get:

Additional information: Invalid column name 'Quotation_Number'. Invalid column name 'Customer_Name'. Invalid column name 'Machine_Model'.

Can you help me? I think the problem is in the insert statement

Thanks

```<code>public void userSales()
{
    con.Open();

    SqlCommand cmd = new SqlCommand("SELECT SalesActivity.Activity_ID, SalesActivity.Date, SalesActivity.Quatation_Number, CUSTOMER.Customer_Name, PRODUCTS.Machine_Model, SalesActivity.Quantity, SalesActivity.valueGBR, SalesActivity.valueEUR, SalesActivity.Rate, SalesActivity.weightedValue, STATUS.Status, SalesActivity.estDecisionDate, SalesActivity.PromisedDeliveryDate FROM SalesActivity INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID ", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();

    if (ds.Tables[0].Rows.Count > 0)
    {
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    else
    {
        ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());  // if record not found then returning a blank table structure
        GridView1.DataSource = ds;
        GridView1.DataBind();

        int columncount = GridView1.Rows[0].Cells.Count;

        GridView1.Rows[0].Cells.Clear();
        GridView1.Rows[0].Cells.Add(new TableCell());
        GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
        GridView1.Rows[0].Cells[0].Text = "No Records Found";
    }
}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex; //this open new index that is edit mode
    userSales();
}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;   //after cancel button want go to one index back that's y -1
    userSales();
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("AddNew"))
    {
        TextBox txtActivity = (TextBox)GridView1.FooterRow.FindControl("ftxtActivity");
        TextBox ftxtDate = (TextBox)GridView1.FooterRow.FindControl("ftxtDate");
        TextBox ftxtQno = (TextBox)GridView1.FooterRow.FindControl("ftxtQno");
        DropDownList fddlCName = GridView1.FooterRow.FindControl("fddlCName") as DropDownList;
        DropDownList fddlMmodel = GridView1.FooterRow.FindControl("fddlMmodel") as DropDownList;
        TextBox ftxtQuantity = (TextBox)GridView1.FooterRow.FindControl("ftxtQuantity");
        TextBox ftxtvalueGBR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueGBR");
        TextBox ftxtvalueEUR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueEUR");
        TextBox ftxtRate = (TextBox)GridView1.FooterRow.FindControl("ftxtRate");
        TextBox ftxtweightedValue = (TextBox)GridView1.FooterRow.FindControl("ftxtweightedValue");
        DropDownList fddlStatus = GridView1.FooterRow.FindControl("fddlStatus") as DropDownList;
        TextBox ftxtestDecisionDate = (TextBox)GridView1.FooterRow.FindControl("ftxtestDecisionDate");
        TextBox ftxtPromisedDeliveryDate = (TextBox)GridView1.FooterRow.FindControl("ftxtPromisedDeliveryDate");

        con.Open();

        SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(@Activity_ID, @Date, @Quotation_Number, @Customer_Name, @Machine_Model, @Quantity, @valueGBR, @valueEUR, @Rate, @weightedValue, @Status, @estDecisionDate, @PromisedDeliveryDate)", con);
        cmd.Parameters.AddWithValue("@Activity_ID", txtActivity.Text.Trim());
        cmd.Parameters.AddWithValue("@Date", ftxtDate.Text.Trim());
        cmd.Parameters.AddWithValue("@Quotation_Number", ftxtQno.Text.Trim());
        cmd.Parameters.AddWithValue("@Customer_Name", fddlCName.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@Machine_Model", fddlMmodel.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@Quantity",  ftxtQuantity.Text.Trim());
        cmd.Parameters.AddWithValue("@valueGBR", ftxtvalueGBR.Text.Trim());
        cmd.Parameters.AddWithValue("@valueEUR",  ftxtvalueEUR.Text.Trim());
        cmd.Parameters.AddWithValue("@weightedValue",ftxtweightedValue.Text.Trim());
        cmd.Parameters.AddWithValue("@Rate",  ftxtRate.Text.Trim());
        cmd.Parameters.AddWithValue("@Status",  fddlStatus.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@estDecisionDate", ftxtestDecisionDate.Text.Trim());
        cmd.Parameters.AddWithValue("@PromisedDeliveryDate", ftxtPromisedDeliveryDate.Text.Trim());

        int result = cmd.ExecuteNonQuery();

        con.Close();

        if (result == 1)
        {
            userSales();
            Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+'Sale Details inserted successfully');</script>");
        }
        else
        {
            Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+' Sale Details not inserted');</script>");
        }
    }
}
</code>```

答:
Your Select Statement is executing this...

```<code>SELECT SalesActivity.Activity_ID
    ,SalesActivity.DATE
    ,SalesActivity.Quatation_Number
    ,CUSTOMER.Customer_Name
    ,PRODUCTS.Machine_Model
    ,SalesActivity.Quantity
    ,SalesActivity.valueGBR
    ,SalesActivity.valueEUR
    ,SalesActivity.Rate
    ,SalesActivity.weightedValue
    ,STATUS.STATUS
    ,SalesActivity.estDecisionDate
    ,SalesActivity.PromisedDeliveryDate
FROM SalesActivity
INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID
INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID
INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID
</code>```

Machine_Model and Customer_Name do not belong to SalesActivity Table, they belong to Products and Customer respectively. And your issue with Quotation_Number is Quatation_Number in the select.

change this...

```<code>SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(@Activity_ID, @Date, @Quotation_Number, @Customer_Name, @Machine_Model, @Quantity, @valueGBR, @valueEUR, @Rate, @weightedValue, @Status, @estDecisionDate, @PromisedDeliveryDate)", con);
</code>```

to this...

```<code>SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quatation_Number,Quantity, valueGBR, valueEUR, Rate, weightedValue, estDecisionDate, PromisedDeliveryDate) VALUES(@Activity_ID, @Date, @Quotation_Number, @Quantity, @valueGBR, @valueEUR, @Rate, @weightedValue, @estDecisionDate, @PromisedDeliveryDate)", con);
</code>```

and remove the following lines...

```<code>cmd.Parameters.AddWithValue("@Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Status",  fddlStatus.SelectedItem.Text);
</code>```

The insert should now work.

Title: Invalid columns names Insert statement

Body:
I am trying to create add button in the gridview. I have 3 joining tables and 3 drop-down lists.

That is the error that I get:

Additional information: Invalid column name 'Quotation_Number'. Invalid column name 'Customer_Name'. Invalid column name 'Machine_Model'.

Can you help me? I think the problem is in the insert statement

Thanks

public void userSales()
{
    con.Open();

    SqlCommand cmd = new SqlCommand("SELECT SalesActivity.Activity_ID, SalesActivity.Date, SalesActivity.Quatation_Number, CUSTOMER.Customer_Name, PRODUCTS.Machine_Model, SalesActivity.Quantity, SalesActivity.valueGBR, SalesActivity.valueEUR, SalesActivity.Rate, SalesActivity.weightedValue, STATUS.Status, SalesActivity.estDecisionDate, SalesActivity.PromisedDeliveryDate FROM SalesActivity INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID ", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();

    if (ds.Tables[0].Rows.Count > 0)
    {
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    else
    {
        ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());  // if record not found then returning a blank table structure
        GridView1.DataSource = ds;
        GridView1.DataBind();

        int columncount = GridView1.Rows[0].Cells.Count;

        GridView1.Rows[0].Cells.Clear();
        GridView1.Rows[0].Cells.Add(new TableCell());
        GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
        GridView1.Rows[0].Cells[0].Text = "No Records Found";
    }
}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex; //this open new index that is edit mode
    userSales();
}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;   //after cancel button want go to one index back that's y -1
    userSales();
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("AddNew"))
    {
        TextBox txtActivity = (TextBox)GridView1.FooterRow.FindControl("ftxtActivity");
        TextBox ftxtDate = (TextBox)GridView1.FooterRow.FindControl("ftxtDate");
        TextBox ftxtQno = (TextBox)GridView1.FooterRow.FindControl("ftxtQno");
        DropDownList fddlCName = GridView1.FooterRow.FindControl("fddlCName") as DropDownList;
        DropDownList fddlMmodel = GridView1.FooterRow.FindControl("fddlMmodel") as DropDownList;
        TextBox ftxtQuantity = (TextBox)GridView1.FooterRow.FindControl("ftxtQuantity");
        TextBox ftxtvalueGBR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueGBR");
        TextBox ftxtvalueEUR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueEUR");
        TextBox ftxtRate = (TextBox)GridView1.FooterRow.FindControl("ftxtRate");
        TextBox ftxtweightedValue = (TextBox)GridView1.FooterRow.FindControl("ftxtweightedValue");
        DropDownList fddlStatus = GridView1.FooterRow.FindControl("fddlStatus") as DropDownList;
        TextBox ftxtestDecisionDate = (TextBox)GridView1.FooterRow.FindControl("ftxtestDecisionDate");
        TextBox ftxtPromisedDeliveryDate = (TextBox)GridView1.FooterRow.FindControl("ftxtPromisedDeliveryDate");

        con.Open();

        SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(@Activity_ID, @Date, @Quotation_Number, @Customer_Name, @Machine_Model, @Quantity, @valueGBR, @valueEUR, @Rate, @weightedValue, @Status, @estDecisionDate, @PromisedDeliveryDate)", con);
        cmd.Parameters.AddWithValue("@Activity_ID", txtActivity.Text.Trim());
        cmd.Parameters.AddWithValue("@Date", ftxtDate.Text.Trim());
        cmd.Parameters.AddWithValue("@Quotation_Number", ftxtQno.Text.Trim());
        cmd.Parameters.AddWithValue("@Customer_Name", fddlCName.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@Machine_Model", fddlMmodel.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@Quantity",  ftxtQuantity.Text.Trim());
        cmd.Parameters.AddWithValue("@valueGBR", ftxtvalueGBR.Text.Trim());
        cmd.Parameters.AddWithValue("@valueEUR",  ftxtvalueEUR.Text.Trim());
        cmd.Parameters.AddWithValue("@weightedValue",ftxtweightedValue.Text.Trim());
        cmd.Parameters.AddWithValue("@Rate",  ftxtRate.Text.Trim());
        cmd.Parameters.AddWithValue("@Status",  fddlStatus.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@estDecisionDate", ftxtestDecisionDate.Text.Trim());
        cmd.Parameters.AddWithValue("@PromisedDeliveryDate", ftxtPromisedDeliveryDate.Text.Trim());

        int result = cmd.ExecuteNonQuery();

        con.Close();

        if (result == 1)
        {
            userSales();
            Response.Write("");
        }
        else
        {
            Response.Write("");
        }
    }
}

Body:
Your Select Statement is executing this...

SELECT SalesActivity.Activity_ID
    ,SalesActivity.DATE
    ,SalesActivity.Quatation_Number
    ,CUSTOMER.Customer_Name
    ,PRODUCTS.Machine_Model
    ,SalesActivity.Quantity
    ,SalesActivity.valueGBR
    ,SalesActivity.valueEUR
    ,SalesActivity.Rate
    ,SalesActivity.weightedValue
    ,STATUS.STATUS
    ,SalesActivity.estDecisionDate
    ,SalesActivity.PromisedDeliveryDate
FROM SalesActivity
INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID
INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID
INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID

Machine_Model and Customer_Name do not belong to SalesActivity Table, they belong to Products and Customer respectively. And your issue with Quotation_Number is Quatation_Number in the select.

change this...

SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(@Activity_ID, @Date, @Quotation_Number, @Customer_Name, @Machine_Model, @Quantity, @valueGBR, @valueEUR, @Rate, @weightedValue, @Status, @estDecisionDate, @PromisedDeliveryDate)", con);

to this...

SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quatation_Number,Quantity, valueGBR, valueEUR, Rate, weightedValue, estDecisionDate, PromisedDeliveryDate) VALUES(@Activity_ID, @Date, @Quotation_Number, @Quantity, @valueGBR, @valueEUR, @Rate, @weightedValue, @estDecisionDate, @PromisedDeliveryDate)", con);

and remove the following lines...

cmd.Parameters.AddWithValue("@Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Status",  fddlStatus.SelectedItem.Text);

The insert should now work.


答:
a[index] will do a toString on the index, and since index is an array, its to string is index.join() making the output a['1']

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Title: Behavior of array as index in JS


问:
ruby/bundler seeming to fail to derive dependencies
I am getting this error when I run "bundle install"

```<code>Could not find gem 'febeling-rubyzip (>= 0, runtime)' in any of the gem sources listed in your Gemfile.
</code>```

My Gemfile looks like this

```<code>source 'http://rubygems.org'

gem 'rails'

gem "authlogic", :git => "git://github.com/binarylogic/authlogic.git"
gem "mechanize"
gem "hpricot"
gem "sqlite3-ruby"
gem "daemons"

gem 'sqlite3-ruby', :require => 'sqlite3'

gem "nokogiri"
gem "roo"
gem "zip"
gem "spreadsheet"
gem "builder"
gem "gimite-google-spreadsheet-ruby"
gem "febeling-rubyzip"

#gem "savon", "=0.7.9"
gem "savon"

#devise is required for rails_admin, but not used
gem 'devise'
gem 'rails_admin', :git => 'git://github.com/sferik/rails_admin.git'

gem 'febeling-rubyzip'

group :development, :test do
  gem "rcov"
  gem "capistrano"
end

group :development do
  gem "ruby-debug"
  gem "httpclient"
end
</code>```

Any thoughts/tips would be greatly appreciarted.

Thanks, Chris

PS I am using rvm with per project gemsets.  Whats probably quite pertinent is that I just did a "rvm gemset empty" and remove Gemfile.lock to do a clean install of the project's gems - things seemed ok prior to that :(

答: Does gem query -r -n febeling-rubyzip find anything in your version of ruby/gems?

Body:
I am getting this error when I run "bundle install"

Could not find gem 'febeling-rubyzip (>= 0, runtime)' in any of the gem sources listed in your Gemfile.

My Gemfile looks like this

source 'http://rubygems.org'

gem 'rails'

gem "authlogic", :git => "git://github.com/binarylogic/authlogic.git"
gem "mechanize"
gem "hpricot"
gem "sqlite3-ruby"
gem "daemons"

gem 'sqlite3-ruby', :require => 'sqlite3'

gem "nokogiri"
gem "roo"
gem "zip"
gem "spreadsheet"
gem "builder"
gem "gimite-google-spreadsheet-ruby"
gem "febeling-rubyzip"

#gem "savon", "=0.7.9"
gem "savon"

#devise is required for rails_admin, but not used
gem 'devise'
gem 'rails_admin', :git => 'git://github.com/sferik/rails_admin.git'

gem 'febeling-rubyzip'

group :development, :test do
  gem "rcov"
  gem "capistrano"
end

group :development do
  gem "ruby-debug"
  gem "httpclient"
end

Any thoughts/tips would be greatly appreciarted.

Thanks, Chris

PS I am using rvm with per project gemsets.  Whats probably quite pertinent is that I just did a "rvm gemset empty" and remove Gemfile.lock to do a clean install of the project's gems - things seemed ok prior to that :(


问:
Passing parameter form jsp to servlet to jsp and then to another servlet
Is there a way to pass a parameter to a servlet going through another jsp and then to another servlet
like
jsp---parameter--->servlet(using getParameter())---parameter--->jsp---parameter--->servlet(is there a way to get the parameter here)

The program that am working on is to pass the username.

答:
Looks like you want to use HTTPsession.

Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
  The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.

Setting

```<code>Session session = request.getSession();
session.setAttribute("username", username);
</code>```

getting it back

```<code>String username = (String)session.getAttribute("username");
</code>```

Body:
Looks like you want to use HTTPsession.

Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
  The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.

Setting

Session session = request.getSession();
session.setAttribute("username", username);

getting it back

String username = (String)session.getAttribute("username");


问:
iOS 11 Navigation bar large title have black color when push on pop view controller
I have a problem with the new navigation bar for iOS 11.

In root view set new navigation by code:

```<code>if (@available(iOS 11.0, *)) {
    self.navigationController.navigationBar.prefersLargeTitles = YES;
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
}
</code>```

Then from root view, I pushed to another view and set code navigation bar by

```<code>if (@available(iOS 11.0, *)) {
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeNever;
}
</code>```

It works well. However, when push and pop view a black color appeared like the image below:

I don't know why the black color appeared on this view although I did not set back ground for navigation bar is a black color for the whole screen in my app.

Someone have any idea for the problem. Please drop me some suggestion to solve that bug. Thanks.

答:
I solved this issue by setting navigation controller background colour in the UIViewController class where I am getting black colour.

Here is the code I used :

```<code>navigationController?.view.backgroundColor = UIColor.white
</code>```

I have tried changing background colours and shadows in story board but it doesn't seem to fix this issue. Hopefully this answer is still relevant here.

Body:
I have a problem with the new navigation bar for iOS 11.

In root view set new navigation by code:

if (@available(iOS 11.0, *)) {
    self.navigationController.navigationBar.prefersLargeTitles = YES;
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
}

Then from root view, I pushed to another view and set code navigation bar by

if (@available(iOS 11.0, *)) {
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeNever;
}

It works well. However, when push and pop view a black color appeared like the image below:

I don't know why the black color appeared on this view although I did not set back ground for navigation bar is a black color for the whole screen in my app.

Someone have any idea for the problem. Please drop me some suggestion to solve that bug. Thanks.

Body:
I solved this issue by setting navigation controller background colour in the UIViewController class where I am getting black colour.

Here is the code I used :

navigationController?.view.backgroundColor = UIColor.white

I have tried changing background colours and shadows in story board but it doesn't seem to fix this issue. Hopefully this answer is still relevant here.


答:
Previous answers already explains what is wrong with your code.

I just want to share another approach which is more efficient. The sample implementation is as per below. Basically, once we know x is prime number, we also know i*x is NOT a prime number. Further reading and visualization is available here

```<code>public int countPrimes(int n) {
            if (n == 0 || n == 1) return 0;

    int count = 0;
    boolean[] check = new boolean[n+1];

    for (int i = 2; i < n; i++) {
        if (check[i]) continue;

        for (int j = 1; j <= n / i; j++) {
            check[j * i] = true;
        }

        count++;
    }

    return count;
}
</code>```

Title: Efficient Prime Number Computing Program Java

Body:
Previous answers already explains what is wrong with your code.

I just want to share another approach which is more efficient. The sample implementation is as per below. Basically, once we know x is prime number, we also know i*x is NOT a prime number. Further reading and visualization is available here

public int countPrimes(int n) {
            if (n == 0 || n == 1) return 0;

    int count = 0;
    boolean[] check = new boolean[n+1];

    for (int i = 2; i < n; i++) {
        if (check[i]) continue;

        for (int j = 1; j <= n / i; j++) {
            check[j * i] = true;
        }

        count++;
    }

    return count;
}