问:
Getting vagrant box definition by http
We have several vagrant boxes in our company and their Vagrantfiles Currently are very similar, the minimal code reproducing the issue I'm dealing with is

```<code>Vagrant.configure("2") do |config|

  config.vm.box = "some_box_name"

  case RbConfig::CONFIG['host_os']
  when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
    config.vm.box_url = "file:////smbhost.ourintra.net/VagrantBoxes/" + config.vm.box + ".json"
  when /darwin|mac os/
    config.vm.box_url = "file:///Volumes/VagrantBoxes/" + config.vm.box + ".json"
  else
    config.vm.box_url = "file:///media/VagrantBoxes/" + config.vm.box + ".json"
  end
  config.vm.network :public_network

end
</code>```

the some_box_name.json will have link to the actual .box file:

```<code>{
   "name":"some_box_name",
   "versions":[
      {
         "version":"1.1337",
         "status":"active",
         "providers":[
            {
               "name":"virtualbox",
               "url":"http://httphost.ourintra.net/Public/VagrantBoxes/some_box_name-1337.box"
            }
         ]
      }
   ]
}
</code>```

The solution above works for me and my colleagues, but I don't like to mount VagrantBoxes every time and I believe there should be more elegant ways, so I've tried to reference the json by http (it lies near .box files on httphost):

```<code>Vagrant.configure("2") do |config|

  config.vm.box = "some_box_name"

  config.vm.box_url = "http://httphost.ourintra.net/Public/VagrantBoxes/" + config.vm.box + ".json"

  config.vm.network :public_network

end
</code>```

And this solution isn't working:

```<code>Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'some_box_name' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
==> default: Box file was not detected as metadata. Adding it directly...
==> default: Adding box 'some_box_name' (v0) for provider: virtualbox
    default: Downloading: http:/httphost.ourintra.net/Public/VagrantBoxes/some_box_name.json
The box failed to unpackage properly. Please verify that the box
file you're trying to add is not corrupted and that enough disk space
is available and then try again.
The output from attempting to unpackage (if any):

bsdtar: Error opening archive: Unrecognized archive format
</code>```

I believe vagrant thinks I'm trying to provide it with direct .box url, but I don't want to do it, because box file names are changed in every build and .json names are static. Is it possible to fix this by changes to Vagrantfiles without much changes to remote files layout?

答:
I found an answer in the similar question on superuser, my problem was in Content-Type returned by webserver. Solution:</p>

```<code>Content-Type: application/json
</code>```

Title: Getting vagrant box definition by http

Body:
We have several vagrant boxes in our company and their Vagrantfiles Currently are very similar, the minimal code reproducing the issue I'm dealing with is

Vagrant.configure("2") do |config|

  config.vm.box = "some_box_name"

  case RbConfig::CONFIG['host_os']
  when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
    config.vm.box_url = "file:////smbhost.ourintra.net/VagrantBoxes/" + config.vm.box + ".json"
  when /darwin|mac os/
    config.vm.box_url = "file:///Volumes/VagrantBoxes/" + config.vm.box + ".json"
  else
    config.vm.box_url = "file:///media/VagrantBoxes/" + config.vm.box + ".json"
  end
  config.vm.network :public_network

end

the some_box_name.json will have link to the actual .box file:

{
   "name":"some_box_name",
   "versions":[
      {
         "version":"1.1337",
         "status":"active",
         "providers":[
            {
               "name":"virtualbox",
               "url":"http://httphost.ourintra.net/Public/VagrantBoxes/some_box_name-1337.box"
            }
         ]
      }
   ]
}

The solution above works for me and my colleagues, but I don't like to mount VagrantBoxes every time and I believe there should be more elegant ways, so I've tried to reference the json by http (it lies near .box files on httphost):

Vagrant.configure("2") do |config|

  config.vm.box = "some_box_name"

  config.vm.box_url = "http://httphost.ourintra.net/Public/VagrantBoxes/" + config.vm.box + ".json"

  config.vm.network :public_network

end

And this solution isn't working:

Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'some_box_name' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
==> default: Box file was not detected as metadata. Adding it directly...
==> default: Adding box 'some_box_name' (v0) for provider: virtualbox
    default: Downloading: http:/httphost.ourintra.net/Public/VagrantBoxes/some_box_name.json
The box failed to unpackage properly. Please verify that the box
file you're trying to add is not corrupted and that enough disk space
is available and then try again.
The output from attempting to unpackage (if any):

bsdtar: Error opening archive: Unrecognized archive format

I believe vagrant thinks I'm trying to provide it with direct .box url, but I don't want to do it, because box file names are changed in every build and .json names are static. Is it possible to fix this by changes to Vagrantfiles without much changes to remote files layout?

Body:
I found an answer in the similar question on superuser, my problem was in Content-Type returned by webserver. Solution:

Content-Type: application/json


来源: stackexchange

问:
GAE datastore cached entities under Python objects
I have this code here: http://sprunge.us/TAjH?py

Why am I getting 10 instead of 1 (or what is in the DB)? Also, any new retrieved python object (as entity) has the very same ID (and maybe even memory address). Why that? How should I proceed in order to have different objects with the real value stored under the DB?

答:
Answered it here: How do I refresh an NDB entity from the datastore?

So the use_cache=False is the solution, while retrieving from the datastore.

ContentLicense: CC BY-SA 3.0


问:
How to write a getter for a container of shared_ptrs which does not allow modification of data
Let's say I have a private variable which is a vector of shared_ptrs to non-const objects.

Is it possible to write a getter method which only allows read access to the data pointed to by the shared pointers?

I want to be able to use range-based loops for elegance, so I want to avoid writing const_iterators.

My understanding is that const shared_ptr<T> makes the pointer itself const, not T. I tried to compile shared_ptr<const T>, but it doesn't compile if T itself is not declared const in the class.

In other words, how could I write something like:

```<code>#include <iostream>
#include <vector>
#include <memory>

using std::vector;
using std::shared_ptr;
using std::make_shared;
using std::cout;
using std::endl;

class MyClass{

public:
    MyClass(int element1, int element2)
    {
        myVector_.push_back(std::make_shared<int>(element1));
        myVector_.push_back(std::make_shared<int>(element2));
    }

    // I want something like this, but doesn't compile
//  const vector<shared_ptr<const int>> readMyVector() const {return myVector_;}

    const vector<shared_ptr<int>> readMyVector() const {return myVector_;}

private:

    // Should NOT be <const int>, the class should be able to modify its elements
    vector<shared_ptr<int>> myVector_;
};

int main(){
    auto testobject = MyClass(1,2);
    for (auto my_protected_data : testobject.readMyVector()){
        cout<<(*my_protected_data)<<endl;
        (*my_protected_data) = 25;
        cout<<(*my_protected_data)<<endl; // Should not happen
    }
    return 0;
}
</code>```

答:
If you want to make your getter to return vector of shared pointers to const data, there is only one way, to return copy of shared pointers to const data.</p>

```<code>const vector<shared_ptr<const int>> readMyVector() const
{
   vector<shared_ptr<const int>> cdata(myVector_.begin(), myVector_.end());
   return cdata;
}
</code>```

Body:
Let's say I have a private variable which is a vector of shared_ptrs to non-const objects.

Is it possible to write a getter method which only allows read access to the data pointed to by the shared pointers?

I want to be able to use range-based loops for elegance, so I want to avoid writing const_iterators.

My understanding is that const shared_ptr<T> makes the pointer itself const, not T. I tried to compile shared_ptr<const T>, but it doesn't compile if T itself is not declared const in the class.

In other words, how could I write something like:

#include <iostream>
#include <vector>
#include <memory>

using std::vector;
using std::shared_ptr;
using std::make_shared;
using std::cout;
using std::endl;

class MyClass{

public:
    MyClass(int element1, int element2)
    {
        myVector_.push_back(std::make_shared<int>(element1));
        myVector_.push_back(std::make_shared<int>(element2));
    }

    // I want something like this, but doesn't compile
//  const vector<shared_ptr<const int>> readMyVector() const {return myVector_;}

    const vector<shared_ptr<int>> readMyVector() const {return myVector_;}

private:

    // Should NOT be <const int>, the class should be able to modify its elements
    vector<shared_ptr<int>> myVector_;
};

int main(){
    auto testobject = MyClass(1,2);
    for (auto my_protected_data : testobject.readMyVector()){
        cout<<(*my_protected_data)<<endl;
        (*my_protected_data) = 25;
        cout<<(*my_protected_data)<<endl; // Should not happen
    }
    return 0;
}

Body:
If you want to make your getter to return vector of shared pointers to const data, there is only one way, to return copy of shared pointers to const data.

const vector<shared_ptr<const int>> readMyVector() const
{
   vector<shared_ptr<const int>> cdata(myVector_.begin(), myVector_.end());
   return cdata;
}


问:
Read/write XML with C#/.NET
What are the best functions, practices, and/or techniques to read/write XML with C#/.NET?</p>

答:
There are classes to read XML:

XmlDocument is slow and memory-intensive: it parses the XML and loads it into an in-RAM DOM, which is good if you want to edit it.

XmlReader is less memory-intensive: it scans the XML from front to back, never needing to keep all of it in RAM at once.

Similarly, for writing you can construct an XmlDocument and then save it, or use an XmlWriter.

After I wrote the above, there's now a new set of APIs which are easier to use: i.e. for example the XDocument and XElement classes.

Title: Read/write XML with C#/.NET

OwnerDisplayName: ChrisW


问:
how to store recent data?
I am using tabbarviewcontroller and i am doing some operations on 3 out of 5 view controllers and i want to store data from every controller when ever i did something and i want to display the stored information in 4th view controller using tableview
(example : like recent dialed list in iphone native phone app )

what is the best method to achieve it ?

thanks for help

regards

答:
Store globally in appDelegate

```<code>yourAppDelegate *appObj=(yourAppDelegate *)[[UIApplication sharedApplication]delegate];
appObj.anyObjectWhichYouDeclaredInAppDelegate = Something;
</code>```

You can assign or retrieve the object in whichever viewcontroller you want by using the above code.

ContentLicense: CC BY-SA 2.5

Title: how to store recent data?

Body:
Store globally in appDelegate

yourAppDelegate *appObj=(yourAppDelegate *)[[UIApplication sharedApplication]delegate];
appObj.anyObjectWhichYouDeclaredInAppDelegate = Something;

You can assign or retrieve the object in whichever viewcontroller you want by using the above code.


问:
WHat Can I do ? During Installing MSSQl server 2014 brings message . An error was encountered. The system cannot read from the specified device
WHat Can I do ? During Installing Microsoft SQl server 2014 express brings message . An error was encountered. The system cannot read from the specified device</p>

答:
I think you should try to read this questions and try the answers:
Installing SQL Server 2012 error "The system cannot open the device or file specified."</p>


问:
Error in Math.random() for arrayList
I'm sure this is a small, stupid error that I just can't see.

I'm getting a compiling error in this code:

```<code>private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }
</code>```

in my length.

Compiling error is:

"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList  "

How can I fix this?  I do want to use Math.random();

Also not sure if this makes a difference, but this is is being done within a String method.

Thanks in advance!

答: if cities is of type ArrayList you have to use cities.size() instead of cities.length.

Title: Error in Math.random() for arrayList

Body:
I'm sure this is a small, stupid error that I just can't see.

I'm getting a compiling error in this code:

private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }

in my length.

Compiling error is:

"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList  "

How can I fix this?  I do want to use Math.random();

Also not sure if this makes a difference, but this is is being done within a String method.

Thanks in advance!


问:
Angular queryParams Subscription does not fire (checkbox for check all)
So I have an application where you can select between several regions that you want to display data from. Above the checkboxes of those regions I added a main checkbox "AllRegions" which obv. selects/unselects all other checkboxes.
This works fine, the parameters are posted to the url and all that.

The only problem I have is when I check/uncheck the "AllRegions" checkbox my component does not react to the subscription of parameter change. It works when unchecking single regions, but not with this "AllRegions" even though I call the same function.

Component:

```<code>        ngOnInit() {
            this.route.queryParams.subscribe(params => {
            this.loadRegionData();
            })
        }
</code>```

This code is called when I click the checkbox.

```<code>this.router.navigateByUrl(this.router.createUrlTree([url], { queryParams: { regions: regionParameters } }));
</code>```

Why is the subscription in ngOnInit not fired when I navigateByUrl?

答:
If the getSelectedRegions returns an Observable, it will not be triggered because you arent subscribing to it (internal observable). I would recommend you to refactor into the following (asuming route is of type ActivatedRoute):

```<code>ngOnInit() {
        this.route.queryParams
        .switchMap(params => this.regionsService.getSelectedRegions())
        .subscribe(
         //handle *data* and *error*
        );
    }
</code>```

Body:
So I have an application where you can select between several regions that you want to display data from. Above the checkboxes of those regions I added a main checkbox "AllRegions" which obv. selects/unselects all other checkboxes.
This works fine, the parameters are posted to the url and all that.

The only problem I have is when I check/uncheck the "AllRegions" checkbox my component does not react to the subscription of parameter change. It works when unchecking single regions, but not with this "AllRegions" even though I call the same function.

Component:

        ngOnInit() {
            this.route.queryParams.subscribe(params => {
            this.loadRegionData();
            })
        }

This code is called when I click the checkbox.

this.router.navigateByUrl(this.router.createUrlTree([url], { queryParams: { regions: regionParameters } }));

Why is the subscription in ngOnInit not fired when I navigateByUrl?

Body:
If the getSelectedRegions returns an Observable, it will not be triggered because you arent subscribing to it (internal observable). I would recommend you to refactor into the following (asuming route is of type ActivatedRoute):

ngOnInit() {
        this.route.queryParams
        .switchMap(params => this.regionsService.getSelectedRegions())
        .subscribe(
         //handle *data* and *error*
        );
    }


答:
The correct type to return is std::vector<std::shared_ptr<const int>>, but you'll have to make that vector by hand. std::shared_ptr<T> is convertible to std::shared_ptr<const T>, but the problem is that std::vector<T> isn't implicitly convertible to std::vector simply because T is convertible to U.

The easiest way is to construct a vector from your internal vector's begin and end iterators.

```<code>vector<shared_ptr<const int>> readMyVector() const
{
    return{ myVector_.begin(), myVector_.end() };
}
</code>```

Note that adding const to the return type of a function that returns by value is rarely useful.

You should also ask yourself rather it's worth it to copy all of those std::shared_ptr. You may want to consider simply returning a vector of int.

Title: How to write a getter for a container of shared_ptrs which does not allow modification of data

Body:
The correct type to return is std::vector<std::shared_ptr<const int>>, but you'll have to make that vector by hand. std::shared_ptr<T> is convertible to std::shared_ptr<const T>, but the problem is that std::vector<T> isn't implicitly convertible to std::vector<U> simply because T is convertible to U.

The easiest way is to construct a vector from your internal vector's begin and end iterators.

vector<shared_ptr<const int>> readMyVector() const
{
    return{ myVector_.begin(), myVector_.end() };
}

Note that adding const to the return type of a function that returns by value is rarely useful.

You should also ask yourself rather it's worth it to copy all of those std::shared_ptr. You may want to consider simply returning a vector of int.


问:
jQuery: Convert every four LI into one
I'm working on a slider, where I want to convert every four LI into one LI.

The slider shows a LI with four elements at the time. I want the content to be SPANs contained in a LI.

From: (one SPAN per LI)

```<code><li><span>#Content</span></li>
<li><span>#Content</span></li>
<li><span>#Content</span></li>
<li><span>#Content</span></li>
<li><span>#Content</span></li>
<li><span>#Content</span></li>
</code>```

...into:  (four SPAN per LI)

```<code><li><span>#Content</span><span>#Content</span><span>#Content</span><span>#Content</span></li>
<li><span>#Content</span><span>#Content</span></li>
</code>```

I can't seem to find any information on the Internet, about this technique. What should I do?

Does it make any sense? Sorry about my poor English...

答:
You can loop through with .slice() and .wrapAll() like this:

```<code>var spans = $("li span").unwrap();
for(var i = 0; i < spans.length; i+=4) {
  spans.slice(i, i+4).wrapAll("<li />");
}
</code>```

You can test it out here.  What this does is .unwrap() to remove the initial
 wrappers, then looping through insets of 4, uses .slice() to get the set we're working with (it'll properly handle the last 4 or less) and use .wrapAll() on those  elements to put them in a new
.

Title: jQuery: Convert every four LI into one

Body:
I'm working on a slider, where I want to convert every four LI into one LI.

The slider shows a LI with four elements at the time. I want the content to be SPANs contained in a LI.

From: (one SPAN per LI)

#Content

#Content

#Content

#Content

#Content

#Content

...into:  (four SPAN per LI)

#Content#Content#Content#Content

#Content#Content

I can't seem to find any information on the Internet, about this technique. What should I do?

Does it make any sense? Sorry about my poor English...

Body:
You can loop through with .slice() and .wrapAll() like this:

var spans = $("li span").unwrap();
for(var i = 0; i < spans.length; i+=4) {
  spans.slice(i, i+4).wrapAll("<li />");
}

You can test it out here.  What this does is .unwrap() to remove the initial <li> wrappers, then looping through insets of 4, uses .slice() to get the set we're working with (it'll properly handle the last 4 or less) and use .wrapAll() on those <span> elements to put them in a new <li>.


问:
Meteorjs dynamically create fields in collection
I have a companies collection that has three companies(at the moment). There is also a second collection called campaigns. Each campaign belongs to a company. Each campaign has different fields depending on what company it is. Because mongodb is schemaless does that mean that I can add whatever fields I want to the collection. Like if I created a template form for each company could I save whatever template was selected.</p>

答:
Short answer

Yes.

Longer answer

While MongoDB does not enforce a schema (save for the required _id field), it is good to have at least some schema to your documents. If you store extremely different documents in a single collection, it can make it very challenging to handle all the different document forms in your code. This usually makes development much harder.

Typically companies have common data associated with them, so you will still have a common schema between them. But each company can expand upon that base schema. Just be sure to appropriately handle all of the potential null values for fields in your code.


问:
unable to redirect to a custom action in devise registrations controller
Excuse me for the noob question.

I have a devise users model and i want to save additional data to the users model after a user signs_in/signs_up.

routes.rb

```<code>     devise_for :users,
        path: '',
        path_names: {sign_in: 'login', sign_out: 'logout',sign_up: 'signup'},
        controllers: { registrations: 'registrations

        devise_scope :user do
             match 'users/customer' => 'registrations#customer', :via => [:get], :as => 'customer'
             match 'users/theme-selector' => 'registrations#theme_selector', :via => [:get], :as => 'theme-selector'
        end
</code>```

registrations_controller.rb

```<code>   class RegistrationsController < Devise::RegistrationsController

    protect_from_forgery :except => :create

      def customer
      @user = current_user

    if @user
       render :customer
     # render :customer
     # redirect_to controller: 'registations', action: 'theme_selector'

        else
            render file: 'public/404', status: 404, formats: [:html]
         end

  end

    def theme_selector
         @user = current_user
            if @user
                render :theme_selector
            else
                render file: 'public/404', status: 404, formats: [:html]
             end

       end

       end
      end
</code>```

customer.html.erb

```<code> <div class="container huge-top small-bottom"">
  <div class="row large-top">
    <div class="col-md-8">
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f|  %>

 <div class="form-group">
    <%= f.label :"Contact Person" %>
    <%= f.text_field :contact, class:"form-control" %>
  </div>
  <div class="form-group">
    <%= f.label :"Business Name" %>
    <%= f.text_field :name, class:"form-control" %>
  </div>
  <div class="form-group">
    <%= f.label :phone %>
    <%= f.text_field :phone, class:"form-control" %>
  </div>
   <div class="form-group">
    <%= f.label :email %>
    <%= f.text_field :email, class:"form-control", required: true %>
  </div>
  <div class="form-group">
    <%= f.label :"Mailing Address" %>
    <%= f.text_field :address, class:"form-control" %>
  </div>
   <div class="form-group">
    <%= f.label :"Do you currently have a domain?" %>
    <%= f.text_area :domain, class:"form-control" %>
  </div>
   <div class="col-md-5">
   <!--%= f.submit '+', :name => "add_additional_fields" %-->
    <span><%= f.submit 'Save', class: "btn btn-success" %></span>
<span><!--%= link_to 'Back', customers_path, class: "btn btn-danger" %--></span>
  </div>

  </div>
  </div>
  <% end %>
</code>```

The steps are:

1.A user signs_up or sign_in.

2.The user then selects customer button which renders customer.html.erb

3.After submitting the customer form ,then it has to redirect to theme_selector page to select a certain theme.

I could update the users model by submitting the data inside the customer.html.erb form .now I want to redirect to the theme_selector page and then pass in the theme_id to the users model.If i use redirect_to controller: 'registations', action: 'theme_selector' in the customer action , it is skipping customer form and rendering theme_selector page.How can I make it to redirect to theme_selector after the customer form.

theme_selector.html.erb

```<code>  <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f|  %>
   <div class="row">
   <div class="col-md-4 col-sm-4 top-space">
      <!-- thumbnail-->
      <div class="thumbnail image-height">
        <a href="http://theme1./" target="_blank">
          <div class="hovereffect">
            <img src="/assets/1.jpg" class="img-responsive theme" alt="">

              <div class="price-sale"><img src="/assets/new.png"></div>

          </div>
          <div class="caption">
            <h4>Click Here</h4>
            <!--p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere, soluta, eligendi doloribus sunt minus amet sit debitis repellat. Consectetur, culpa itaque odio similique suscipit</p-->
            <p><button class="btn-update" role="button">View</button></p>
          </div>
        </a>
      </div>
      <div><%= f.radio_button :theme_id, 'theme-1' %> </div>
    <!-- thumbnail end -->
    </div>
    <div class="col-md-4 col-sm-4 top-space">
      <!-- thumbnail-->
      <div class="thumbnail image-height">
        <a href="http://theme2/" target="_blank">
          <div class="hovereffect">
            <img src="/assets/2.jpg" class="img-responsive theme" alt="">

              <div class="price-sale"><img src="/assets/new.png"></div>

          </div>
          <div class="caption">
            <h4>Click Here</h4>
            <!--p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere, soluta, eligendi doloribus sunt minus amet sit debitis repellat. Consectetur, culpa itaque odio similique suscipit</p-->
            <p><button class="btn-update" role="button">View</button></p>
          </div>
        </a>
      </div>
      <div><%= f.radio_button :theme_id, 'theme-1' %> </div>
    <!-- thumbnail end -->
    </div>
     <div class="row">
 <div class="col-md-12 top-space"><%= f.submit 'Submit', class: "btn-addmore" %></div>
 </div>
 <% end %>
</code>```

Any Help or suggestion is highly Appreciated. Thanks in Advance.

答:
Easy solution will be:

In your config/routes.rb

```<code>devise_for :users,
    path: '',
    path_names: {sign_in: 'login', sign_out: 'logout',sign_up: 'signup'},
    controllers: { registrations: 'registrations}

    devise_scope :user do
        get 'users/theme-selector' => 'registrations#theme_selector', :as => 'theme-selector'
</code>```

In your registrations_controller.rb

```<code>class RegistrationsController < Devise::RegistrationsController
  protected

  def after_sign_up_path_for(resource)
    'users/theme-selector'
  end
end
</code>```

Body:
Excuse me for the noob question.

I have a devise users model and i want to save additional data to the users model after a user signs_in/signs_up.

routes.rb

     devise_for :users,
        path: '',
        path_names: {sign_in: 'login', sign_out: 'logout',sign_up: 'signup'},
        controllers: { registrations: 'registrations

        devise_scope :user do
             match 'users/customer' => 'registrations#customer', :via => [:get], :as => 'customer'
             match 'users/theme-selector' => 'registrations#theme_selector', :via => [:get], :as => 'theme-selector'
        end

registrations_controller.rb

   class RegistrationsController < Devise::RegistrationsController

    protect_from_forgery :except => :create

      def customer
      @user = current_user

    if @user
       render :customer
     # render :customer
     # redirect_to controller: 'registations', action: 'theme_selector'

        else
            render file: 'public/404', status: 404, formats: [:html]
         end

  end

    def theme_selector
         @user = current_user
            if @user
                render :theme_selector
            else
                render file: 'public/404', status: 404, formats: [:html]
             end

       end

       end
      end

customer.html.erb

    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f|  %>

    <%= f.label :"Contact Person" %>
    <%= f.text_field :contact, class:"form-control" %>

    <%= f.label :"Business Name" %>
    <%= f.text_field :name, class:"form-control" %>

    <%= f.label :phone %>
    <%= f.text_field :phone, class:"form-control" %>

    <%= f.label :email %>
    <%= f.text_field :email, class:"form-control", required: true %>

    <%= f.label :"Mailing Address" %>
    <%= f.text_field :address, class:"form-control" %>

    <%= f.label :"Do you currently have a domain?" %>
    <%= f.text_area :domain, class:"form-control" %>

    <%= f.submit 'Save', class: "btn btn-success" %>

  <% end %>

The steps are:

1.A user signs_up or sign_in.

2.The user then selects customer button which renders customer.html.erb

3.After submitting the customer form ,then it has to redirect to theme_selector page to select a certain theme.

I could update the users model by submitting the data inside the customer.html.erb form .now I want to redirect to the theme_selector page and then pass in the theme_id to the users model.If i use redirect_to controller: 'registations', action: 'theme_selector' in the customer action , it is skipping customer form and rendering theme_selector page.How can I make it to redirect to theme_selector after the customer form.

theme_selector.html.erb

  <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f|  %>

Click Here

<button class="btn-update" role="button">View</button>

<%= f.radio_button :theme_id, 'theme-1' %>

Click Here

<button class="btn-update" role="button">View</button>

<%= f.radio_button :theme_id, 'theme-1' %>

<%= f.submit 'Submit', class: "btn-addmore" %>

 <% end %>

Any Help or suggestion is highly Appreciated. Thanks in Advance.

Body:
Easy solution will be:

In your config/routes.rb

devise_for :users,
    path: '',
    path_names: {sign_in: 'login', sign_out: 'logout',sign_up: 'signup'},
    controllers: { registrations: 'registrations}

    devise_scope :user do
        get 'users/theme-selector' => 'registrations#theme_selector', :as => 'theme-selector'

In your registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  protected

  def after_sign_up_path_for(resource)
    'users/theme-selector'
  end
end


问:
Rails - where to put model helper methods
I want to hide certain implementations from the main Model methods, because of clean code reasons. I don't want my Model to contain a lot of huge methods, only the clearest and verbose functionalities.

For example:

```<code>class SomeModel
  #included stuff
  #fields & attrs

  def modelMethod
      variable = functionality1(functionality2)
      if some condition
        functionality3
      else
        functionality4
      end
  end
</code>```

Should I put my functionality methods under a private or protected part at the end of the same model file, or should I put them into a helper file?

If I'm right, the codes in the helpers are only used for the View. What is the convention for this?

答:
Having private or protected has nothing to do with the type of cleanup you're trying to do.

This is related to inheritance method visibility/access (though inheritance can obviously be used for reusability).

Methods will depends on reusability. Why not leverage concerns? Say we have SomeModel and want multiple models to implement suspensions.

```<code># app/models/some_model.rb
class SomeModel
  include Suspendable
end
</code>```

Then add your model concern.

```<code># app/models/concerns/suspendable.rb
module Suspendable
  extend ActiveSupport::Concern

  included do
    has_one :suspension
    scope :active, -> { joins('LEFT OUTER JOIN suspensions').where(suspension: {id: nil} }
  end
end
</code>```

Or if this only really applies to a single model, but want to keep the model strictly DB manipulations (not Business oriented), then you could have namespaced concerns.

```<code># app/models/concerns/some_model/availability.rb
module SomeModel::Availability
  extend ActiveSupport::Concern

  module ClassMethods
    def availabilities_by_some_logic
    end
  end
end
</code>```

http://api.rubyonrails.org/v5.0/classes/ActiveSupport/Concern.html

Body:
I want to hide certain implementations from the main Model methods, because of clean code reasons. I don't want my Model to contain a lot of huge methods, only the clearest and verbose functionalities.

For example:

class SomeModel
  #included stuff
  #fields & attrs

  def modelMethod
      variable = functionality1(functionality2)
      if some condition
        functionality3
      else
        functionality4
      end
  end

Should I put my functionality methods under a private or protected part at the end of the same model file, or should I put them into a helper file?

If I'm right, the codes in the helpers are only used for the View. What is the convention for this?

Body:
Having private or protected has nothing to do with the type of cleanup you're trying to do.

This is related to inheritance method visibility/access (though inheritance can obviously be used for reusability).

Methods will depends on reusability. Why not leverage concerns? Say we have SomeModel and want multiple models to implement suspensions.

# app/models/some_model.rb
class SomeModel
  include Suspendable
end

Then add your model concern.

# app/models/concerns/suspendable.rb
module Suspendable
  extend ActiveSupport::Concern

  included do
    has_one :suspension
    scope :active, -> { joins('LEFT OUTER JOIN suspensions').where(suspension: {id: nil} }
  end
end

Or if this only really applies to a single model, but want to keep the model strictly DB manipulations (not Business oriented), then you could have namespaced concerns.

# app/models/concerns/some_model/availability.rb
module SomeModel::Availability
  extend ActiveSupport::Concern

  module ClassMethods
    def availabilities_by_some_logic
    end
  end
end

http://api.rubyonrails.org/v5.0/classes/ActiveSupport/Concern.html


问:
Are chrome alarms fired if the browser is closed?
Do chrome alarms fire if the browser gets closed before the time it was supposed to fire? If it is called, is it called when the browser reopens next?</p>

答:
If you set an alarm and close the browser, the alarm will fire immediately when you reopen the browser if the time for the alarm has expired.

If this is not what you want, you can try to put a session id with the alarm and then check on startup if the session id of the alarm matches with the current session, if it does not match then just skip over the code.


问:
how can i achieve FibonacciSecret in php
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>
</code>```

Output

```<code>h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-
</code>```

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

答:
Recursive version and wrapped in a function, string length should be irrilevant:</p>

```<code>function fiboSecret($msg, $num = 0, $fib = [], $secret = []){
  if(count($fib) > 0) {
    if($num == 1){
      if(strlen($msg) > 1){
        $secret[] = strtoupper($msg[1]);
        return fiboSecret($msg, ++$num, array(0, 1), $secret);
      }else{
        return $secret;
      }
    }
    $lastFibo = $fib[count($fib) - 1];
    if(array_key_exists($lastFibo, str_split($msg))){
      $secret[] = strtoupper($msg[$lastFibo]);
      $fib[] = $fib[$num-1] + $fib[$num-2];
      return fiboSecret($msg, ++$num, $fib, $secret);
    }else{
      return $secret;
    }
  }else if(strlen($msg) > 0){
    $msg = preg_replace('/\s+/', '', $msg);
    $secret[] = strtoupper($msg[0]);
    return fiboSecret($msg, ++$num, array(0), $secret);
  }else{
    return [];
  }
  if(array_key_exists($lastFibo, str_split($msg))){
    $secret[] = strtoupper($msg[$lastFibo]);
    $num++;
  }
}
</code>```

Body:
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>

Output

h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

Body:
Recursive version and wrapped in a function, string length should be irrilevant:

function fiboSecret($msg, $num = 0, $fib = [], $secret = []){
  if(count($fib) > 0) {
    if($num == 1){
      if(strlen($msg) > 1){
        $secret[] = strtoupper($msg[1]);
        return fiboSecret($msg, ++$num, array(0, 1), $secret);
      }else{
        return $secret;
      }
    }
    $lastFibo = $fib[count($fib) - 1];
    if(array_key_exists($lastFibo, str_split($msg))){
      $secret[] = strtoupper($msg[$lastFibo]);
      $fib[] = $fib[$num-1] + $fib[$num-2];
      return fiboSecret($msg, ++$num, $fib, $secret);
    }else{
      return $secret;
    }
  }else if(strlen($msg) > 0){
    $msg = preg_replace('/\s+/', '', $msg);
    $secret[] = strtoupper($msg[0]);
    return fiboSecret($msg, ++$num, array(0), $secret);
  }else{
    return [];
  }
  if(array_key_exists($lastFibo, str_split($msg))){
    $secret[] = strtoupper($msg[$lastFibo]);
    $num++;
  }
}


问:
Is @$array['possibly_missing_key'] an anti-pattern?
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

```<code>$value = @$array['possibly_missing_key'];
</code>```

The intended behavior:

```<code>if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}
</code>```

I want to know, before spreading the usage pattern.

答:
Or</p>

```<code>$value = (isset($array['possibly_missing_key'])) ? $array['possibly_missing_key']: null;
</code>```

Body:
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

$value = @$array['possibly_missing_key'];

The intended behavior:

if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}

I want to know, before spreading the usage pattern.

Body:
Or

$value = (isset($array['possibly_missing_key'])) ? $array['possibly_missing_key']: null;


问:
how can I store my data in a global variable?
```<code>$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});
</code>```

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.

答:
you can use var at global scope (outside of all functions) to declare a global variable:</p>

```<code><script>

var astronautsData;
$(function(){

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

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

Body:
$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.

Body:
you can use var at global scope (outside of all functions) to declare a global variable:

<script>

var astronautsData;
$(function(){

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});
</script>


问:
Get String value from JSON document

valeurs_d = "";
for (var i = 0; i < keys.length -1 ; i++)
valeurs_d += + event[keys[i]] + ", ";
var str5 = ",";
var str6 = str5.concat(valeurs_d);
var valeurs = str6.substring (0, str6.length - 2);
console.log(valeurs);```
</div>
</div>
</p>

<p>I have a json document like this :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> {
  "temperature" : 12.45,
  "lala" : 45.75,
  "humidite" : 45.78,
  "toto" : "gvvgvh",
  "topic" : "sk1_001/data"
 }</code>```

The problem when I retrieve the values. I have the following result: 12.45, 45.75, 45.78, NaN!

I want to retrieve my string instead of NaN, How ?

edit : Thank you, it's donne, but I hava annoter question :

Typeof in Javascript returns number or string, or I want to return varchar for string, and double for number.

I need this to write on my Apache Cassandra database in node.js.

How can I proceed to return varchar and double ?

答:
If you want all values in a string with comma delimited, try code as following</p>

```<code>var obj = {
 "temperature" : 12.45,
 "lala" : 45.75,
 "humidite" : 45.78,
 "toto" : "gvvgvh",
 "topic" : "sk1_001/data"
 };

var a = [];
for(var k in obj){
  a.push(obj[k].toString());
}
var result = a.join(",");
console.log(result);
</code>```

Title: Get String value from JSON document

Body:
valeurs_d = "";
for (var i = 0; i < keys.length -1 ; i++)
valeurs_d += + event[keys[i]] + ", ";
var str5 = ",";
var str6 = str5.concat(valeurs_d);
var valeurs = str6.substring (0, str6.length - 2);
console.log(valeurs);

I have a json document like this :

 {
  "temperature" : 12.45,
  "lala" : 45.75,
  "humidite" : 45.78,
  "toto" : "gvvgvh",
  "topic" : "sk1_001/data"
 }

The problem when I retrieve the values. I have the following result: 12.45, 45.75, 45.78, NaN!

I want to retrieve my string instead of NaN, How ?

edit : Thank you, it's donne, but I hava annoter question :

Typeof in Javascript returns number or string, or I want to return varchar for string, and double for number.

I need this to write on my Apache Cassandra database in node.js.

How can I proceed to return varchar and double ?

Body:
If you want all values in a string with comma delimited, try code as following

var obj = {
 "temperature" : 12.45,
 "lala" : 45.75,
 "humidite" : 45.78,
 "toto" : "gvvgvh",
 "topic" : "sk1_001/data"
 };

var a = [];
for(var k in obj){
  a.push(obj[k].toString());
}
var result = a.join(",");
console.log(result);


问:
How do I check if a page or node (IPublishedContent) uses a specific inherited document type?
I have a document type Page which inherits from a parent document type Page Base.

On a rendered page, I can see if the document type is equal to the Page document type alias:

```<code>// Where Model is type Umbraco.Web.Models.RenderModel.
if (Model.Content.DocumentTypeAlias == "page")
{
    // My current page uses the "page" document type.
}
</code>```

But how can I check to see if my IPublishedContent inherits from Page Base?

答:
Turns out there is a method for this on the IPublishedContent type:

```<code>// Where Model is type Umbraco.Web.Models.RenderModel.
if (Model.Content.IsDocumentType("pageBase", true))
{
    // My current page uses the "pageBase" document type.
}
</code>```

The overload on .IsDocumentType() which accepts a boolean is called recursive and it checks to see if your IPublishedContent either is the supplied document type, or is derived from that document type.

Update: However!!

There is a bug using recursive .IsDocumentType() if your document types are stored in folders. This issue has been logged here.

Instead, you can use .IsComposedOf():

```<code>// Where Model is type Umbraco.Web.Models.RenderModel.
if (Model.Content.IsComposedOf("pageBase"))
{
    // My current page uses the "pageBase" document type.
}
</code>```

This method both checks document type compositions and inheritance.

This method differs from recursive .IsDocumentType() because it only checks inheritance/compositions, not if the current doc type is the provided alias.

Body:
I have a document type Page which inherits from a parent document type Page Base.

On a rendered page, I can see if the document type is equal to the Page document type alias:

// Where Model is type Umbraco.Web.Models.RenderModel.
if (Model.Content.DocumentTypeAlias == "page")
{
    // My current page uses the "page" document type.
}

But how can I check to see if my IPublishedContent inherits from Page Base?

Body:
Turns out there is a method for this on the IPublishedContent type:

// Where Model is type Umbraco.Web.Models.RenderModel.
if (Model.Content.IsDocumentType("pageBase", true))
{
    // My current page uses the "pageBase" document type.
}

The overload on .IsDocumentType() which accepts a boolean is called recursive and it checks to see if your IPublishedContent either is the supplied document type, or is derived from that document type.

Update: However!!

There is a bug using recursive .IsDocumentType() if your document types are stored in folders. This issue has been logged here.

Instead, you can use .IsComposedOf():

// Where Model is type Umbraco.Web.Models.RenderModel.
if (Model.Content.IsComposedOf("pageBase"))
{
    // My current page uses the "pageBase" document type.
}

This method both checks document type compositions and inheritance.

This method differs from recursive .IsDocumentType() because it only checks inheritance/compositions, not if the current doc type is the provided alias.


问:
Pyskark Dataframe: Transforming unique elements in rows to columns
I have a Pyspark Dataframe in the following format:

```<code>+------------+---------+
|    date    |  query  |
+------------+---------+
| 2011-08-11 | Query 1 |
| 2011-08-11 | Query 1 |
| 2011-08-11 | Query 2 |
| 2011-08-12 | Query 3 |
| 2011-08-12 | Query 3 |
| 2011-08-13 | Query 1 |
+------------+---------+
</code>```

And I need to transform it to turn each unique query into a column, grouped by date, and insert the count of each query in the rows of the dataframe. I expect the output to be like this:

```<code>+------------+---------+---------+---------+
|    date    | Query 1 | Query 2 | Query 3 |
+------------+---------+---------+---------+
| 2011-08-11 |       2 |       1 |       0 |
| 2011-08-12 |       0 |       0 |       2 |
| 2011-08-13 |       1 |       0 |       0 |
+------------+---------+---------+---------+
</code>```

I am trying to use this answer as example, but I don't quite understand the code, especially the return statement in the make_row function.

Is there a way to count the queries while transforming the DataFrame?
Maybe something like

```<code>import pyspark.sql.functions as func

grouped = (df
    .map(lambda row: (row.date, (row.query, func.count(row.query)))) # Just an example. Not sure how to do this.
    .groupByKey())
</code>```

It is a dataframe with potentially hundreds of thousands of rows and queries, so I prefer the RDD version over the options that use a .collect()

Thank you!

Body:
I have a Pyspark Dataframe in the following format:

+------------+---------+
|    date    |  query  |
+------------+---------+
| 2011-08-11 | Query 1 |
| 2011-08-11 | Query 1 |
| 2011-08-11 | Query 2 |
| 2011-08-12 | Query 3 |
| 2011-08-12 | Query 3 |
| 2011-08-13 | Query 1 |
+------------+---------+

And I need to transform it to turn each unique query into a column, grouped by date, and insert the count of each query in the rows of the dataframe. I expect the output to be like this:

+------------+---------+---------+---------+
|    date    | Query 1 | Query 2 | Query 3 |
+------------+---------+---------+---------+
| 2011-08-11 |       2 |       1 |       0 |
| 2011-08-12 |       0 |       0 |       2 |
| 2011-08-13 |       1 |       0 |       0 |
+------------+---------+---------+---------+

I am trying to use this answer as example, but I don't quite understand the code, especially the return statement in the make_row function.

Is there a way to count the queries while transforming the DataFrame?
Maybe something like

import pyspark.sql.functions as func

grouped = (df
    .map(lambda row: (row.date, (row.query, func.count(row.query)))) # Just an example. Not sure how to do this.
    .groupByKey())

It is a dataframe with potentially hundreds of thousands of rows and queries, so I prefer the RDD version over the options that use a .collect()

Thank you!

Body:
You can use groupBy.pivot with count as the aggregation function:

from pyspark.sql.functions import count
df.groupBy('date').pivot('query').agg(count('query')).na.fill(0).orderBy('date').show()

+--------------------+-------+-------+-------+
|                date|Query 1|Query 2|Query 3|
+--------------------+-------+-------+-------+
|2011-08-11 00:00:...|      2|      1|      0|
|2011-08-12 00:00:...|      0|      0|      2|
|2011-08-13 00:00:...|      1|      0|      0|
+--------------------+-------+-------+-------+


问:
Any way to auto add a quote mark around a character variable during implode for mysql?
Here it is..

```<code>Foreach ($data as $x) {

$mydata =  implode( ", ", $x);

$sql = "INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`, `user_id`,
`class_id`, `MLS`, `DOM`, `Zip`, `Status`) VALUES($id, 1, 1, $mydata);";

echo "$sql<br>";

$id++;

}
</code>```

Keep in mind this is a simplified example and there will be over 200 fields being imploded for insertion.. so there might be as many as 100+ character variables that will require tick encapsulation so if the implode won't do it then it could get complicated..

```<code>End result of echo the resultant sql..
Line 1:
INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`, `user_id`,
`class_id`, `MLS`, `DOM`, `Zip`, `Status`) VALUES(2, 1, 1, 1475566, 626,
 89005, Sold);
Line 2:
INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`, `user_id`,
`class_id`, `MLS`, `DOM`, `Zip`, `Status`) VALUES(3, 1, 1, 1485995, 492,
89005, 'Sold');
</code>```

PROBLEM:  To use php insert the character variables require that it have a tick on each side of the variable like 'Sold' as you see in line 1 it will not put the tick on implode.. Line 2 is an example of where i manually added the tick.. and it works fine.. Is there anyway to have the implode add the ticks around any character variables... w/o extensive additional programming.

答:
```<code>$xt = array_map(function($x){ return "'$x'";}, $x);
$mydata =  implode( ", ", $xt);
</code>```

Apart from that the code is probably vulnerable to SQL injection.

ContentLicense: CC BY-SA 4.0

Body:
Here it is..

Foreach ($data as $x) {

$mydata =  implode( ", ", $x);

$sql = "INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`, `user_id`,
`class_id`, `MLS`, `DOM`, `Zip`, `Status`) VALUES($id, 1, 1, $mydata);";

echo "$sql
";

$id++;

}

Keep in mind this is a simplified example and there will be over 200 fields being imploded for insertion.. so there might be as many as 100+ character variables that will require tick encapsulation so if the implode won't do it then it could get complicated..

End result of echo the resultant sql..
Line 1:
INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`, `user_id`,
`class_id`, `MLS`, `DOM`, `Zip`, `Status`) VALUES(2, 1, 1, 1475566, 626,
 89005, Sold);
Line 2:
INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`, `user_id`,
`class_id`, `MLS`, `DOM`, `Zip`, `Status`) VALUES(3, 1, 1, 1485995, 492,
89005, 'Sold');

PROBLEM:  To use php insert the character variables require that it have a tick on each side of the variable like 'Sold' as you see in line 1 it will not put the tick on implode.. Line 2 is an example of where i manually added the tick.. and it works fine.. Is there anyway to have the implode add the ticks around any character variables... w/o extensive additional programming.

Body:
$xt = array_map(function($x){ return "'$x'";}, $x);
$mydata =  implode( ", ", $xt);

Apart from that the code is probably vulnerable to SQL injection.


问:
How to get value of 2 different radio box and set it to specific place using loop/each?

$(document).ready(function() {

  $('.allrb').change(function() {
    valueE();
  });

});

function valueE()
{
  for(j=0; j<=2 ; j++)
  {
    var nofr1=[];
    row=document.getElementsByName("Fr"+j);
      for (i=0; i<row.length; i++)
      {
        if(row[i].checked)
          nofr1[i]= parseInt(row.value);
      }
    $("#numFr"+(j+1)).val(nofr1[j]);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover table-responsive" id="tab">
<tr id="alertr1" name="v">
  <td width="200px" id="text">content 1</td>
  <td width="40px"><label><input type="radio" name="Fr1" class="allrb" value="0"></label></td>
  <td width="40px"><label><input type="radio" name="Fr1" class="allrb" value="1"></label></td>
  <td width="40px"><label><input type="radio" name="Fr1" class="allrb" value="2"></label></td>
  <td width="40px"><label><input type="radio" name="Fr1" class="allrb" value="3"></label></td>
  <td width="30px"><label><input type="radio" name="Fr1" class="allrb" value="4"></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="0" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="1" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="2" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="3" ></label></td>
  <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="4" ></label></td>
  <td width="30px"><input type="number" name="numFr1" id="numFr1" disabled></td>
  <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr1" id="numIr1" disabled></td>
</tr>

<tr id="alertr2" name="v">
  <td width="200px" id="text">content 2</td>
  <td width="40px"><label><input type="radio" name="Fr2" class="allrb" value="0"></label></td>
  <td width="40px"><label><input type="radio" name="Fr2" class="allrb" value="1"></label></td>
  <td width="40px"><label><input type="radio" name="Fr2" class="allrb" value="2"></label></td>
  <td width="40px"><label><input type="radio" name="Fr2" class="allrb" value="3"></label></td>
  <td width="30px"><label><input type="radio" name="Fr2" class="allrb" value="4"></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="0" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="1" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="2" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="3" ></label></td>
  <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="4" ></label></td>
  <td width="30px"><input type="number" name="numFr2" id="numFr2" disabled></td>
  <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr2" id="numIr2" disabled></td>
</tr>

<tr id="alertr3" name="v">
  <td width="200px" id="text">content 3</td>
  <td width="40px"><label><input type="radio" name="Fr3" class="allrb" value="0"></label></td>
  <td width="40px"><label><input type="radio" name="Fr3" class="allrb" value="1"></label></td>
  <td width="40px"><label><input type="radio" name="Fr3" class="allrb" value="2"></label></td>
  <td width="40px"><label><input type="radio" name="Fr3" class="allrb" value="3"></label></td>
  <td width="30px"><label><input type="radio" name="Fr3" class="allrb" value="4"></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="0" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="1" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="2" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="3" ></label></td>
  <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="4" ></label></td>
  <td width="30px"><input type="number" name="numFr3" id="numFr3" disabled></td>
  <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr3" id="numIr3" disabled></td>
</tr>

</tbody>
</table></code>```

In a row, I have 2 different radio box, how to I get the value of all of the radio box and set the value in the specific input[type=number] there? Since I had 16 row and each row had 2 different value box, I would like to use loop to loop all the value into specific place, else there will be many redundant code. I had try to do it, but my jquery won't work. Thanks.

答:
The element that is changed can be referenced on the event.  If you give the input you want to update a common class, you can find the one that is related to your radios by finding the radios parent tr, and finding that class within.

$(document).ready(function() {
  $('.allrb').change(valueE);
});

function valueE(e) {
  var newValue = e.target.value;
  var $radio = $(e.target);

  if ($radio.is('.Fr')) {
    $radio.closest('tr').find('.numFr').val(newValue);
  } else {
    $radio.closest('tr').find('.numIr').val(newValue);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover table-responsive" id="tab">
  <tr id="alertr1" name="v">
    <td width="200px" id="text">content 1</td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr1" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr1" class="numFr" id="numFr1" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr1" class="numIr" id="numIr1" disabled></td>
  </tr>

  <tr id="alertr2" name="v">
    <td width="200px" id="text">content 2</td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr2" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr2" class="numFr" id="numFr2" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr2" class="numIr" id="numIr2" disabled></td>
  </tr>

  <tr id="alertr3" name="v">
    <td width="200px" id="text">content 3</td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr3" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir Ir3" class="allrb" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr2" class="numFr" id="numFr2" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr3" class="numIr" id="numIr3" disabled></td>
  </tr>

  </tbody>
</table></code>```

Body:
$(document).ready(function() {

  $('.allrb').change(function() {
    valueE();
  });

});

function valueE()
{
  for(j=0; j<=2 ; j++)
  {
    var nofr1=[];
    row=document.getElementsByName("Fr"+j);
      for (i=0; i<row.length; i++)
      {
        if(row[i].checked)
          nofr1[i]= parseInt(row.value);
      }
    $("#numFr"+(j+1)).val(nofr1[j]);
  }
}

  content 1
  <input type="radio" name="Fr1" class="allrb" value="0">
  <input type="radio" name="Fr1" class="allrb" value="1">
  <input type="radio" name="Fr1" class="allrb" value="2">
  <input type="radio" name="Fr1" class="allrb" value="3">
  <input type="radio" name="Fr1" class="allrb" value="4">
  <input type="radio" name="Ir1" class="allrb" value="0" >
  <input type="radio" name="Ir1" class="allrb" value="1" >
  <input type="radio" name="Ir1" class="allrb" value="2" >
  <input type="radio" name="Ir1" class="allrb" value="3" >
  <input type="radio" name="Ir1" class="allrb" value="4" >
  <input type="number" name="numFr1" id="numFr1" disabled>
  <input type="number" name="numIr1" id="numIr1" disabled>

  content 2
  <input type="radio" name="Fr2" class="allrb" value="0">
  <input type="radio" name="Fr2" class="allrb" value="1">
  <input type="radio" name="Fr2" class="allrb" value="2">
  <input type="radio" name="Fr2" class="allrb" value="3">
  <input type="radio" name="Fr2" class="allrb" value="4">
  <input type="radio" name="Ir2" class="allrb" value="0" >
  <input type="radio" name="Ir2" class="allrb" value="1" >
  <input type="radio" name="Ir2" class="allrb" value="2" >
  <input type="radio" name="Ir2" class="allrb" value="3" >
  <input type="radio" name="Ir2" class="allrb" value="4" >
  <input type="number" name="numFr2" id="numFr2" disabled>
  <input type="number" name="numIr2" id="numIr2" disabled>

  content 3
  <input type="radio" name="Fr3" class="allrb" value="0">
  <input type="radio" name="Fr3" class="allrb" value="1">
  <input type="radio" name="Fr3" class="allrb" value="2">
  <input type="radio" name="Fr3" class="allrb" value="3">
  <input type="radio" name="Fr3" class="allrb" value="4">
  <input type="radio" name="Ir3" class="allrb" value="0" >
  <input type="radio" name="Ir3" class="allrb" value="1" >
  <input type="radio" name="Ir3" class="allrb" value="2" >
  <input type="radio" name="Ir3" class="allrb" value="3" >
  <input type="radio" name="Ir3" class="allrb" value="4" >
  <input type="number" name="numFr3" id="numFr3" disabled>
  <input type="number" name="numIr3" id="numIr3" disabled>

In a row, I have 2 different radio box, how to I get the value of all of the radio box and set the value in the specific input[type=number] there? Since I had 16 row and each row had 2 different value box, I would like to use loop to loop all the value into specific place, else there will be many redundant code. I had try to do it, but my jquery won't work. Thanks.

Body:
The element that is changed can be referenced on the event.  If you give the input you want to update a common class, you can find the one that is related to your radios by finding the radios parent tr, and finding that class within.

$(document).ready(function() {
  $('.allrb').change(valueE);
});

function valueE(e) {
  var newValue = e.target.value;
  var $radio = $(e.target);

  if ($radio.is('.Fr')) {
    $radio.closest('tr').find('.numFr').val(newValue);
  } else {
    $radio.closest('tr').find('.numIr').val(newValue);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover table-responsive" id="tab">
  <tr id="alertr1" name="v">
    <td width="200px" id="text">content 1</td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr1" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr1" class="numFr" id="numFr1" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr1" class="numIr" id="numIr1" disabled></td>
  </tr>

  <tr id="alertr2" name="v">
    <td width="200px" id="text">content 2</td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr2" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr2" class="numFr" id="numFr2" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr2" class="numIr" id="numIr2" disabled></td>
  </tr>

  <tr id="alertr3" name="v">
    <td width="200px" id="text">content 3</td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr3" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir Ir3" class="allrb" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr2" class="numFr" id="numFr2" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr3" class="numIr" id="numIr3" disabled></td>
  </tr>

  </tbody>
</table>


问:
If then else and dlookup challenge in Access 2010
Its been a long time since I have used coded in VBA, and I am rusty...

Trying to look at a field, which is populated by a combo box, within a table to see if it is null or not.  Based upon the field having value or not, the code determines which form to open.

[table].field

Form1
Form2

here is what I have attempted to no avail

```<code>If DLookup("[field]", "table", IsNull) Then
        DoCmd.OpenForm "form1", acNormal
        End If
    If DLookup("[field]", "table", NotIsNull) Then
        DoCmd.OpenForm "form2", acNormal
</code>```

I can't get this to run without errors.  Help!

答:
Do you mean you've got a combo-box on a form, the combo-box gets its values from a table.  If the selected value is blank then open one form, if it's got a value open another form?

Based on a two column Combo-Box (column 0 is hidden key value, column 1 holds the value we're after):

```<code>Private Sub Combo0_AfterUpdate()
    With Me.Combo0
        If .Column(1) = "" Then
            DoCmd.OpenForm "Form2", acNormal
        Else
            DoCmd.OpenForm "Form3", acNormal
        End If
    End With
End Sub
</code>```

Based on a 1 column combo:

```<code>Private Sub Combo0_AfterUpdate()
    With Me.Combo0
        If IsNull(.Value) Then
            DoCmd.OpenForm "Form2", acNormal
        Else
            DoCmd.OpenForm "Form3", acNormal
        End If
    End With
End Sub
</code>```

Body:
Its been a long time since I have used coded in VBA, and I am rusty...

Trying to look at a field, which is populated by a combo box, within a table to see if it is null or not.  Based upon the field having value or not, the code determines which form to open.

[table].field

Form1
Form2

here is what I have attempted to no avail

If DLookup("[field]", "table", IsNull) Then
        DoCmd.OpenForm "form1", acNormal
        End If
    If DLookup("[field]", "table", NotIsNull) Then
        DoCmd.OpenForm "form2", acNormal

I can't get this to run without errors.  Help!

Body:
Do you mean you've got a combo-box on a form, the combo-box gets its values from a table.  If the selected value is blank then open one form, if it's got a value open another form?

Based on a two column Combo-Box (column 0 is hidden key value, column 1 holds the value we're after):

Private Sub Combo0_AfterUpdate()
    With Me.Combo0
        If .Column(1) = "" Then
            DoCmd.OpenForm "Form2", acNormal
        Else
            DoCmd.OpenForm "Form3", acNormal
        End If
    End With
End Sub

Based on a 1 column combo:

Private Sub Combo0_AfterUpdate()
    With Me.Combo0
        If IsNull(.Value) Then
            DoCmd.OpenForm "Form2", acNormal
        Else
            DoCmd.OpenForm "Form3", acNormal
        End If
    End With
End Sub


问:
VB.net, SQL 2012, selecting phone data where date is today
I'm making a wallboard app that displays all call records from a database in SQL 2012 server. I've been trying stuff left and right but everything gives one of 2 errors executing the select command:

"Conversion failed when converting date and/or time from character
  string"

or

"Invalid column name '07/07/2017 15:03:35'."

Here is an SQL select command example i have:

```<code>SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > """ & DateToday & """"
</code>```

I've worked on a different wallboard program for the company i'm on and when I tried retrieving data from the current date it worked with the select command above (tweaked obviously) and only with this has it started having problems on me.

edit: oops, where it says DateToday i mean DateYesterday, my bad

edit*: This is the code im using to essentially count the number of calls that happened today, it might be rubbish, but it was from the person who was here before me had this and when i was told to continue his work I just used and improvised his code since it was working and the databases i've worked with are all similar if not the same

```<code>SDACallsP = New SqlDataAdapter(cmdCallsP, conn)
Dim num_calls_parceiros = SDACallsP.Fill(data_set, "dbo.tblCallList")
cs_parceiros.Text = num_calls_parceiros

cmdCallsP = String.Format("SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > ''" & DateYesterday & "''")
Dim DateYesterday As Date = Date.Today.AddDays(-1).ToString("yyyy-MM-dd")
</code>```

答:
Did you try:
cmdCallsP = String.Format("SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > '" & DateYesterday.ToString & "'")

I do not think you need the double single quotes

Body:
I'm making a wallboard app that displays all call records from a database in SQL 2012 server. I've been trying stuff left and right but everything gives one of 2 errors executing the select command:

"Conversion failed when converting date and/or time from character
  string"

or

"Invalid column name '07/07/2017 15:03:35'."

Here is an SQL select command example i have:

SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > """ & DateToday & """"

I've worked on a different wallboard program for the company i'm on and when I tried retrieving data from the current date it worked with the select command above (tweaked obviously) and only with this has it started having problems on me.

edit: oops, where it says DateToday i mean DateYesterday, my bad

edit*: This is the code im using to essentially count the number of calls that happened today, it might be rubbish, but it was from the person who was here before me had this and when i was told to continue his work I just used and improvised his code since it was working and the databases i've worked with are all similar if not the same

SDACallsP = New SqlDataAdapter(cmdCallsP, conn)
Dim num_calls_parceiros = SDACallsP.Fill(data_set, "dbo.tblCallList")
cs_parceiros.Text = num_calls_parceiros

cmdCallsP = String.Format("SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > ''" & DateYesterday & "''")
Dim DateYesterday As Date = Date.Today.AddDays(-1).ToString("yyyy-MM-dd")


问:
Verilog - confusion between || and + operator
In boolean algebra, addition of terms corresponds to an OR gate, while multiplication corresponds to an AND gate.

Suppose I wanted a blower fan of a thermostat that worked as follows:

The fan should turn on if either the heater or air-conditioner are on. Alternatively if the user requests the fan to turn on (by turning on an input fan_on), the fan should turn on even if the heater or air conditioner are off.

Based on these requirements I formulated the logic statement in Verilog code as:

```<code>assign blower_fan = fan_on + heater + aircon;
</code>```

However upon simulation this yields an incorrect solution. However this works:

```<code>assign blower_fan = fan_on || (heater + aircon);
</code>```

as does

```<code>assign blower_fan = fan_on || (heater || aircon);
</code>```

My Question:

What am I misunderstanding about the + operator? Also, I'm confused between the latter two solutions that DO work - why do both of them work and is the last one where I use only the logical OR operator a more correct (or preferred) way of doing what I want to do?

Edit#1: Here is the whole module where I declared inputs and outputs

```<code>module top_module (
    input too_cold,
    input too_hot,
    input mode,
    input fan_on,
    output heater,
    output aircon,
    output fan
);

    assign heater = (mode&&too_cold);
    assign aircon = (!mode&&too_hot);
    assign fan = (fan_on) || (heater || aircon);

endmodule
</code>```

答:
Boolean expression for OR and AND are || and && respectively.

The + symbol is actually the arithmetic expression

```<code>a = 2'b01 // 1
b = 2'b01 // 1
a + b = 2'b10 // 1 + 1 = 2
a || b = 2'b01 // 1 OR 1 = 1
</code>```

Source: https://www.utdallas.edu/~akshay.sridharan/index_files/Page5212.htm

EDIT:

The two following statements are logically equivalent

```<code>assign fan = (fan_on) || (heater || aircon);
assign fan = fan_on || heater || aircon;
</code>```

The problem with

```<code>assign blower_fan = fan_on + heater + aircon;
</code>```

is that if two inputs are high (e.g. heater = 1, aircon = 1, fan_on = 0), then blower_fan (which is assumed to be 1 bit) has overflowed, and therefore will be 0 (1'b1 + 1'b1 = 1'b0).

Body:
In boolean algebra, addition of terms corresponds to an OR gate, while multiplication corresponds to an AND gate.

Suppose I wanted a blower fan of a thermostat that worked as follows:

The fan should turn on if either the heater or air-conditioner are on. Alternatively if the user requests the fan to turn on (by turning on an input fan_on), the fan should turn on even if the heater or air conditioner are off.

Based on these requirements I formulated the logic statement in Verilog code as:

assign blower_fan = fan_on + heater + aircon;

However upon simulation this yields an incorrect solution. However this works:

assign blower_fan = fan_on || (heater + aircon);

as does

assign blower_fan = fan_on || (heater || aircon);

My Question:

What am I misunderstanding about the + operator? Also, I'm confused between the latter two solutions that DO work - why do both of them work and is the last one where I use only the logical OR operator a more correct (or preferred) way of doing what I want to do?

Edit#1: Here is the whole module where I declared inputs and outputs

module top_module (
    input too_cold,
    input too_hot,
    input mode,
    input fan_on,
    output heater,
    output aircon,
    output fan
);

    assign heater = (mode&&too_cold);
    assign aircon = (!mode&&too_hot);
    assign fan = (fan_on) || (heater || aircon);

endmodule

Body:
Boolean expression for OR and AND are || and && respectively.

The + symbol is actually the arithmetic expression

a = 2'b01 // 1
b = 2'b01 // 1
a + b = 2'b10 // 1 + 1 = 2
a || b = 2'b01 // 1 OR 1 = 1

Source: https://www.utdallas.edu/~akshay.sridharan/index_files/Page5212.htm

EDIT:

The two following statements are logically equivalent

assign fan = (fan_on) || (heater || aircon);
assign fan = fan_on || heater || aircon;

The problem with

assign blower_fan = fan_on + heater + aircon;

is that if two inputs are high (e.g. heater = 1, aircon = 1, fan_on = 0), then blower_fan (which is assumed to be 1 bit) has overflowed, and therefore will be 0 (1'b1 + 1'b1 = 1'b0).


问:
How to get value selected from select in Yii?
I have a dropDownList like follwing:

```<code><?php echo TbHtml::dropdownList('cls', $sel, CHtml::listData($classes, 'type_class', 'name_class')); ?>
</code>```

That generates a select option like that:

```<code><select id="cls" name="cls">
    <option value="1">Main Class</option>
    <option value="2">Other Class</option>
</select>
</code>```

When I click on a button, I need to get the value, in my example 1 or 2.

The button is built like following:

```<code>echo $this->widget('booster.widgets.TbButton', array(
    'buttonType' => 'link',
    'context' => 'warning',
    'icon' => 'fa fa-file-pdf-o',
    'label' => 'Submit',
    'size' => 'small',
    'url' => array(
        '//wseder/excel/wws',
        'code_from_select' => $VALUE_THAT_I_NEED // here i need the value
    ),
    'htmlOptions' => array(
        'class' => 'pull-rigth btn-nxt-prv',
        'style' => 'margin-left:5px'
    )
), true);
</code>```

How can I access to the value selected from the select?

答: How I understand you creating select on html page and button on html page. When you click button you need get select val and put it in button. If so, you can not do it, because php do not have access to select val on html page. You should use javascript (jquery) to read select value and insert it where you need.</p>

Body:
I have a dropDownList like follwing:

<?php echo TbHtml::dropdownList('cls', $sel, CHtml::listData($classes, 'type_class', 'name_class')); ?>

That generates a select option like that:

<select id="cls" name="cls">
    <option value="1">Main Class</option>
    <option value="2">Other Class</option>
</select>

When I click on a button, I need to get the value, in my example 1 or 2.

The button is built like following:

echo $this->widget('booster.widgets.TbButton', array(
    'buttonType' => 'link',
    'context' => 'warning',
    'icon' => 'fa fa-file-pdf-o',
    'label' => 'Submit',
    'size' => 'small',
    'url' => array(
        '//wseder/excel/wws',
        'code_from_select' => $VALUE_THAT_I_NEED // here i need the value
    ),
    'htmlOptions' => array(
        'class' => 'pull-rigth btn-nxt-prv',
        'style' => 'margin-left:5px'
    )
), true);

How can I access to the value selected from the select?


问:
FormatException appears when trying to convert a string to Int16
The program is supposed to take a positive number from textbox1.Text and send it to the constructor HR form to use it as array size (handled error with try catch) but when I run the program it gives error.

```<code>//first form(info)
HR frm = new HR(textBox1.Text);
frm.show();
this.close();
//2nd form(HR)
static int size = 0;
public HR(string emplyee_num)
{
    InitializeComponent();
    size = Convert.ToInt16(emplyee_num);//Error appear her instead
}
</code>```

However, I tried to send the string then convert it in HR form instead of send it as shown in picture it gives error in the line for converting.

How can I fix that error and what is the reason for it being thrown?

答:
A FormatException is thrown because text in the input control is not a valid number.

It would be better to try parsing the input first and only create the form if the input is valid like this:

```<code>Int16 size = 0;
try
{
     size = Convert.ToInt16(textBox1.Text));
}
catch(FormatException)
{
     // Handle exception
}

if(size > 0)
{
     HR frm = new HR(size);
     frm.show();
     this.close();
}
else
{
     // Handle error
}
</code>```

Remember to update HR constructor definition:

```<code>public HR(Int16 emplyee_num)
{
    InitializeComponent();
    size = emplyee_num;
}
</code>```

Body:
The program is supposed to take a positive number from textbox1.Text and send it to the constructor HR form to use it as array size (handled error with try catch) but when I run the program it gives error.

//first form(info)
HR frm = new HR(textBox1.Text);
frm.show();
this.close();
//2nd form(HR)
static int size = 0;
public HR(string emplyee_num)
{
    InitializeComponent();
    size = Convert.ToInt16(emplyee_num);//Error appear her instead
}

However, I tried to send the string then convert it in HR form instead of send it as shown in picture it gives error in the line for converting.

How can I fix that error and what is the reason for it being thrown?

Body:
A FormatException is thrown because text in the input control is not a valid number.

It would be better to try parsing the input first and only create the form if the input is valid like this:

Int16 size = 0;
try
{
     size = Convert.ToInt16(textBox1.Text));
}
catch(FormatException)
{
     // Handle exception
}

if(size > 0)
{
     HR frm = new HR(size);
     frm.show();
     this.close();
}
else
{
     // Handle error
}

Remember to update HR constructor definition:

public HR(Int16 emplyee_num)
{
    InitializeComponent();
    size = emplyee_num;
}


问:
Nest QueryContainer usage
I am able to populate QueryContainer with DateRangeQuery array as shown below

```<code>        QueryContainer marriageDateQuerys = null;

        if (!string.IsNullOrEmpty((item.marriage_date)))
            {
                DateRangeQuery query = new DateRangeQuery();
                query.Field = "marriages.marriage_date";
                query.Name = item.marriage_date;
                query.GreaterThanOrEqualTo = item.marriage_date;
                query.LessThanOrEqualTo = item.marriage_date;

                marriageDateQuerys &= query;
            }
</code>```

But when I use QueryContainer to use MatchQuery/TermQuery to populate data it is not happening.

```<code>           QueryContainer marriageSpouseFirstNameQuerys = null;

            if (!string.IsNullOrEmpty((item.spouse_first_name)))
            {
                MatchQuery query = new MatchQuery();
                query.Field = "marriages.spouse_first_name";
                query.Name = item.spouse_first_name;
                marriageSpouseFirstNameQuerys &= query;
            }
</code>```

Query object is created in last if condition but marriageSpouseFirstNameQuerys is not populated with the same. I even tried marriageSpouseFirstNameQuerys += query; but without any success

答:
Below code worked for me after making changes with eyildiz answer</p>

```<code>       if (!string.IsNullOrEmpty((item.spouse_last_name)))
                {
                    marriageSpouseLastNameQuery = new QueryContainer(
                        new MatchQuery
                        {
                            Field = "marriages.spouse_last_name",
                            Query = item.spouse_last_name
                        });
                    lstmarriageSpouseLastNameQuerys.Add(marriageSpouseLastNameQuery);
                }
</code>```

Title: Nest QueryContainer usage

Body:
I am able to populate QueryContainer with DateRangeQuery array as shown below

        QueryContainer marriageDateQuerys = null;

        if (!string.IsNullOrEmpty((item.marriage_date)))
            {
                DateRangeQuery query = new DateRangeQuery();
                query.Field = "marriages.marriage_date";
                query.Name = item.marriage_date;
                query.GreaterThanOrEqualTo = item.marriage_date;
                query.LessThanOrEqualTo = item.marriage_date;

                marriageDateQuerys &= query;
            }

But when I use QueryContainer to use MatchQuery/TermQuery to populate data it is not happening.

           QueryContainer marriageSpouseFirstNameQuerys = null;

            if (!string.IsNullOrEmpty((item.spouse_first_name)))
            {
                MatchQuery query = new MatchQuery();
                query.Field = "marriages.spouse_first_name";
                query.Name = item.spouse_first_name;
                marriageSpouseFirstNameQuerys &= query;
            }

Query object is created in last if condition but marriageSpouseFirstNameQuerys is not populated with the same. I even tried marriageSpouseFirstNameQuerys += query; but without any success

Body:
Below code worked for me after making changes with eyildiz answer

       if (!string.IsNullOrEmpty((item.spouse_last_name)))
                {
                    marriageSpouseLastNameQuery = new QueryContainer(
                        new MatchQuery
                        {
                            Field = "marriages.spouse_last_name",
                            Query = item.spouse_last_name
                        });
                    lstmarriageSpouseLastNameQuerys.Add(marriageSpouseLastNameQuery);
                }


问:
TabLayout with ViewPager not working as expected
There is 3 TabLayout with ViewPager in my application.

If I swipe for change Tabs then it behaves strangely.

Below is the scenario.

Let's say 3 Tabs A, B, C.

Default Tab A will open when I start App.

Go to B From A - Works OK.

Go to A From B - Works Ok.

Go To B From A - Works Ok.

Go To C From B - Works Ok.

Now Problem Starts here.

Go To B From C - It will Load A and B Both but display Only B.

Why A and B loads if I come from C ??

Below is my code.

```<code>private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    ViewPagerAdapter adapter;

toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

private void setupViewPager(ViewPager viewPager) {
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FragmentOpen(), "OPEN");
        adapter.addFragment(new FragmentClose(), "CLOSE");
        adapter.addFragment(new FragmentTest(), "TEST");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
</code>```

I want to load Tabs every time.

For that, I use below code.

```<code>viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(adapter != null){
                    adapter.getItem(position).onResume();
                }
                Toast.makeText(getApplicationContext(), "Page Selected", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
</code>```

But it will always load both tabs when I came from C.

What I want is: only Tab B must load when came from C, not Both.

答:
Its not possible when using ViewPager. ViewPager loads at least one right/left adjacent fragment of current fragment as per your swipe direction.

If you read the ViewPager documentation, there is a method ViewPager.setOffscreenPageLimit(LIMIT) which supports off screen page limit and its default value is 1.

SetOffscreenPageLimit:

Set the number of pages that should be retained to either side of the
current page in the view hierarchy in an idle state. Pages beyond this
limit will be recreated from the adapter when needed.

This is offered as an optimization. If you know in advance the number
of pages you will need to support or have lazy-loading mechanisms in
place on your pages, tweaking this setting can have benefits in
perceived smoothness of paging animations and interaction. If you have
a small number of pages (3-4) that you can keep active all at once,
less time will be spent in layout for newly created view subtrees as
the user pages back and forth.

You should keep this limit low, especially if your pages have complex
layouts. This setting defaults to 1.

See documentation.

Here are some related answers:

1. ViewPager.setOffscreenPageLimit(0) doesn't work as expected

2. How can make my ViewPager load only one page at a time ie setOffscreenPageLimit(0);

3. How does setOffscreenPageLimit() improve ViewPager performance by retaining more offscreen Fragments?

Body:
There is 3 TabLayout with ViewPager in my application.

If I swipe for change Tabs then it behaves strangely.

Below is the scenario.

Let's say 3 Tabs A, B, C.

Default Tab A will open when I start App.

Go to B From A - Works OK.

Go to A From B - Works Ok.

Go To B From A - Works Ok.

Go To C From B - Works Ok.

Now Problem Starts here.

Go To B From C - It will Load A and B Both but display Only B.

Why A and B loads if I come from C ??

Below is my code.

private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    ViewPagerAdapter adapter;

toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

private void setupViewPager(ViewPager viewPager) {
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FragmentOpen(), "OPEN");
        adapter.addFragment(new FragmentClose(), "CLOSE");
        adapter.addFragment(new FragmentTest(), "TEST");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

I want to load Tabs every time.

For that, I use below code.

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(adapter != null){
                    adapter.getItem(position).onResume();
                }
                Toast.makeText(getApplicationContext(), "Page Selected", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

But it will always load both tabs when I came from C.

What I want is: only Tab B must load when came from C, not Both.