问:
How Do I Update Nested Mongo Document Attributes in Rails with Mongoid?
(Apologies in advance if this question is short on details, I'll watch the comments and add what I can)

I have a Model with the following:

```<code>class Product
  include Mongoid::Document
  include Mongoid::Timestamps
#...
  field :document_template, :type => Document
  accepts_nested_attributes_for :document_template
</code>```

Inside the Document document_template, is the following references_many, which I want to modify. Specifically, I want to change which fonts are referenced:

```<code>class Document
  include Mongoid::Document
  include Mongoid::Timestamps
#...
  references_many :fonts, :stored_as => :array, :inverse_of => :documents
</code>```

What sort of logic and details should I have in my controller and form to get this done? Please comment if you would like me to add some of the zany things I've tried; however, I haven't had any luck with any of them.

Here is a quick showing of the issue using rails console:

```<code># Grab a Product and check how many fonts are in it's document_template
ruby-1.8.7-p302 > prod = Product.find(:first)
 => ...
ruby-1.8.7-p302 > prod._id
 => BSON::ObjectId('4d06af15afb3182bf5000111')
ruby-1.8.7-p302 > prod.document_template.font_ids.count
 => 9

# Remove a font from the font_ids array
ruby-1.8.7-p302 > prod.document_template.font_ids.pop
 => BSON::ObjectId('...')    # This font id was removed from font_ids
ruby-1.8.7-p302 > prod.document_template.font_ids.count
 => 8

# Save the changes
ruby-1.8.7-p302 > prod.document_template.save!
 => true
ruby-1.8.7-p302 > prod.save!
 => true

# Instantiate a new product object of that same product
ruby-1.8.7-p302 > prod_new = Product.find(:first)
 => ...

# Confirm the _ids are the same
ruby-1.8.7-p302 > prod._id == prod_new._id
 => true

# Check to see if the changes were persisted
ruby-1.8.7-p302 > prod_new.document_template.font_ids.count
 => 9  # If the changes persisted, this should be 8.

# Grrrrr... doesn't look like it. Will the change disappear after a reload too?

ruby-1.8.7-p302 > prod.reload
 => ...
ruby-1.8.7-p302 > prod.document_template.font_ids.count
 => 9

# ಠ_ಠ ... no dice.
</code>```

Updating objects using mongo (and not mongoid in rails) works as expected.

Kyle Banker has asked for some logging info, so here it is. Unfortunatly, I couldn't find a better source of logging than the output from rails server, which seems to suggest the update call is never being made. For some context here is some info from the controller:

```<code>def update_resource(object, attributes)
  update_pricing_scheme(object, attributes)
  update_document_template_fonts(object, attributes)
end

def update_document_template_fonts(object, attributes)
  document_template = object.document_template
  document_template_attributes = attributes[:document_template_attributes]

  font_ids = document_template_attributes[:font_ids]
  font_ids.delete("") # Removing an empty string that tags along with the font_ids.
  font_ids.collect! { |f| BSON::ObjectId(f) } # Mongo want BSON::ObjectId

  object.document_template.font_ids.replace font_ids
  object.document_template.save!(:validate => false)
  object.save!(:validate => false)
end
</code>```

Here is the output from rails server when the POST is processed:

```<code>Started GET "/admin/products/4d091b18afb3180f3d000111" for 127.0.0.1 at Wed Dec 15 13:57:28 -0600 2010

Started POST "/admin/products/4d091b18afb3180f3d000111" for 127.0.0.1 at Wed Dec 15 13:57:49 -0600 2010
  Processing by Admin::ProductsController#update as HTML
  Parameters: {"commit"=>"Update Product", "authenticity_token"=>"QUW0GZw7nz83joj8ncPTtcuqHpHRtp1liq8fB7/rB5s=", "utf8"=>"✓", "id"=>"4d091b18afb3180f3d000111", "product"=>{"name"=>"Ho Ho Ho Flat Multiple Photo Modern Holiday Card", "document_template_attributes"=>{"id"=>"4d091b18afb3180f3d000112", "font_ids"=>["", "4d091b17afb3180f3d000023"]}, "description"=>"", "pricing_scheme_id"=>"4d091b17afb3180f3d00003b"}}

development['users'].find({:_id=>BSON::ObjectId('4d091b17afb3180f3d00009b')}, {}).limit(-1)
development['products'].find({:_id=>BSON::ObjectId('4d091b18afb3180f3d000111')}, {}).limit(-1)
development['pricing_schemes'].find({:_id=>BSON::ObjectId('4d091b17afb3180f3d00003b')}, {}).limit(-1)

MONGODB development['products'].update({"_id"=>BSON::ObjectId('4d091b18afb3180f3d000111')}, {"$set"=>{"updated_at"=>Wed Dec 15 19:57:50 UTC 2010}})

in Document#set_default_color_scheme: self.color_scheme = #<ColorScheme:0xb52f6f38>

MONGODB development['documents'].update({"_id"=>BSON::ObjectId('4d091b18afb3180f3d000112')}, {"$set"=>{"color_scheme_name"=>"green_charcoal_black", "updated_at"=>Wed Dec 15 19:57:50 UTC 2010}})

Redirected to http://localhost:3000/admin/products/4d091b18afb3180f3d000111
Completed 302 Found in 49ms
</code>```

It looks like the MONGODB command to update the font_ids is completely absent...

答:
I'm partial to believing Mongoid Issue #357 is causing the problem. The logging above suggests that an update for the product's document_template.fonts (or font_ids) which seems to match the bug description.

(sidenote: I'm a bit confused where exactly the font_ids array comes from if not the :stored_as => :array. I'm not 100% certain which I should be modifying either but since font_ids is an Array and fonts is a Mongoid::Criteria, the path of least resistance is font_ids.)

From a data standpoint, :field and :embeds_* seem to be similar in that the information is embedded in the parent document.

Body:
(Apologies in advance if this question is short on details, I'll watch the comments and add what I can)

I have a Model with the following:

class Product
  include Mongoid::Document
  include Mongoid::Timestamps
#...
  field :document_template, :type => Document
  accepts_nested_attributes_for :document_template

Inside the Document document_template, is the following references_many, which I want to modify. Specifically, I want to change which fonts are referenced:

class Document
  include Mongoid::Document
  include Mongoid::Timestamps
#...
  references_many :fonts, :stored_as => :array, :inverse_of => :documents

What sort of logic and details should I have in my controller and form to get this done? Please comment if you would like me to add some of the zany things I've tried; however, I haven't had any luck with any of them.

Here is a quick showing of the issue using rails console:

# Grab a Product and check how many fonts are in it's document_template
ruby-1.8.7-p302 > prod = Product.find(:first)
 => ...
ruby-1.8.7-p302 > prod._id
 => BSON::ObjectId('4d06af15afb3182bf5000111')
ruby-1.8.7-p302 > prod.document_template.font_ids.count
 => 9

# Remove a font from the font_ids array
ruby-1.8.7-p302 > prod.document_template.font_ids.pop
 => BSON::ObjectId('...')    # This font id was removed from font_ids
ruby-1.8.7-p302 > prod.document_template.font_ids.count
 => 8

# Save the changes
ruby-1.8.7-p302 > prod.document_template.save!
 => true
ruby-1.8.7-p302 > prod.save!
 => true

# Instantiate a new product object of that same product
ruby-1.8.7-p302 > prod_new = Product.find(:first)
 => ...

# Confirm the _ids are the same
ruby-1.8.7-p302 > prod._id == prod_new._id
 => true

# Check to see if the changes were persisted
ruby-1.8.7-p302 > prod_new.document_template.font_ids.count
 => 9  # If the changes persisted, this should be 8.

# Grrrrr... doesn't look like it. Will the change disappear after a reload too?

ruby-1.8.7-p302 > prod.reload
 => ...
ruby-1.8.7-p302 > prod.document_template.font_ids.count
 => 9

# ಠ_ಠ ... no dice.

Updating objects using mongo (and not mongoid in rails) works as expected.

Kyle Banker has asked for some logging info, so here it is. Unfortunatly, I couldn't find a better source of logging than the output from rails server, which seems to suggest the update call is never being made. For some context here is some info from the controller:

def update_resource(object, attributes)
  update_pricing_scheme(object, attributes)
  update_document_template_fonts(object, attributes)
end

def update_document_template_fonts(object, attributes)
  document_template = object.document_template
  document_template_attributes = attributes[:document_template_attributes]

  font_ids = document_template_attributes[:font_ids]
  font_ids.delete("") # Removing an empty string that tags along with the font_ids.
  font_ids.collect! { |f| BSON::ObjectId(f) } # Mongo want BSON::ObjectId

  object.document_template.font_ids.replace font_ids
  object.document_template.save!(:validate => false)
  object.save!(:validate => false)
end

Here is the output from rails server when the POST is processed:

Started GET "/admin/products/4d091b18afb3180f3d000111" for 127.0.0.1 at Wed Dec 15 13:57:28 -0600 2010

Started POST "/admin/products/4d091b18afb3180f3d000111" for 127.0.0.1 at Wed Dec 15 13:57:49 -0600 2010
  Processing by Admin::ProductsController#update as HTML
  Parameters: {"commit"=>"Update Product", "authenticity_token"=>"QUW0GZw7nz83joj8ncPTtcuqHpHRtp1liq8fB7/rB5s=", "utf8"=>"✓", "id"=>"4d091b18afb3180f3d000111", "product"=>{"name"=>"Ho Ho Ho Flat Multiple Photo Modern Holiday Card", "document_template_attributes"=>{"id"=>"4d091b18afb3180f3d000112", "font_ids"=>["", "4d091b17afb3180f3d000023"]}, "description"=>"", "pricing_scheme_id"=>"4d091b17afb3180f3d00003b"}}

development['users'].find({:_id=>BSON::ObjectId('4d091b17afb3180f3d00009b')}, {}).limit(-1)
development['products'].find({:_id=>BSON::ObjectId('4d091b18afb3180f3d000111')}, {}).limit(-1)
development['pricing_schemes'].find({:_id=>BSON::ObjectId('4d091b17afb3180f3d00003b')}, {}).limit(-1)

MONGODB development['products'].update({"_id"=>BSON::ObjectId('4d091b18afb3180f3d000111')}, {"$set"=>{"updated_at"=>Wed Dec 15 19:57:50 UTC 2010}})

in Document#set_default_color_scheme: self.color_scheme = #<ColorScheme:0xb52f6f38>

MONGODB development['documents'].update({"_id"=>BSON::ObjectId('4d091b18afb3180f3d000112')}, {"$set"=>{"color_scheme_name"=>"green_charcoal_black", "updated_at"=>Wed Dec 15 19:57:50 UTC 2010}})

Redirected to http://localhost:3000/admin/products/4d091b18afb3180f3d000111
Completed 302 Found in 49ms

It looks like the MONGODB command to update the font_ids is completely absent...


来源: stackexchange

问:
JavaScript and AJAX not working as expected
I'm using the JavaScript and AJAX for signup form.

I want to post all textboxes in signup form through AJAX but am failing to do so.

signup.php

$(document).ready(function() {
  $('submit').click(function() {
    var first = $('#firstname').val();
    var last = $('#lastname').val();
    var Email = $('#email').val();
    var pass = $('#password').val();
    var confirm = $('#confirmpassword').val();
    var phone = $('#phoneno').val();

    $.ajax({
      type: "POST",
      url: "register.php",
      data: {
        (

          firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,

        )
      },
      success: function(data) {
        alert('passed');
      },
      error: function() {
        alert("error");
      }

    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery-3.2.0.min.js"></script>
<title>
</title>

<div align="right">
</div>
<div id="div">
  <center>
    <h3>REGISTER</h3>
  </center>
  <table>
    <thead>
    </thead>
    <tbody>
      <tr>
        <td>
          <label>Firstname</label>
          <td>
            <input type="text" name="firstname" id="firstname" required="">
          </td>
      </tr>
      <tr>
        <td>
          <label>Lastname</label>
        </td>
        <td>
          <input type="text" name="lastname" id="lastname" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Email</label>
        </td>
        <td>
          <input type="text" name="email" id="email" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Password</label>
        </td>
        <td>
          <input type="password" name="password" id="password" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Confirm password</label>
        </td>
        <td>
          <input type="password" name="confirmpassword" id="confirmpassword" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Phone no</label>
        </td>
        <td>
          <input type="text" name="phoneno" id="phoneno" required="">
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
          <input type="button" name="submit" value="submit" id="submit" />
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
        </td>
        <td>
          Login?
        </td>
      </tr>
    </tbody>
  </table>
</div></code>```

register.php

```<code><?php
include 'config.php';
 $firstname=$_POST['firstname'];
 $lastname= $_POST['lastname'];
 $email=$_POST['email'];
 $password=$_POST['password'];
 $confirmpassword=$_POST['confirmpassword'];
 $phoneno=$_POST['phoneno'];
if($password==$confirmpassword)
{
$insertuser=mysql_query("insert into register(firstname,lastname,email,password,confirmpassword,phoneno) values('$firstname','$lastname','$email','$password','$confirmpassword','$phoneno')",$conn)or die(mysql_error());
echo "success";

}
else
{
  echo "failure";

 }
?>
</code>```

答:
You are using wrong jQuery selector use

```<code>$('#submit')
</code>```

To bind the button event

Also change the data passed in ajax - there should not be a () around it.

The code will be

```<code>$(document).ready(function() {
    $('#submit').click(function() {
        var first = $('#firstname').val();
        var last = $('#lastname').val();
        var Email = $('#email').val();
        var pass = $('#password').val();
        var confirm = $('#confirmpassword').val();
        var phone = $('#phoneno').val();

        $.ajax({
            type: "POST",
            url: "register.php",
            data: {
                firstname: first,
                lastname: last,
                email: Email,
                password: pass,
                confirmpassword: confirm,
                phoneno: phone // no comma on the last item

            },
            success: function(data) {
                alert('passed');
            },
            error: function() {
                alert("error");
            }

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

ContentLicense: CC BY-SA 3.0

Body:
I'm using the JavaScript and AJAX for signup form.

I want to post all textboxes in signup form through AJAX but am failing to do so.

signup.php

$(document).ready(function() {
  $('submit').click(function() {
    var first = $('#firstname').val();
    var last = $('#lastname').val();
    var Email = $('#email').val();
    var pass = $('#password').val();
    var confirm = $('#confirmpassword').val();
    var phone = $('#phoneno').val();

    $.ajax({
      type: "POST",
      url: "register.php",
      data: {
        (

          firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,

        )
      },
      success: function(data) {
        alert('passed');
      },
      error: function() {
        alert("error");
      }

    });
  });
});

<title>
</title>

REGISTER

          Firstname

            <input type="text" name="firstname" id="firstname" required="">

          Lastname

          <input type="text" name="lastname" id="lastname" required="">

          Email

          <input type="text" name="email" id="email" required="">

          Password

          <input type="password" name="password" id="password" required="">

          Confirm password

          <input type="password" name="confirmpassword" id="confirmpassword" required="">

          Phone no

          <input type="text" name="phoneno" id="phoneno" required="">

          <input type="button" name="submit" value="submit" id="submit" />

          Login?

register.php

<?php
include 'config.php';
 $firstname=$_POST['firstname'];
 $lastname= $_POST['lastname'];
 $email=$_POST['email'];
 $password=$_POST['password'];
 $confirmpassword=$_POST['confirmpassword'];
 $phoneno=$_POST['phoneno'];
if($password==$confirmpassword)
{
$insertuser=mysql_query("insert into register(firstname,lastname,email,password,confirmpassword,phoneno) values('$firstname','$lastname','$email','$password','$confirmpassword','$phoneno')",$conn)or die(mysql_error());
echo "success";

}
else
{
  echo "failure";

 }
?>

Body:
You are using wrong jQuery selector use

$('#submit')

To bind the button event

Also change the data passed in ajax - there should not be a () around it.

The code will be

$(document).ready(function() {
    $('#submit').click(function() {
        var first = $('#firstname').val();
        var last = $('#lastname').val();
        var Email = $('#email').val();
        var pass = $('#password').val();
        var confirm = $('#confirmpassword').val();
        var phone = $('#phoneno').val();

        $.ajax({
            type: "POST",
            url: "register.php",
            data: {
                firstname: first,
                lastname: last,
                email: Email,
                password: pass,
                confirmpassword: confirm,
                phoneno: phone // no comma on the last item

            },
            success: function(data) {
                alert('passed');
            },
            error: function() {
                alert("error");
            }

        });
    });
});


问:
Swift: Expandable Static TableView
Before I post this, I have read some article like this or this , but all of that example always using dynamic data. I want to know how implement expandable tableview in static data. I think this is more simple but I don't have any idea. My snippet code : </p>

```<code>override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if (indexPath.section == 1) {
        if indexPath.row == self.department {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }
    }

    if indexPath.section == 0 {
        if indexPath.row == 2 {
            datePickerFrom.isHidden = true
        }
        else if indexPath.row == 4 {
            datePickerUntil.isHidden = true
        }
    }

}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: false)

    if indexPath.section == 1 {
        let lastDepartment = self.department
        self.department = indexPath.row

        tableView.reloadRows(at: [indexPath, IndexPath.init(row: lastDepartment, section: 1)], with: .none)
    }

    if indexPath.section == 0 {
        if indexPath.row == 2 {
            datePickerFrom.isHidden = false
        }
        else if indexPath.row == 4 {
            datePickerUntil.isHidden = false
        }

        tableView.reloadData()
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var count = 0
    if section == 0 {

    } else if section == 1 {
        count = 2
    } else if section == 2 || section == 3 {
        count = 1
    }

    return count
}
</code>```

<p>Let's say I have 4 section. I want make first section be expandable but with static table, cell and static data. </p>

答:
I solved it. I read some example that using Bool value and set the height to manage expand and collapse cell. Here is my final code:

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: false)

    if indexPath.section == 1 {
        let lastDepartment = self.department
        self.department = indexPath.row

        tableView.reloadRows(at: [indexPath, IndexPath.init(row: lastDepartment, section: 1)], with: .none)
    }

    if indexPath.section == 0 && indexPath.row == 1 {

        if !isExpandToDate {
            if isExpandFromDate {
                isExpandFromDate = !isExpandFromDate
                isExpandToDate = !isExpandToDate
            } else {
                isExpandFromDate = !isExpandFromDate
            }
        } else {
            if isExpandFromDate {
                isExpandFromDate = !isExpandToDate
            } else {
                isExpandFromDate = !isExpandFromDate
            }
        }
    }

    if indexPath.section == 0 && indexPath.row == 3 {

        if !isExpandFromDate {
            if isExpandToDate {
                isExpandToDate = !isExpandToDate
                isExpandFromDate = !isExpandFromDate
            } else {
                isExpandToDate = !isExpandToDate
            }
        } else {
            if isExpandToDate {
                isExpandToDate = !isExpandFromDate
            } else {
                isExpandToDate = !isExpandToDate
            }
        }
    }

    tableView.beginUpdates()
    tableView.endUpdates()
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if isExpandFromDate && indexPath.section == 0 && indexPath.row == 2 {
        return 0
    }
    else if isExpandToDate && indexPath.section == 0 && indexPath.row == 4 {
        return 0
    }
    else {
        return super.tableView(tableView, heightForRowAt: indexPath)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Swift: Expandable Static TableView

Body:
Before I post this, I have read some article like this or this , but all of that example always using dynamic data. I want to know how implement expandable tableview in static data. I think this is more simple but I don't have any idea. My snippet code :

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if (indexPath.section == 1) {
        if indexPath.row == self.department {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }
    }

    if indexPath.section == 0 {
        if indexPath.row == 2 {
            datePickerFrom.isHidden = true
        }
        else if indexPath.row == 4 {
            datePickerUntil.isHidden = true
        }
    }

}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: false)

    if indexPath.section == 1 {
        let lastDepartment = self.department
        self.department = indexPath.row

        tableView.reloadRows(at: [indexPath, IndexPath.init(row: lastDepartment, section: 1)], with: .none)
    }

    if indexPath.section == 0 {
        if indexPath.row == 2 {
            datePickerFrom.isHidden = false
        }
        else if indexPath.row == 4 {
            datePickerUntil.isHidden = false
        }

        tableView.reloadData()
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var count = 0
    if section == 0 {

    } else if section == 1 {
        count = 2
    } else if section == 2 || section == 3 {
        count = 1
    }

    return count
}

Let's say I have 4 section. I want make first section be expandable but with static table, cell and static data.

Body:
I solved it. I read some example that using Bool value and set the height to manage expand and collapse cell. Here is my final code:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: false)

    if indexPath.section == 1 {
        let lastDepartment = self.department
        self.department = indexPath.row

        tableView.reloadRows(at: [indexPath, IndexPath.init(row: lastDepartment, section: 1)], with: .none)
    }

    if indexPath.section == 0 && indexPath.row == 1 {

        if !isExpandToDate {
            if isExpandFromDate {
                isExpandFromDate = !isExpandFromDate
                isExpandToDate = !isExpandToDate
            } else {
                isExpandFromDate = !isExpandFromDate
            }
        } else {
            if isExpandFromDate {
                isExpandFromDate = !isExpandToDate
            } else {
                isExpandFromDate = !isExpandFromDate
            }
        }
    }

    if indexPath.section == 0 && indexPath.row == 3 {

        if !isExpandFromDate {
            if isExpandToDate {
                isExpandToDate = !isExpandToDate
                isExpandFromDate = !isExpandFromDate
            } else {
                isExpandToDate = !isExpandToDate
            }
        } else {
            if isExpandToDate {
                isExpandToDate = !isExpandFromDate
            } else {
                isExpandToDate = !isExpandToDate
            }
        }
    }

    tableView.beginUpdates()
    tableView.endUpdates()
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if isExpandFromDate && indexPath.section == 0 && indexPath.row == 2 {
        return 0
    }
    else if isExpandToDate && indexPath.section == 0 && indexPath.row == 4 {
        return 0
    }
    else {
        return super.tableView(tableView, heightForRowAt: indexPath)
    }
}


问:
List bullets like 1) 2) 3)
I need this types of bullets using CSS

1)    Lorem ipsum dolor sit amet, consectetur adipisicing elit

2)    Lorem ipsum dolor sit amet, consectetur adipisicing elit

3)    Lorem ipsum dolor sit amet, consectetur adipisicing elit

Any one have a idea about this ?

答:
Use CSS counters. The counter-increment CSS property is used to increase the value of CSS Counters by a given value. The counter's value can be reset using the counter-reset CSS property. Try this

ol {
  counter-reset: item;
  list-style-type: none;
}

ol li:before {
  content: counter(item) ")";
  padding-right: 5px;
  counter-increment: item
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit</li>
  <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit</li>
  <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit</li>
</ol></code>```

Title: List bullets like 1) 2) 3)

Body:
Use CSS counters. The counter-increment CSS property is used to increase the value of CSS Counters by a given value. The counter's value can be reset using the counter-reset CSS property. Try this

ol {
  counter-reset: item;
  list-style-type: none;
}

ol li:before {
  content: counter(item) ")";
  padding-right: 5px;
  counter-increment: item
}

<ol>
  <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit</li>
  <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit</li>
  <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit</li>
</ol>


问:
string is not getting exploded
Here is my code where explode function is not getting correctly.code looks like this

```<code> <div id="demo-1" data-zs-src='[<?php foreach( $slides as $slide ){?>"<?php echo base_url();?>uploads/<?php echo $slide->image;?>"<?php }?>]' data-zs-overlay="dots">
<div class="demo-inner-content">
  <h1><span>Tasty</span> & <span>Healthy</span></h1>
  <p>For those who have taste for life.</p>
</div>
</code>```

my result looks like this

```<code><div id="demo-1" data-zs-src='["http://localhost/fahiz_kitchen/uploads/upload-file1496902770.jpg""http://localhost/fahiz_kitchen/uploads/upload-file1496901910.gif""http://localhost/fahiz_kitchen/uploads/upload-file1496901900.jpg""http://localhost/fahiz_kitchen/uploads/upload-file1496901887.jpg"]' data-zs-overlay="dots">
<div class="demo-inner-content">
  <h1><span>Tasty</span> & <span>Healthy</span></h1>
  <p>For those who have taste for life.</p>
</div>
</div>
</code>```

i want to get comma in between the result that means my result should be like this

```<code><div id="demo-1" data-zs-src='["http://localhost/fahiz_kitchen/uploads/upload-file1496902770.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901910.gif",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901900.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901887.jpg"
</code>```

答:
plz use this;</p>

```<code><?php foreach( $slides as $slide ){
     $images= base_url()."uploads/". $slide->image;
     var_dump($images);
     $arr= explode(',',$images);
     print_r($arr);
}

?>
</code>```

Title: string is not getting exploded

Body:
Here is my code where explode function is not getting correctly.code looks like this

 <div id="demo-1" data-zs-src='[<?php foreach( $slides as $slide ){?>"<?php echo base_url();?>uploads/<?php echo $slide->image;?>"<?php }?>]' data-zs-overlay="dots">

Tasty & Healthy

For those who have taste for life.

my result looks like this

Tasty & Healthy

For those who have taste for life.

i want to get comma in between the result that means my result should be like this

<div id="demo-1" data-zs-src='["http://localhost/fahiz_kitchen/uploads/upload-file1496902770.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901910.gif",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901900.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901887.jpg"

Body:
plz use this;

<?php foreach( $slides as $slide ){
     $images= base_url()."uploads/". $slide->image;
     var_dump($images);
     $arr= explode(',',$images);
     print_r($arr);
}

?>


问:
CosmosDB grant permission to multiple resources?
I am trying to understand how, using DocumentDB, I can grant permission to multiple resources. It's unclear to me how I would go about this or if it's currently possible.

https://learn.microsoft.com/en-us/azure/cosmos-db/mobile-apps-with-xamarin

In their docs here they state

If you want two users to have access to the same to-do list, you can add additional permissions to the access token in Resource Token Broker.

The Resource Token Broker is linked below:

https://github.com/Azure/azure-documentdb-dotnet/blob/master/samples/xamarin/UserItems/ResourceTokenBroker/ResourceTokenBroker/Controllers/ResourceTokenController.cs#L153-L159

And I assume they specifically mean this:

```<code>using Microsoft.Azure.Documents;

Permission p = new Permission
{
    PermissionMode =  PermissionMode.All,
    ResourceLink = collection.SelfLink,
    ResourcePartitionKey = new PartitionKey(userId),
    Id = permissionId //needs to be unique for a given user
};
</code>```

However, this snippet only support the one partition key. Which is what I want to do, grant permissions for multiple partition keys in a collection.

This is there call where I assume the token is created:

```<code>permission = await Client.CreatePermissionAsync(UriFactory.CreateUserUri(databaseId, userId), p);
</code>```

But again, it looks like a singular permission. Which would mean you'd have to create N permissions and each time you went to access one of those resources, you'd need to request the Token from the Resource Broker? In other words, if I grant permission to 5 resources, when my client goes to the Resource Broker, I need to return 5 tokens?

Is there no way to say: This Resource Token grants PermissionMode.All permissions to all of these resources?

答:
if I grant permission to 5 resources, when my client goes to the Resource Broker, I need to return 5 tokens?

DocumentClient class has four constructors and two of these constructors support the provision of several resource keys allowing the resulting DocumentClient object to be used to authenticate operations against multiple resources. You could grant permissions on multiple resources for a user in your Resource Token Broker API and return a list of permission objects (instead of a single resource token) to the client app.

```<code>FeedResponse<Permission> permFeed = await client.ReadPermissionFeedAsync(UriFactory.CreateUserUri("dbid", " userId"));

List<Permission> permList = permFeed.ToList();
</code>```

The client app could initialize an instance of the DocumentClient class and pass permList after the client app get it.

```<code>var client = new DocumentClient(new Uri(EndpointUri), permList);
</code>```

Body:
I am trying to understand how, using DocumentDB, I can grant permission to multiple resources. It's unclear to me how I would go about this or if it's currently possible.

https://learn.microsoft.com/en-us/azure/cosmos-db/mobile-apps-with-xamarin

In their docs here they state

If you want two users to have access to the same to-do list, you can add additional permissions to the access token in Resource Token Broker.

The Resource Token Broker is linked below:

https://github.com/Azure/azure-documentdb-dotnet/blob/master/samples/xamarin/UserItems/ResourceTokenBroker/ResourceTokenBroker/Controllers/ResourceTokenController.cs#L153-L159

And I assume they specifically mean this:

using Microsoft.Azure.Documents;

Permission p = new Permission
{
    PermissionMode =  PermissionMode.All,
    ResourceLink = collection.SelfLink,
    ResourcePartitionKey = new PartitionKey(userId),
    Id = permissionId //needs to be unique for a given user
};

However, this snippet only support the one partition key. Which is what I want to do, grant permissions for multiple partition keys in a collection.

This is there call where I assume the token is created:

permission = await Client.CreatePermissionAsync(UriFactory.CreateUserUri(databaseId, userId), p);

But again, it looks like a singular permission. Which would mean you'd have to create N permissions and each time you went to access one of those resources, you'd need to request the Token from the Resource Broker? In other words, if I grant permission to 5 resources, when my client goes to the Resource Broker, I need to return 5 tokens?

Is there no way to say: This Resource Token grants PermissionMode.All permissions to all of these resources?

Body:
if I grant permission to 5 resources, when my client goes to the Resource Broker, I need to return 5 tokens?

DocumentClient class has four constructors and two of these constructors support the provision of several resource keys allowing the resulting DocumentClient object to be used to authenticate operations against multiple resources. You could grant permissions on multiple resources for a user in your Resource Token Broker API and return a list of permission objects (instead of a single resource token) to the client app.

FeedResponse<Permission> permFeed = await client.ReadPermissionFeedAsync(UriFactory.CreateUserUri("dbid", " userId"));

List<Permission> permList = permFeed.ToList();

The client app could initialize an instance of the DocumentClient class and pass permList after the client app get it.

var client = new DocumentClient(new Uri(EndpointUri), permList);


问:
Push data into another object
How can I push new values into an existing object?

Basically I get some form datanoteValue and I have some other data being input to my component person which I would like to make part of noteValue before I run my save function.

```<code>let noteValue = form.value;
noteValue.said_by.person_name = this.person.name;
</code>```

This is an example I have working elsewhere but it doesn't seem to work:

```<code>let exValue = form.value;
exValue['due_date'].timestamp = this.timestamp;
</code>```

What am I missing? And is this even the right way to do this?

答:
you can use the spread operator to create a new object that contains both the prevState and the newData you have, then replace the prevState with the newState

const newState = {...prevState, newData}
prevState = newState;

Title: Push data into another object

Body:
How can I push new values into an existing object?

Basically I get some form datanoteValue and I have some other data being input to my component person which I would like to make part of noteValue before I run my save function.

let noteValue = form.value;
noteValue.said_by.person_name = this.person.name;

This is an example I have working elsewhere but it doesn't seem to work:

let exValue = form.value;
exValue['due_date'].timestamp = this.timestamp;

What am I missing? And is this even the right way to do this?


问:
Scanner exception handling
I'm trying to do some simple program and there is a little thing that I curious about at exception handling.

Thus a piece of my code

```<code>do{
       System.out.println(helloWorld.line);

            System.out.print("Value a : ");
            try{
                if(scan.hasNextInt())
                    rep++;
                a = scan.nextInt();
            }
            catch (InputMismatchException e){
                rep = 0;
                scan.next();
                System.out.println("Input Mismatch, try again");
            }
            while (rep == 0);
</code>```

and then another code

```<code>do{
       System.out.println(helloWorld.line);

            System.out.print("Value a : ");
            try{
                if(scan.hasNextInt())
                    rep++;
                a = scan.nextInt();
            }
            catch (InputMismatchException e){
                rep = 0;
                scan.next();
                JOptionPane.showMessageDialog(null,"Input
                mismatch","Error",JOptionPane.INFORMATION_MESSAGE);
            }
            while(rep == 0);
</code>```

I'm doing a piece of code for ignoring the wrong input and do a loop until the scanner read the correct input also give a popup message.
The question is that the first code works as intended, the second piece is running but doing nothing after the first input and the program not terminated. Why?

答:
Try this:-     scan.nextLine(); this line will clear the buffer

```<code>do{
   System.out.println(helloWorld.line);

        System.out.print("Value a : ");
        try{
             scan.nextLine();
            if(scan.hasNextInt())
                rep++;
            a = scan.nextInt();
        }
        catch (InputMismatchException e){
            rep = 0;
            scan.next();
            JOptionPane.showMessageDialog(null,"Input
            mismatch","Error",JOptionPane.INFORMATION_MESSAGE);
        }
        while(rep == 0);
</code>```

For more info: https://itaehun.wordpress.com/2010/09/30/flush-in-java-when-using-nextline/

Title: Scanner exception handling

Body:
I'm trying to do some simple program and there is a little thing that I curious about at exception handling.

Thus a piece of my code

do{
       System.out.println(helloWorld.line);

            System.out.print("Value a : ");
            try{
                if(scan.hasNextInt())
                    rep++;
                a = scan.nextInt();
            }
            catch (InputMismatchException e){
                rep = 0;
                scan.next();
                System.out.println("Input Mismatch, try again");
            }
            while (rep == 0);

and then another code

do{
       System.out.println(helloWorld.line);

            System.out.print("Value a : ");
            try{
                if(scan.hasNextInt())
                    rep++;
                a = scan.nextInt();
            }
            catch (InputMismatchException e){
                rep = 0;
                scan.next();
                JOptionPane.showMessageDialog(null,"Input
                mismatch","Error",JOptionPane.INFORMATION_MESSAGE);
            }
            while(rep == 0);

I'm doing a piece of code for ignoring the wrong input and do a loop until the scanner read the correct input also give a popup message.
The question is that the first code works as intended, the second piece is running but doing nothing after the first input and the program not terminated. Why?

Body:
Try this:-     scan.nextLine(); this line will clear the buffer

do{
   System.out.println(helloWorld.line);

        System.out.print("Value a : ");
        try{
             scan.nextLine();
            if(scan.hasNextInt())
                rep++;
            a = scan.nextInt();
        }
        catch (InputMismatchException e){
            rep = 0;
            scan.next();
            JOptionPane.showMessageDialog(null,"Input
            mismatch","Error",JOptionPane.INFORMATION_MESSAGE);
        }
        while(rep == 0);

For more info: https://itaehun.wordpress.com/2010/09/30/flush-in-java-when-using-nextline/


问:
In nodejs, when the method is called multiple times at the same time, is the variable is shared
I want to generate the short id of number type, but when I call shortid method and output id and emaill, the contents of the output in the console are the same as the incoming variable. the gist in github</p>

答: I get an answer that  change 'var self = this ' to 'var self = {}', because 'this' in method equal 'global'.</p>


问:
How do I prevent my submit button in android from giving me multiple scores when clicked multiple times?
Whenever I answer a question and hit the submit button, a score of 1 should show but on hitting submit button again, it keeps adding 1 to the score and more hits on the submit button keeps adding more 1 to the score. I actually don't want 1 to be added to the score every time the submit button is clicked. I do not want the score to be updated based on the number of times I hit the submit button.

package com.example.android.generalknowledge;

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    int baseScore = 0;

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

    }

    public void submitResult(View view) {
        RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
        boolean answerIsLargestRailwayStation = largestRailwayStation.isChecked();

        RadioButton insects = (RadioButton) findViewById(R.id.insects);
        boolean answerIsInsects = insects.isChecked();

        CheckBox physicsChemistry = (CheckBox) findViewById(R.id.physics_chemistry);
        boolean physicsChemistryIsAnswer = physicsChemistry.isChecked();

        CheckBox physiologyMedicine = (CheckBox) findViewById(R.id.physiology_medicine);
        boolean physiologyMedicineIsAnswer = physiologyMedicine.isChecked();

        CheckBox literature = (CheckBox) findViewById(R.id.literature);
        boolean literatureIsAnswer = literature.isChecked();

        CheckBox peaceEconomics = (CheckBox) findViewById(R.id.peace_economics);
        boolean peaceEconomicsIsAnswer = peaceEconomics.isChecked();

        RadioButton naziParty = (RadioButton) findViewById(R.id.nazi_party);
        boolean answerIsNaziParty = naziParty.isChecked();

        RadioButton allOfTheAbove = (RadioButton) findViewById(R.id.all_of_the_above);
        boolean answerIsAll = allOfTheAbove.isChecked();

        RadioButton filmFinance = (RadioButton) findViewById(R.id.film_finance);
        boolean answerIsFilmFinance = filmFinance.isChecked();

        EditText enterNameHere = (EditText) findViewById(R.id.name_view);
        String name = enterNameHere.getText().toString();

        EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
        String answer = enterAnswerHere.getText().toString();
        if (enterAnswerHere.getText().toString().equals("Africa")) {
            baseScore += 1 ;
        }

        int finalScore = calculateTotalScore(answerIsLargestRailwayStation, answerIsInsects, physicsChemistryIsAnswer,
                physiologyMedicineIsAnswer, literatureIsAnswer, peaceEconomicsIsAnswer, answerIsNaziParty, answerIsAll, answerIsFilmFinance);

        Toast.makeText(MainActivity.this,
                name + " " + "\n" + "You have a Total Score of " + " " + finalScore + " " + "/10", Toast.LENGTH_LONG).show();
    }

    /**
     * This method is called when any of the radio buttons in question one is selected
     */

    public void onRadioButtonClickedOne(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.largest_railway_station:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.highest_railway_station:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.longest_railway_station:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.none_of_the_above:
                if (checked)
                    //Wrong answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question two is selected
     */

    public void onRadioButtonClickedTwo(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.behaviour_of_human_beings:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.insects:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.origin_history:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.rock_formation:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    /**
     * This method is called when the checkboxes for question three are clicked
     */

    public void onCheckboxThreeClicked(View view) {
        //Is the button now checked?
        boolean checked = ((CheckBox) view).isChecked();

        // Check which checkbox is clicked
        switch (view.getId()) {
            case R.id.physics_chemistry:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.physiology_medicine:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.literature:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.peace_economics:
                if (checked)
                    // One of the Correct answers
                    break;
        }
    }

    /**
     * This method is called when any of the radio buttons in question four is selected
     */

    public void onRadioButtonClickedFour(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.labour_party:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.nazi_party:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.leading_party:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.democratic_party:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question six is selected
     */

    public void onRadioButtonClickedSix(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.develop_telescope:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.discovered_jupiter:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.movement_of_pendulum:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.all_of_the_above:
                if (checked)
                    // This is the correct answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question seven is selected
     */

    public void onRadioButtonClickedSeven(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.foreign_finance:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.film_finance:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.federation_football:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.none:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    private int calculateTotalScore(boolean questionOneAnswer, boolean questionTwoAnswer, boolean questionThreeAnswer1,
                                    boolean questionThreeAnswer2, boolean questionThreeAnswer3, boolean questionThreeAnswer4,
                                    boolean questionFourAnswer, boolean questionSixAnswer, boolean questionSevenAnswer) {

        if (questionOneAnswer) {
            baseScore += 1 ;
        }

        if (questionTwoAnswer) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer1) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer2) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer3) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer4) {
            baseScore += 1 ;
        }

        if (questionFourAnswer) {
            baseScore += 1 ;
        }

        if (questionSixAnswer) {
            baseScore += 1 ;
        }

        if (questionSevenAnswer) {
            baseScore += 1 ;
        }

       // EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
       // String answer = enterAnswerHere.getText().toString();
       // {
        //    if (answer == "Africa") {
        //        baseScore = baseScore + 1;
        //    }
       // }
        return baseScore;
    }
}
</code>```

答:
We can achieve by 2 ways,

You can diable the button by button.setEnable(false); once user click for for time

In your case if you don't have button object so you can use one global boolean and make that as false default and once user click for first time do the process and make that boolean as true, from next time check if the boolean is true just return it.

private boolean mIsSubmited = false;

```<code>        public void submitResult(View view) {
            if(mIsSubmited) {
                return;
            }
            mIsSubmited = true;
            RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
            // Remaining code..
        }
</code>```

Body:
Whenever I answer a question and hit the submit button, a score of 1 should show but on hitting submit button again, it keeps adding 1 to the score and more hits on the submit button keeps adding more 1 to the score. I actually don't want 1 to be added to the score every time the submit button is clicked. I do not want the score to be updated based on the number of times I hit the submit button.

package com.example.android.generalknowledge;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    int baseScore = 0;

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

    }

    public void submitResult(View view) {
        RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
        boolean answerIsLargestRailwayStation = largestRailwayStation.isChecked();

        RadioButton insects = (RadioButton) findViewById(R.id.insects);
        boolean answerIsInsects = insects.isChecked();

        CheckBox physicsChemistry = (CheckBox) findViewById(R.id.physics_chemistry);
        boolean physicsChemistryIsAnswer = physicsChemistry.isChecked();

        CheckBox physiologyMedicine = (CheckBox) findViewById(R.id.physiology_medicine);
        boolean physiologyMedicineIsAnswer = physiologyMedicine.isChecked();

        CheckBox literature = (CheckBox) findViewById(R.id.literature);
        boolean literatureIsAnswer = literature.isChecked();

        CheckBox peaceEconomics = (CheckBox) findViewById(R.id.peace_economics);
        boolean peaceEconomicsIsAnswer = peaceEconomics.isChecked();

        RadioButton naziParty = (RadioButton) findViewById(R.id.nazi_party);
        boolean answerIsNaziParty = naziParty.isChecked();

        RadioButton allOfTheAbove = (RadioButton) findViewById(R.id.all_of_the_above);
        boolean answerIsAll = allOfTheAbove.isChecked();

        RadioButton filmFinance = (RadioButton) findViewById(R.id.film_finance);
        boolean answerIsFilmFinance = filmFinance.isChecked();

        EditText enterNameHere = (EditText) findViewById(R.id.name_view);
        String name = enterNameHere.getText().toString();

        EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
        String answer = enterAnswerHere.getText().toString();
        if (enterAnswerHere.getText().toString().equals("Africa")) {
            baseScore += 1 ;
        }

        int finalScore = calculateTotalScore(answerIsLargestRailwayStation, answerIsInsects, physicsChemistryIsAnswer,
                physiologyMedicineIsAnswer, literatureIsAnswer, peaceEconomicsIsAnswer, answerIsNaziParty, answerIsAll, answerIsFilmFinance);

        Toast.makeText(MainActivity.this,
                name + " " + "\n" + "You have a Total Score of " + " " + finalScore + " " + "/10", Toast.LENGTH_LONG).show();
    }

    /**
     * This method is called when any of the radio buttons in question one is selected
     */

    public void onRadioButtonClickedOne(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.largest_railway_station:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.highest_railway_station:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.longest_railway_station:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.none_of_the_above:
                if (checked)
                    //Wrong answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question two is selected
     */

    public void onRadioButtonClickedTwo(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.behaviour_of_human_beings:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.insects:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.origin_history:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.rock_formation:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    /**
     * This method is called when the checkboxes for question three are clicked
     */

    public void onCheckboxThreeClicked(View view) {
        //Is the button now checked?
        boolean checked = ((CheckBox) view).isChecked();

        // Check which checkbox is clicked
        switch (view.getId()) {
            case R.id.physics_chemistry:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.physiology_medicine:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.literature:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.peace_economics:
                if (checked)
                    // One of the Correct answers
                    break;
        }
    }

    /**
     * This method is called when any of the radio buttons in question four is selected
     */

    public void onRadioButtonClickedFour(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.labour_party:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.nazi_party:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.leading_party:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.democratic_party:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question six is selected
     */

    public void onRadioButtonClickedSix(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.develop_telescope:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.discovered_jupiter:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.movement_of_pendulum:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.all_of_the_above:
                if (checked)
                    // This is the correct answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question seven is selected
     */

    public void onRadioButtonClickedSeven(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.foreign_finance:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.film_finance:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.federation_football:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.none:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    private int calculateTotalScore(boolean questionOneAnswer, boolean questionTwoAnswer, boolean questionThreeAnswer1,
                                    boolean questionThreeAnswer2, boolean questionThreeAnswer3, boolean questionThreeAnswer4,
                                    boolean questionFourAnswer, boolean questionSixAnswer, boolean questionSevenAnswer) {

        if (questionOneAnswer) {
            baseScore += 1 ;
        }

        if (questionTwoAnswer) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer1) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer2) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer3) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer4) {
            baseScore += 1 ;
        }

        if (questionFourAnswer) {
            baseScore += 1 ;
        }

        if (questionSixAnswer) {
            baseScore += 1 ;
        }

        if (questionSevenAnswer) {
            baseScore += 1 ;
        }

       // EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
       // String answer = enterAnswerHere.getText().toString();
       // {
        //    if (answer == "Africa") {
        //        baseScore = baseScore + 1;
        //    }
       // }
        return baseScore;
    }
}

Body:
We can achieve by 2 ways,

You can diable the button by button.setEnable(false); once user click for for time

In your case if you don't have button object so you can use one global boolean and make that as false default and once user click for first time do the process and make that boolean as true, from next time check if the boolean is true just return it.

private boolean mIsSubmited = false;

        public void submitResult(View view) {
            if(mIsSubmited) {
                return;
            }
            mIsSubmited = true;
            RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
            // Remaining code..
        }


答:
You can declare a Boolean globally and set it to false at first.
then on button click you can turn its value to true.
on the button click you can check if its false then only to increase the score.</p>

Title: How do I prevent my submit button in android from giving me multiple scores when clicked multiple times?


问:
Laravel 5.4 - Skip Model Mutator
I have a model mutator that adds a random string to the end of a slug. </p>

```<code>public function setSlugAttribute($slug) {

  $slugNumber = mt_rand(100000, 999999);
  $this->attributes['slug'] = $slug."-".$slugNumber;
}
</code>```

<p>I only need this to happen the first time that the model is created, not when the model is updated. How can I skip the mutator when the model already exists and the slug is already good? </p>

答:
```<code>this Delete your slug mutator and use the creating
public static function boot()
    {
        parent::boot();
        Posts::saving(function(Posts $model){
            $random = mt_rand(10000, 99999);
            $model->slug = str_slug($model->title). '-'. $random;
        });
    }
</code>```

Title: Laravel 5.4 - Skip Model Mutator

Body:
I have a model mutator that adds a random string to the end of a slug.

public function setSlugAttribute($slug) {

  $slugNumber = mt_rand(100000, 999999);
  $this->attributes['slug'] = $slug."-".$slugNumber;
}

I only need this to happen the first time that the model is created, not when the model is updated. How can I skip the mutator when the model already exists and the slug is already good?


问:
ffmpeg API encoding mpeg-4 Windows Media Player error
We have an app that uses the ffmpeg C API to encode mpeg-4 (AV_CODEC_ID_MPEG4) files in a mp4 container.  The problem is that the files don't play in Windows Media Player or the Windows 10 video player "Movies & TV" app.  It plays in VLC, google chrome, Ubuntu's video player, and all other video players I've tried.

The two Windows players are able to play other files encoded with mpeg-4 in mp4 container.  I also tested transcoding video files to the same format using the command line 'ffmpeg' tool and was successfully able to play the video using the following command:

ffmpeg input.avi -c:v mpeg4 output.mp4

While I found the following commands do not work:

ffmpeg input.avi -c:v mpeg4 -vtag xvid output.mp4

ffmpeg input.avi -c:v libxvid output.mp4

# the last command wont play with windows media player but VLC can still play it.  If the extension of the output file is changed to avi for the last two commands then Windows media player can play it.

I started looking at the ffmpeg src code but it appears a bit large/complex, I tried using the simpler "encode_video.c" example, which was able to encode a video and play it in Ubuntu's default video player but VLC nor Windows Media Player could play it.

We need to encode these using the ffmpeg API, not the command line tool, so I am wondering what the ffmpeg command line tool is doing that I am not, or any ideas on what the problem could be and how to get this working.

Thanks.

答: According to this and this XVid playback is not supported by Movies & TV app as well as other Win Store apps using WinRT out of box video capabilities. And according to this it is also not supported by Windows Media Player. If you've managed to play it using Windows Media Player then most likely you had corresponding third-party Direct Show codec installed. There is actually no real point to use XVid in 2017, just use h264 instead.</p>


问:
Android RecyclerView : Setting a view at the bottom of each row of recyclerView.
I have a view that works as a footer of each row of recyclerView. What I am trying to achieve is something like this.

The image represents a row of my recyclerView.and each box a different view.

For most of the part it is obvious but I am having issues placing the the view that is represented by the yellow box at the bottom of the row.

I have tried a few different ways for example:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <View
        android:id="@+id/colored_penal"
        android:layout_width="4dp"
        android:layout_height="fill_parent"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="128"
            android:textSize="24sp"/>

        <TextView
            android:id="@+id/unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="mtr" />

    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/hospital_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hey, this is a dummy hospital"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/hospital_address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/hospital_name"
            android:text="At the end of the road" />

        <!--This is the yellow box view that I want at the bottom-->
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="8dp"
            android:layout_alignParentBottom="true">

            <TextView
                android:id="@+id/waiting_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Waiting time: 40 mins"
                android:textSize="8sp"
                android:layout_weight="1"/>

            <TextView
                android:id="@+id/travel_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Travel time: 20 mins"
                android:textSize="8sp"
                android:layout_weight="1"/>

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

</RelativeLayout>
</code>```

I have used alignParentBottom as true yet the view is not getting placed at the bottom of the row. It makes sense that Android squeezes each row to make sure it looks like a recyclerView but than how to put something at the bottom?

I also tried setting up layout_height="fill_parent"  and gravity="bottom" for the LinearLayout (yellow view) despite knowing fill_parent is deprecated but it didn't work anyways.

Would appreciate any input helping me achieve this.

答:
I just optimized layout. You need to specify your own View Components and attributes like maxLines or textSizes and etc. Its layout-ready.

```<code><LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="100dp"
   android:orientation="horizontal">

   <View
       android:layout_width="10dp"
       android:layout_height="match_parent"/>

   <View
       android:layout_width="100dp"
       android:layout_height="match_parent"/>

   <LinearLayout
       android:layout_width="0dp"
       android:layout_height="match_parent"
       android:layout_weight="1"
       android:orientation="vertical"
       android:padding="12dp">

       <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           tools:text="Title"/>

       <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           tools:text="Content"/>

       <Space
           android:layout_width="match_parent"
           android:layout_height="0dp"
           android:layout_weight="1"/>

       <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           tools:text="Footer"/>
   </LinearLayout>
</code>```

Good luck there

Emre

Body:
I have a view that works as a footer of each row of recyclerView. What I am trying to achieve is something like this.

The image represents a row of my recyclerView.and each box a different view.

For most of the part it is obvious but I am having issues placing the the view that is represented by the yellow box at the bottom of the row.

I have tried a few different ways for example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <View
        android:id="@+id/colored_penal"
        android:layout_width="4dp"
        android:layout_height="fill_parent"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="128"
            android:textSize="24sp"/>

        <TextView
            android:id="@+id/unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="mtr" />

    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/hospital_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hey, this is a dummy hospital"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/hospital_address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/hospital_name"
            android:text="At the end of the road" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="8dp"
            android:layout_alignParentBottom="true">

            <TextView
                android:id="@+id/waiting_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Waiting time: 40 mins"
                android:textSize="8sp"
                android:layout_weight="1"/>

            <TextView
                android:id="@+id/travel_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Travel time: 20 mins"
                android:textSize="8sp"
                android:layout_weight="1"/>

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

</RelativeLayout>

I have used alignParentBottom as true yet the view is not getting placed at the bottom of the row. It makes sense that Android squeezes each row to make sure it looks like a recyclerView but than how to put something at the bottom?

I also tried setting up layout_height="fill_parent"  and gravity="bottom" for the LinearLayout (yellow view) despite knowing fill_parent is deprecated but it didn't work anyways.

Would appreciate any input helping me achieve this.

Body:
I just optimized layout. You need to specify your own View Components and attributes like maxLines or textSizes and etc. Its layout-ready.

<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="100dp"
   android:orientation="horizontal">

   <View
       android:layout_width="10dp"
       android:layout_height="match_parent"/>

   <View
       android:layout_width="100dp"
       android:layout_height="match_parent"/>

   <LinearLayout
       android:layout_width="0dp"
       android:layout_height="match_parent"
       android:layout_weight="1"
       android:orientation="vertical"
       android:padding="12dp">

       <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           tools:text="Title"/>

       <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           tools:text="Content"/>

       <Space
           android:layout_width="match_parent"
           android:layout_height="0dp"
           android:layout_weight="1"/>

       <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           tools:text="Footer"/>
   </LinearLayout>

Good luck there

Emre


问:
need html and javascript testing code for Secugen Hamster pro2o
I'm using Secugen Hamster pro2o for finger print.I already installed all driver related to secugen hamster.Now i need html and javascript code for testing.</p>

答:
Here you go:</p>

```<code><html>
<head>
<title>ActiveX Example 1.1 of SecuGen FDx Pro SDK </title>

<script lang=javascript>
<!--
var aaa = 0;
function fnOpenDevice()
{
    document.frmmain.objFP.DeviceID = document.frmmain.inc.value;
    document.frmmain.objFP.CodeName = document.frmmain.dev.value;
    document.frmmain.objFP.MinutiaeMode = document.frmmain.templateFormat.value;

    // template format of objVerify should be the same to those of objFP[]
    objVerify.MinutiaeMode = document.frmmain.templateFormat.value;
    return;
}

function fnCapture()
{
    document.frmmain.objFP.Capture();
    var result = document.frmmain.objFP.ErrorCode;
alert(result);
    if (result == 0)
    {
        //var strimg1 = objFP.ImageTextData;
        var strmin = document.frmmain.objFP.MinTextData;
alert(strmin);
        document.frmmain.min.value = strmin;
    }
    else
        alert('failed - ' + result);

    return;
}

function fnRegister()
{
    var strmin1 = document.frmmain.min[0].value;
    var strmin2 = document.frmmain.min[1].value;

    if ( objVerify.RegisterForText(strmin1, strmin2) && objVerify.ErrorCode == 0 )
        alert('success- registered');
    else
        alert('failed - ' + objVerify.ErrorCode);

    return;
}

function fnVerifyEx()
{
    var strmin1 = document.frmmain.min[0].value;
    var strmin2 = document.frmmain.min[1].value;
    var strmin3 = document.frmmain.min[2].value;

    if ( objVerify.VerifyExForText(strmin1, strmin2, strmin3) && objVerify.ErrorCode == 0)
        alert('Success - matched');
    else
        alert('Failed - ' + objVerify.ErrorCode);

    return;
}

function fnVerify()
{
    var strmin1 = document.frmmain.min[0].value;
    var strmin2 = document.frmmain.min[2].value;

    if ( objVerify.VerifyForText(strmin1, strmin2) && objVerify.ErrorCode == 0 )
        alert('Success - matched');
    else
        alert('Failed - ' + objVerify.ErrorCode);

    return;
}

function fnSetimage()
{
    document.frmmain.objFP.ImageTextData = document.frmmain.img1.value;

    return;
}
// -->

</script>
</head>

<body>
<h4><b>ActiveX Example 1.1 of SecuGen FDx Pro SDK</b></h4>
<p></p>

<OBJECT id=objVerify style="LEFT: 0px; TOP: 0px" height=0 width=0
    classid="CLSID:8D613732-7D38-4664-A8B7-A24049B96117"
    name=objVerify VIEWASTEXT>
</OBJECT>

<form name=frmmain>

Device Type :
<select name=dev>
<option value=0>FDP02
<option value=1>FDU02
<option value=2>FDU03
<option value=3>FDU04
<option selected value=4>FDU05

</select>

Instance No. :
<select name=inc>
<option value=-1>-1
<option value=0>0
<option value=1>1
<option value=2>2
<option value=3>3
<option value=4>4
<option value=5>5
<option value=6>6
<option value=7>7
<option value=8>8
<option value=9>9
</select>

<p>
Template Format:
<select name=templateFormat>
<option value=256>ANSI 378
<option value=512>SG 400
<option value=768>ISO 19794-2
</select>

<input type=button name=open value='Open Device' OnClick='fnOpenDevice();'>
<p>

<table border=1 cellspacing=0 cellpadding=0>
<caption> Fingerprint Images </caption>
<tr>
<td>
    <OBJECT id=objFP style="LEFT: 0px; WIDTH: 149px; TOP: 0px; HEIGHT: 182px" height=182
        width=149 classid="CLSID:D547FDD7-82F6-44e8-AFBA-7553ADCEE7C8" name=objFP VIEWASTEXT>
    <PARAM NAME="CodeName" VALUE="1">
    </OBJECT>
</td>
</tr>
<tr>
<td align=center><input type=button name=btnCapture1 value='Capture' OnClick='fnCapture();'></td>
</tr>
</table>

<p>

min1 : <input type=text id=min name=min><br>
<p>
<input type=button name=btnRegister value='Register' OnClick='fnRegister();' style='width:200px'>
<br>
<input type=button name=btnVerify value='VerifyEx' OnClick='fnVerifyEx();' style='width:200px'>
<br>
<input type=button name=btnVerify value='Verify' OnClick='fnVerify();' style='width:200px'>

</form>
<script>
fnOpenDevice();
</script>
</BODY>
</HTML>
</code>```

Body:
Here you go:

<html>
<head>
<title>ActiveX Example 1.1 of SecuGen FDx Pro SDK </title>

<script lang=javascript>
<!--
var aaa = 0;
function fnOpenDevice()
{
    document.frmmain.objFP.DeviceID = document.frmmain.inc.value;
    document.frmmain.objFP.CodeName = document.frmmain.dev.value;
    document.frmmain.objFP.MinutiaeMode = document.frmmain.templateFormat.value;

    // template format of objVerify should be the same to those of objFP[]
    objVerify.MinutiaeMode = document.frmmain.templateFormat.value;
    return;
}

function fnCapture()
{
    document.frmmain.objFP.Capture();
    var result = document.frmmain.objFP.ErrorCode;
alert(result);
    if (result == 0)
    {
        //var strimg1 = objFP.ImageTextData;
        var strmin = document.frmmain.objFP.MinTextData;
alert(strmin);
        document.frmmain.min.value = strmin;
    }
    else
        alert('failed - ' + result);

    return;
}

function fnRegister()
{
    var strmin1 = document.frmmain.min[0].value;
    var strmin2 = document.frmmain.min[1].value;

    if ( objVerify.RegisterForText(strmin1, strmin2) && objVerify.ErrorCode == 0 )
        alert('success- registered');
    else
        alert('failed - ' + objVerify.ErrorCode);

    return;
}

function fnVerifyEx()
{
    var strmin1 = document.frmmain.min[0].value;
    var strmin2 = document.frmmain.min[1].value;
    var strmin3 = document.frmmain.min[2].value;

    if ( objVerify.VerifyExForText(strmin1, strmin2, strmin3) && objVerify.ErrorCode == 0)
        alert('Success - matched');
    else
        alert('Failed - ' + objVerify.ErrorCode);

    return;
}

function fnVerify()
{
    var strmin1 = document.frmmain.min[0].value;
    var strmin2 = document.frmmain.min[2].value;

    if ( objVerify.VerifyForText(strmin1, strmin2) && objVerify.ErrorCode == 0 )
        alert('Success - matched');
    else
        alert('Failed - ' + objVerify.ErrorCode);

    return;
}

function fnSetimage()
{
    document.frmmain.objFP.ImageTextData = document.frmmain.img1.value;

    return;
}
// -->

</script>
</head>

<body>
<h4><b>ActiveX Example 1.1 of SecuGen FDx Pro SDK</b></h4>
<p></p>

<OBJECT id=objVerify style="LEFT: 0px; TOP: 0px" height=0 width=0
    classid="CLSID:8D613732-7D38-4664-A8B7-A24049B96117"
    name=objVerify VIEWASTEXT>
</OBJECT>

<form name=frmmain>

Device Type :
<select name=dev>
<option value=0>FDP02
<option value=1>FDU02
<option value=2>FDU03
<option value=3>FDU04
<option selected value=4>FDU05

</select>

Instance No. :
<select name=inc>
<option value=-1>-1
<option value=0>0
<option value=1>1
<option value=2>2
<option value=3>3
<option value=4>4
<option value=5>5
<option value=6>6
<option value=7>7
<option value=8>8
<option value=9>9
</select>

<p>
Template Format:
<select name=templateFormat>
<option value=256>ANSI 378
<option value=512>SG 400
<option value=768>ISO 19794-2
</select>

<input type=button name=open value='Open Device' OnClick='fnOpenDevice();'>
<p>

<table border=1 cellspacing=0 cellpadding=0>
<caption> Fingerprint Images </caption>
<tr>
<td>
    <OBJECT id=objFP style="LEFT: 0px; WIDTH: 149px; TOP: 0px; HEIGHT: 182px" height=182
        width=149 classid="CLSID:D547FDD7-82F6-44e8-AFBA-7553ADCEE7C8" name=objFP VIEWASTEXT>
    <PARAM NAME="CodeName" VALUE="1">
    </OBJECT>
</td>
</tr>
<tr>
<td align=center><input type=button name=btnCapture1 value='Capture' OnClick='fnCapture();'></td>
</tr>
</table>

<p>

min1 : <input type=text id=min name=min><br>
<p>
<input type=button name=btnRegister value='Register' OnClick='fnRegister();' style='width:200px'>
<br>
<input type=button name=btnVerify value='VerifyEx' OnClick='fnVerifyEx();' style='width:200px'>
<br>
<input type=button name=btnVerify value='Verify' OnClick='fnVerify();' style='width:200px'>

</form>
<script>
fnOpenDevice();
</script>
</BODY>
</HTML>


问:
SQL Server subqueries in CASE THEN with multiple JOINS
I've searched high and low for an answer but I'm not finding one...

I'm trying to run a subquery inside a CASE THEN statement based on qualifier, that goes something like this:

```<code>SELECT
    CASE
        WHEN cbpotm.DOLCheck LIKE '%<%'
        THEN
        (
            SELECT
                ...
            FROM #AnotherTempTable AS CB
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            WHERE CONDITION AND CONDITION
            AND CONDITION IN ( 1, 2, 3, 4 )
            AND CAST(SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 1, 4) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 5, 2) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 7, 2) AS DATE) BETWEEN CB.SomeDate AND CB.SomeOtherDate
            GROUP BY FIELD, FIELD
        )
        END
FROM
#TempTable cbpotm
</code>```

Apparently I'm missing the mark because I'm not allowed to have more than one JOIN inside the CASE THEN without introducing the statement with an EXISTS clause.

I'm not trying to compare the statement to anything so I can't see why I should only use a single field to match against?
I also don't see why I should use EXISTS because I'm not trying to perform validation...

答:
try Something like this :</p>

```<code>SELECT *
FROM
#TempTable cbpotm
outer apply
(
            SELECT *
            FROM #AnotherTempTable AS CB
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            WHERE CONDITION AND CONDITION
            AND CONDITION IN ( 1, 2, 3, 4 )
            AND CAST(SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 1, 4) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 5, 2) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 7, 2) AS DATE) BETWEEN CB.SomeDate AND CB.SomeOtherDate
            AND cbpotm.DOLCheck LIKE '%<%'
            GROUP BY FIELD, FIELD

) tmp
</code>```

Body:
I've searched high and low for an answer but I'm not finding one...

I'm trying to run a subquery inside a CASE THEN statement based on qualifier, that goes something like this:

SELECT
    CASE
        WHEN cbpotm.DOLCheck LIKE '%<%'
        THEN
        (
            SELECT
                ...
            FROM #AnotherTempTable AS CB
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            WHERE CONDITION AND CONDITION
            AND CONDITION IN ( 1, 2, 3, 4 )
            AND CAST(SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 1, 4) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 5, 2) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 7, 2) AS DATE) BETWEEN CB.SomeDate AND CB.SomeOtherDate
            GROUP BY FIELD, FIELD
        )
        END
FROM
#TempTable cbpotm

Apparently I'm missing the mark because I'm not allowed to have more than one JOIN inside the CASE THEN without introducing the statement with an EXISTS clause.

I'm not trying to compare the statement to anything so I can't see why I should only use a single field to match against?
I also don't see why I should use EXISTS because I'm not trying to perform validation...

Body:
try Something like this :

SELECT *
FROM
#TempTable cbpotm
outer apply
(
            SELECT *
            FROM #AnotherTempTable AS CB
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            WHERE CONDITION AND CONDITION
            AND CONDITION IN ( 1, 2, 3, 4 )
            AND CAST(SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 1, 4) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 5, 2) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 7, 2) AS DATE) BETWEEN CB.SomeDate AND CB.SomeOtherDate
            AND cbpotm.DOLCheck LIKE '%<%'
            GROUP BY FIELD, FIELD

) tmp


问:
What is a docker-compose.yml file?
I can't find a real definition of what a docker-compose file is.

Is it correct to say this:

A docker-compose file is a YAML file that allows us to deploy multiples Docker containers at the same time.

I'd like to be able to explain a bit better what a docker-compose file is.

答:
A docker-compose.yml is a config file for Docker Compose.

It allows to deploy, combine, and configure multiple docker containers at the same time. The Docker "rule" is to outsource every single process to its own Docker container.

Take for example a simple web application: You need a server, a database, and PHP. So you can set three docker containers with Apache2, PHP, and MySQL.

The advantage of Docker Compose is easy configuration. You don't have to write a big bunch of commands into Bash. You can predefine it in the docker-compose.yml:

db:
    image: mysql
    ports:
        - "3306:3306"
    environment:
        MYSQL_DATABASE: example_db
        MYSQL_USER: root
        MYSQL_PASSWORD: rootpw
php:
    image: php
    ports:
        - "80:80"
        - "443:443"
    volumes:
        - ./SRC:/var/www/
    links:
        - db
```

As you can see in my example, I define port forwarding, volumes for external data, and links to the other Docker container. It's fast, reproducible, and not that hard to understand.

The Docker Compose file format is formally specified which enables docker-compose.yml files being executed with something else than Docker, Podman for example.

Title: What is a docker-compose.yml file?

Body:
A docker-compose.yml is a config file for Docker Compose.

It allows to deploy, combine, and configure multiple docker containers at the same time. The Docker "rule" is to outsource every single process to its own Docker container.

Take for example a simple web application: You need a server, a database, and PHP. So you can set three docker containers with Apache2, PHP, and MySQL.

The advantage of Docker Compose is easy configuration. You don't have to write a big bunch of commands into Bash. You can predefine it in the docker-compose.yml:

db:
    image: mysql
    ports:
        - "3306:3306"
    environment:
        MYSQL_DATABASE: example_db
        MYSQL_USER: root
        MYSQL_PASSWORD: rootpw
php:
    image: php
    ports:
        - "80:80"
        - "443:443"
    volumes:
        - ./SRC:/var/www/
    links:
        - db

As you can see in my example, I define port forwarding, volumes for external data, and links to the other Docker container. It's fast, reproducible, and not that hard to understand.

The Docker Compose file format is formally specified which enables docker-compose.yml files being executed with something else than Docker, Podman for example.


问:
Rails3 - How to make a submit button for a nested resource
I'm using SimpleForm in Rails 3. How do I make the submit button for this nested resource?

```<code>resources :schools do
  resources :students
end

<%= simple_form_for @student do |f| %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  <%= f.button :submit %>
<% end %>
</code>```

If I use f.submit:

```<code>ActionView::Template::Error (undefined method `students_path' for #<#<Class:0x000001040ddfb8>:0x000001040d2578>):
1: <%= simple_form_for @student do |f| %>
2:     <%= f.input :first_name %>
3:     <%= f.input :last_name %>
4:     <%= f.submit %>
</code>```

答: Just use <%= f.submit %> instead of <%= f.button :submit %>

Body:
I'm using SimpleForm in Rails 3. How do I make the submit button for this nested resource?

resources :schools do
  resources :students
end

<%= simple_form_for @student do |f| %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  <%= f.button :submit %>
<% end %>

If I use f.submit:

ActionView::Template::Error (undefined method `students_path' for #<#<Class:0x000001040ddfb8>:0x000001040d2578>):
1: <%= simple_form_for @student do |f| %>
2:     <%= f.input :first_name %>
3:     <%= f.input :last_name %>
4:     <%= f.submit %>

ContentLicense: CC BY-SA 2.5