问:
Send button with certain features

Javascript

```<code>$(function(){
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true'); //disables the button
      $('#overlay').show(); //after disabling show the overlay for hover
      setTimeout(function(){
        $(this).attr('disabled','false'); //enables after 5mins
        $('#overlay').hide(); //hide the overlay
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
    $('#message').show();
},function(){
    $('#message').hide();
});
</code>```

CSS

```<code>.title-actions {
  float: right;
  height: 50px;
  margin-top: 13px; }
  .title-actions a {
    transition: background 0.3s ease; }
    .title-actions a.btn {
      padding: 2px 14px;
      line-height: 26px;
      max-height: 28px;
      position: relative;
      top: -1px;
      margin-left: 8px; }
    .title-actions a:hover {
      background: #4382b5; }
  .title-actions span {
    color: #444;
    background: #e6e6e6;
    padding: 6px 10px;
    border-radius: 3px;
    float: none;
    position: relative;
    margin-left: 6px; }
  .title-actions .btn {
    padding: 2px 14px;
    line-height: 26px;
    max-height: 28px;
    position: relative;
    top: -1px;
    margin-left: 8px; }
  .title-actions .btn-icon {
    background: transparent;
    position: relative;il
    color: #3e5366;
    text-align: center;
    display: inline-block;
    padding: 0 !important;
    transition: color 0.3s ease;
    box-shadow: none !important;
    margin-top: -16px;
    margin-left: 6px; }
    .title-actions .btn-icon i {
      font-size: 35px;
      line-height: 20px;
      position: relative;
      top: 12px; }
    .title-actions .btn-icon:hover {
      color: #4382b5;
      background: transparent; }
  .title-actions .badge .material-icons {
    font-size: 1.2em;
    line-height: 0;
    position: relative;
    top: 4px; }
.wrapper {
    display: inline-block;
}
</code>```

HTML

```<code>    <div class="wrapper">
        <div id="overlay"></div>
        <a href="#"
           title="{% trans "Send email - rejected file(s)" %}"
           class="btn btn-icon select-another-button"
           data-url="{% url "messaging:send" request_id=object.pk %}">
            <i class="material-icons">assignment_late</i>
            <div class='alert alert-success' id='send-message' style="display: none;">
                <p>
                The message was sent to the client. Please wait 5 minutes <br> before sending the message again.
                </p>
            </div>
        </a>
    </div>
</code>```

Django

I have this in my urls.py file

```<code>app_name = 'messaging'
urlpatterns = [
    ...

    url(r'^send/(?P<request_id>[0-9]+)/$',
        send, name='send'),
]
</code>```

The django's method is Send button with certain features

```<code>@staff_member_required
@csrf_exempt
def send(request, request_id=None):
    req= Request.objects.get(pk=request_id)
    request_folders = req.folder.all_files.all()
    context = []

    for doc in request_folders:
        if doc.meta.state == u'rejected':
            context.append(doc)

    if context:
        ctx = {'request': req}
        EmailFromTemplate('document-refusal', extra_context=ctx)\
            .send_to(req.customer.user)

    return HttpResponse('')
</code>```

I've created a button which send an email under certain conditions. I'd like once I send a message to deactivate the button for five minutes and then display a pop-up message which will display the remaining time before they have the possibility to send the email again. The message may be 'It remains 3 minutes and 20 secondes before you may send the message again.'. This message will be displayed if and only if the cursor is on the button and nothing will happen otherwise. So far when I clicked the button, it turned off, but nothing else happened. I mean django's function is never called, .... How could I fix it so that it'll do what I want? How could I display the remaining time in that message? With JsonResponse()?

Edit :

I have another issue with setTimeout. It is easy for the client to just reload the page to skip the 5 minutes wait. By what could I substitute setTimeout so that it will not do such thing?

答:
For getting the time left you can use something like this:

```<code>$(function(){
var timeout;
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true'); //disables the button
      $('#overlay').show(); //after disabling show the overlay for hover
      timeout = setTimeout(function(){
        $(this).attr('disabled','false'); //enables after 5mins
        $('#overlay').hide(); //hide the overlay
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
  var timeleft =  Math.ceil((timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000);
    $('#send-message').html("Please wait" + timeleft).show();
},function(){
    $('#send-message').hide();
});
</code>```

If show() and hide() didn't work, try .css("display","block")

Title: Send button with certain features

Body:
Javascript

$(function(){
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true'); //disables the button
      $('#overlay').show(); //after disabling show the overlay for hover
      setTimeout(function(){
        $(this).attr('disabled','false'); //enables after 5mins
        $('#overlay').hide(); //hide the overlay
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
    $('#message').show();
},function(){
    $('#message').hide();
});

CSS

.title-actions {
  float: right;
  height: 50px;
  margin-top: 13px; }
  .title-actions a {
    transition: background 0.3s ease; }
    .title-actions a.btn {
      padding: 2px 14px;
      line-height: 26px;
      max-height: 28px;
      position: relative;
      top: -1px;
      margin-left: 8px; }
    .title-actions a:hover {
      background: #4382b5; }
  .title-actions span {
    color: #444;
    background: #e6e6e6;
    padding: 6px 10px;
    border-radius: 3px;
    float: none;
    position: relative;
    margin-left: 6px; }
  .title-actions .btn {
    padding: 2px 14px;
    line-height: 26px;
    max-height: 28px;
    position: relative;
    top: -1px;
    margin-left: 8px; }
  .title-actions .btn-icon {
    background: transparent;
    position: relative;il
    color: #3e5366;
    text-align: center;
    display: inline-block;
    padding: 0 !important;
    transition: color 0.3s ease;
    box-shadow: none !important;
    margin-top: -16px;
    margin-left: 6px; }
    .title-actions .btn-icon i {
      font-size: 35px;
      line-height: 20px;
      position: relative;
      top: 12px; }
    .title-actions .btn-icon:hover {
      color: #4382b5;
      background: transparent; }
  .title-actions .badge .material-icons {
    font-size: 1.2em;
    line-height: 0;
    position: relative;
    top: 4px; }
.wrapper {
    display: inline-block;
}

HTML

            assignment_late

                The message was sent to the client. Please wait 5 minutes
 before sending the message again.

Django

I have this in my urls.py file

app_name = 'messaging'
urlpatterns = [
    ...

    url(r'^send/(?P<request_id>[0-9]+)/$',
        send, name='send'),
]

The django's method is Send button with certain features

@staff_member_required
@csrf_exempt
def send(request, request_id=None):
    req= Request.objects.get(pk=request_id)
    request_folders = req.folder.all_files.all()
    context = []

    for doc in request_folders:
        if doc.meta.state == u'rejected':
            context.append(doc)

    if context:
        ctx = {'request': req}
        EmailFromTemplate('document-refusal', extra_context=ctx)\
            .send_to(req.customer.user)

    return HttpResponse('')

I've created a button which send an email under certain conditions. I'd like once I send a message to deactivate the button for five minutes and then display a pop-up message which will display the remaining time before they have the possibility to send the email again. The message may be 'It remains 3 minutes and 20 secondes before you may send the message again.'. This message will be displayed if and only if the cursor is on the button and nothing will happen otherwise. So far when I clicked the button, it turned off, but nothing else happened. I mean django's function is never called, .... How could I fix it so that it'll do what I want? How could I display the remaining time in that message? With JsonResponse()?

Edit :

I have another issue with setTimeout. It is easy for the client to just reload the page to skip the 5 minutes wait. By what could I substitute setTimeout so that it will not do such thing?

Body:
For getting the time left you can use something like this:

$(function(){
var timeout;
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true'); //disables the button
      $('#overlay').show(); //after disabling show the overlay for hover
      timeout = setTimeout(function(){
        $(this).attr('disabled','false'); //enables after 5mins
        $('#overlay').hide(); //hide the overlay
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
  var timeleft =  Math.ceil((timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000);
    $('#send-message').html("Please wait" + timeleft).show();
},function(){
    $('#send-message').hide();
});

If show() and hide() didn't work, try .css("display","block")


来源: stackexchange

问:
Rspec testing No Route Matches ActionController::UrlGenerationError
I'm trying to wrap my head about Rspec and Controller tests, more specifically a JSON request.  In this case, I'm trying to hit the v1_devices_path route:

routes.rb

```<code>v1_device_scans POST   /v1/devices/:device_serial_number/scans(.:format) v1/scans#create
v1_device       GET    /v1/devices/:serial_number(.:format)              v1/devices#show
                PATCH  /v1/devices/:serial_number(.:format)              v1/devices#update
                PUT    /v1/devices/:serial_number(.:format)              v1/devices#update
</code>```

And my controller:

controllers/v1/devices_controller.rb

```<code>class V1::DevicesController < ApplicationController
  before_action :set_device, only: [:show, :update]
  respond_to :json

  def show
    @device = Device.find_by(serial_number: params[:serial_number])
    render :json => @device.as_json
  end

  def update
    if @device.update(device_params)
      render json: @device, status: :ok, location: @device
    else
      render json: @device.errors, status: :unprocessable_entity
    end
  end

  private

  def set_device
    @device = Device.find_by!(serial_number: params[:serial_number])
  end

  def device_params
    params.require(:device).permit(
      :serial_number,
      :name,
      :diagnostic_checkin_status,
      :diagnostic_dns,
      :diagnostic_ping,
      :assigned_internal_ip,
      :assigned_external_ip,
      :assigned_gateway_ip,
      :version,
      :timezone,
      :task_id,
      :scan_status,
      :scan_progress
    )
  end

end
</code>```

As of right now my test is super simple... just want to make sure I get some results back:

spec/controllers/v1/devices_controller_spec.rb

require 'rails_helper'

```<code>RSpec.describe V1::DevicesController, type: :controller do

  it "shows device info" do
    device = FactoryGirl.create(:device)
    get v1_device_path(device.serial_number), :format => :json
    expect(response.status).to be(200)
  end
end
</code>```

After some tweaking, I've gotten to the point where it looks like my url is being created correctly, but I'm still getting the no route matches error:

```<code>  1) V1::DevicesController shows device info
     Failure/Error: get v1_device_path(device.serial_number), :format => :json

     ActionController::UrlGenerationError:
       No route matches {:action=>"/v1/devices/41442305171c430ab253ba1ad95c5c61", :controller=>"v1/devices", :format=>:json}
     # /usr/local/bundle/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/template_assertions.rb:61:in `process'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:33:in `block in process'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:100:in `catch'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:100:in `_catch_warden'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:33:in `process'
     # /usr/local/bundle/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/integration.rb:12:in `block (2 levels) in <module:Integration>'
     # ./spec/controllers/v1/devices_controller_spec.rb:11:in `block (2 levels) in <top (required)>'
</code>```

What am I doing wrong?

答:
Alright, starting with @sebastián's comment, I changed the spec to:

```<code>require 'rails_helper'

RSpec.describe V1::DevicesController, type: :request do

  it "shows device info" do
    headers = {
      "ACCEPT" => "application/json",     # This is what Rails 4 accepts
    }

    device = FactoryGirl.create(:device)
    get v1_device_path(device.serial_number), :headers => headers
    expect(response.content_type).to eq("application/json")
  end
end
</code>```

And my test passes now.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to wrap my head about Rspec and Controller tests, more specifically a JSON request.  In this case, I'm trying to hit the v1_devices_path route:

routes.rb

v1_device_scans POST   /v1/devices/:device_serial_number/scans(.:format) v1/scans#create
v1_device       GET    /v1/devices/:serial_number(.:format)              v1/devices#show
                PATCH  /v1/devices/:serial_number(.:format)              v1/devices#update
                PUT    /v1/devices/:serial_number(.:format)              v1/devices#update

And my controller:

controllers/v1/devices_controller.rb

class V1::DevicesController < ApplicationController
  before_action :set_device, only: [:show, :update]
  respond_to :json

  def show
    @device = Device.find_by(serial_number: params[:serial_number])
    render :json => @device.as_json
  end

  def update
    if @device.update(device_params)
      render json: @device, status: :ok, location: @device
    else
      render json: @device.errors, status: :unprocessable_entity
    end
  end

  private

  def set_device
    @device = Device.find_by!(serial_number: params[:serial_number])
  end

  def device_params
    params.require(:device).permit(
      :serial_number,
      :name,
      :diagnostic_checkin_status,
      :diagnostic_dns,
      :diagnostic_ping,
      :assigned_internal_ip,
      :assigned_external_ip,
      :assigned_gateway_ip,
      :version,
      :timezone,
      :task_id,
      :scan_status,
      :scan_progress
    )
  end

end

As of right now my test is super simple... just want to make sure I get some results back:

spec/controllers/v1/devices_controller_spec.rb

require 'rails_helper'

RSpec.describe V1::DevicesController, type: :controller do

  it "shows device info" do
    device = FactoryGirl.create(:device)
    get v1_device_path(device.serial_number), :format => :json
    expect(response.status).to be(200)
  end
end

After some tweaking, I've gotten to the point where it looks like my url is being created correctly, but I'm still getting the no route matches error:

  1) V1::DevicesController shows device info
     Failure/Error: get v1_device_path(device.serial_number), :format => :json

     ActionController::UrlGenerationError:
       No route matches {:action=>"/v1/devices/41442305171c430ab253ba1ad95c5c61", :controller=>"v1/devices", :format=>:json}
     # /usr/local/bundle/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/template_assertions.rb:61:in `process'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:33:in `block in process'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:100:in `catch'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:100:in `_catch_warden'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:33:in `process'
     # /usr/local/bundle/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/integration.rb:12:in `block (2 levels) in <module:Integration>'
     # ./spec/controllers/v1/devices_controller_spec.rb:11:in `block (2 levels) in <top (required)>'

What am I doing wrong?

Body:
Alright, starting with @sebastián's comment, I changed the spec to:

require 'rails_helper'

RSpec.describe V1::DevicesController, type: :request do

  it "shows device info" do
    headers = {
      "ACCEPT" => "application/json",     # This is what Rails 4 accepts
    }

    device = FactoryGirl.create(:device)
    get v1_device_path(device.serial_number), :headers => headers
    expect(response.content_type).to eq("application/json")
  end
end

And my test passes now.


问:
Checkbox's OnAction does not do anything
I have a custom ribbon with several checkboxes within a menu:

```<code><?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="Ribbon_Load">
  <ribbon>
    <tabs>
      <tab id="ribbon" label="Ribbon">
        <group id="ribbonGroup" label="Group">
          <menu id="menu" label="Menu">
            <checkBox id="checkbox1" label="Checkbox 1" visible="true" onAction="OnCheckboxChanged"/>
            <checkBox id="checkbox2" label="Checkbox 2" visible="true" onAction="OnCheckboxChanged"/>
            <checkBox id="checkbox2" label="Checkbox 2" visible="true" onAction="OnCheckboxChanged"/>
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>
</code>```

This is the respective C# code:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Excel;

namespace ExcelAddIn1
{
    [ComVisible(true)]
    public class SSRRibbon : Office.IRibbonExtensibility
    {
        private Office.IRibbonUI ribbon;

        public SSRRibbon()
        {
        }

        #region IRibbonExtensibility-Member
        public string GetCustomUI(string ribbonID)
        {
            return GetResourceText("ExcelAddIn1.SSRRibbon.xml");
        }
        #endregion

        #region ribbon callback functions
        public void Ribbon_Load(Office.IRibbonUI ribbonUI)
        {
            this.ribbon = ribbonUI;
        }

        public void OnCheckboxChanged(Office.IRibbonControl control)
        {
            int i = 1;
        }
        #endregion

        #region auxiliary
        private static string GetResourceText(string resourceName)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            string[] resourceNames = asm.GetManifestResourceNames();
            for (int i = 0; i < resourceNames.Length; ++i)
            {
                if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
                {
                    using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
                    {
                        if (resourceReader != null)
                        {
                            return resourceReader.ReadToEnd();
                        }
                    }
                }
            }
            return null;
        }
        #endregion
    }
}
</code>```

However, OnCheckboxChanged is never called. It works fine when I use this callback function with buttons but it does not with checkboxes, neither in the menu nor directly in the ribbon group. It also does work with getPressed instead of onAction.

答:
This thread and this Social MSDN thread both indicate onAction has a second argument in the parameter; isPressed.

```<code>public void markAsRead_OnAction(Office.IRibbonControl control, bool isPressed)
{

public void cbViewAction(Office.IRibbonControl control, bool pressed)
{
</code>```

It is also the way official documentation states to do it:

```<code>public void OnActionCallback(Office.IRibbonControl control, bool isPressed)
{
    if (control.Id == "checkBox1")
    {
        MessageBox.Show("You clicked " + control.Id);
    }
    else
    {
        MessageBox.Show("You clicked a different control.");
    }
}
</code>```

Defining Callback Methods

It must be declared as public.

Its name must match the name of a callback method that you assigned to a control in the Ribbon XML file.

Its signature must match the signature of a type of callback method that is available for the associated Ribbon control.

Following on from that article I read Customizing the 2007 Office Fluent Ribbon for Developers (Part 3 of 3)

Can I have two callbacks with the same name but different signatures?

Although you can do this, we recommended that you have different callbacks for each control (and not count on built-in overloading to handle the distinction between the two callbacks). For example, assume that you write a Fluent UI add-in with two callbacks of the same name, as in the following code.

```<code>public void doSomething(IRibbonControl control, bool pressState);
public void doSomething(IRibbonControl control);
</code>```

Also assume that your XML markup defines a toggleButton control and a button control, and that each of them has an onAction="doSomething" callback.
  In this instance, only the toggleButton control will work, because of the Visual Basic and Visual C# auto-generated IDispatch implementation. If you write a C++ add-in and implement IDispatch yourself, this case will work. (In other words, it is best not to do this.)

Body:
I have a custom ribbon with several checkboxes within a menu:

<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="Ribbon_Load">
  <ribbon>
    <tabs>
      <tab id="ribbon" label="Ribbon">
        <group id="ribbonGroup" label="Group">
          <menu id="menu" label="Menu">
            <checkBox id="checkbox1" label="Checkbox 1" visible="true" onAction="OnCheckboxChanged"/>
            <checkBox id="checkbox2" label="Checkbox 2" visible="true" onAction="OnCheckboxChanged"/>
            <checkBox id="checkbox2" label="Checkbox 2" visible="true" onAction="OnCheckboxChanged"/>
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>

This is the respective C# code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Excel;

namespace ExcelAddIn1
{
    [ComVisible(true)]
    public class SSRRibbon : Office.IRibbonExtensibility
    {
        private Office.IRibbonUI ribbon;

        public SSRRibbon()
        {
        }

        #region IRibbonExtensibility-Member
        public string GetCustomUI(string ribbonID)
        {
            return GetResourceText("ExcelAddIn1.SSRRibbon.xml");
        }
        #endregion

        #region ribbon callback functions
        public void Ribbon_Load(Office.IRibbonUI ribbonUI)
        {
            this.ribbon = ribbonUI;
        }

        public void OnCheckboxChanged(Office.IRibbonControl control)
        {
            int i = 1;
        }
        #endregion

        #region auxiliary
        private static string GetResourceText(string resourceName)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            string[] resourceNames = asm.GetManifestResourceNames();
            for (int i = 0; i < resourceNames.Length; ++i)
            {
                if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
                {
                    using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
                    {
                        if (resourceReader != null)
                        {
                            return resourceReader.ReadToEnd();
                        }
                    }
                }
            }
            return null;
        }
        #endregion
    }
}

However, OnCheckboxChanged is never called. It works fine when I use this callback function with buttons but it does not with checkboxes, neither in the menu nor directly in the ribbon group. It also does work with getPressed instead of onAction.

Body:
This thread and this Social MSDN thread both indicate onAction has a second argument in the parameter; isPressed.

public void markAsRead_OnAction(Office.IRibbonControl control, bool isPressed)
{

public void cbViewAction(Office.IRibbonControl control, bool pressed)
{

It is also the way official documentation states to do it:

public void OnActionCallback(Office.IRibbonControl control, bool isPressed)
{
    if (control.Id == "checkBox1")
    {
        MessageBox.Show("You clicked " + control.Id);
    }
    else
    {
        MessageBox.Show("You clicked a different control.");
    }
}

Defining Callback Methods

It must be declared as public.

Its name must match the name of a callback method that you assigned to a control in the Ribbon XML file.

Its signature must match the signature of a type of callback method that is available for the associated Ribbon control.

Following on from that article I read Customizing the 2007 Office Fluent Ribbon for Developers (Part 3 of 3)

Can I have two callbacks with the same name but different signatures?

Although you can do this, we recommended that you have different callbacks for each control (and not count on built-in overloading to handle the distinction between the two callbacks). For example, assume that you write a Fluent UI add-in with two callbacks of the same name, as in the following code.

public void doSomething(IRibbonControl control, bool pressState);
public void doSomething(IRibbonControl control);

Also assume that your XML markup defines a toggleButton control and a button control, and that each of them has an onAction="doSomething" callback.
  In this instance, only the toggleButton control will work, because of the Visual Basic and Visual C# auto-generated IDispatch implementation. If you write a C++ add-in and implement IDispatch yourself, this case will work. (In other words, it is best not to do this.)


问:
Parsing a script tag with dicts in BeautifulSoup
Working on a partial answer to this question, I came across a bs4.element.Tag that is a mess of nested dicts and lists (s, below).

Is there a way to return a list of urls contained in s without using re.find_all?  Other comments regarding the structure of this tag are helpful too.

```<code>from bs4 import BeautifulSoup
import requests

link = 'https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab&sort=p'
r = requests.get(link)
soup = BeautifulSoup(r.text, 'html.parser')

s = soup.find('script', type='application/ld+json')

## the first bit of s:
# s
# Out[116]:
# <script type="application/ld+json">
# {"@context":"http://schema.org","@type":"ItemList","numberOfItems":50,
</code>```

What I've tried:

randomly perusing through methods with tab completion on s.

picking through the docs.

My problem is that s only has 1 attribute (type) and doesn't seem to have any child tags.

答:
You can use s.text to get the content of the script. It's JSON, so you can then just parse it with json.loads. From there, it's simple dictionary access:

```<code>import json

from bs4 import BeautifulSoup
import requests

link = 'https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab&sort=p'
r = requests.get(link)

soup = BeautifulSoup(r.text, 'html.parser')

s = soup.find('script', type='application/ld+json')

urls = [el['url'] for el in json.loads(s.text)['itemListElement']]

print(urls)
</code>```

Body:
Working on a partial answer to this question, I came across a bs4.element.Tag that is a mess of nested dicts and lists (s, below).

Is there a way to return a list of urls contained in s without using re.find_all?  Other comments regarding the structure of this tag are helpful too.

from bs4 import BeautifulSoup
import requests

link = 'https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab&sort=p'
r = requests.get(link)
soup = BeautifulSoup(r.text, 'html.parser')

s = soup.find('script', type='application/ld+json')

## the first bit of s:
# s
# Out[116]:
#

Body:
You can use s.text to get the content of the script. It's JSON, so you can then just parse it with json.loads. From there, it's simple dictionary access:

import json

from bs4 import BeautifulSoup
import requests

link = 'https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab&sort=p'
r = requests.get(link)

soup = BeautifulSoup(r.text, 'html.parser')

s = soup.find('script', type='application/ld+json')

urls = [el['url'] for el in json.loads(s.text)['itemListElement']]

print(urls)


问:
Convert from long to wide format counting frequency of eliminated factor level (Prepping dataframe for input into iNEXT Online)
I have a dataframe that looks like:

```<code>df<- data.frame(region= c("1","1","1","1","1","2","2","2","2","2","2"),loc=c("104","104","104","105","106","107","108", "109", "110", "110", "111"), interact= c("A_B", "B_C", "A_B", "B_C", "B_C", "A_B", "G_H", "I_J", "J_K", "L_M", "M_O"))
</code>```

And I would like to change it from long to wide format so that the region number becomes the variable (column headings) and the rows become counts of the levels of interact occurring in that region. The caveat is I would also like the first row to be a count of unique loc levels in that region. I will first illustrate the intermediate df:

```<code>df2<- data.frame(interact= c("", "A_B", "B_C", "G_H", "I_J", "J_K",
 "L_M", "M_O"), region1= c("3", "2", "3", "0","0","0","0","0"),
 region2= c("5", "1", "0", "1","1","1","1","1"))
</code>```

You'll notice that there were 3 unique levels in loc for region 1 and 5 unique levles in loc for region2; thus the first row of numbers indicate the unique loc count in that region. All rows to follow represent the frequency of each interaction type among all loc in that region. However, I do not want this interact column in the final dataframe so the final output should look like:

```<code>output<- data.frame(region1= c("3", "2", "3", "0","0","0","0","0"),
region2= c("5", "1", "0", "1","1","1","1","1"))
</code>```

I have tried the following, but I get stuck adding a row with counts of unique loc in each region and I know my current steps are not the most efficient methods:

```<code>library(tidyr)
df<- df %>%
group_by(region, interact) %>%
summarise(freq = n())
data_wide <- spread(df, region, freq)
data_wide<- data_wide[,-1]
</code>```

答:
We can do this in two steps using data.table

```<code>library(data.table)
d1 <- dcast(setDT(df)[, .(interact = "", uniqueN(loc)), region],
         interact ~ paste0('region', region))
rbind(d1, dcast(df, interact ~ paste0('region', region), length))
#   interact region1 region2
#1:                3       5
#2:      A_B       2       1
#3:      B_C       3       0
#4:      G_H       0       1
#5:      I_J       0       1
#6:      J_K       0       1
#7:      L_M       0       1
#8:      M_O       0       1
</code>```

Or using tidyverse

```<code>library(tidyverse)
bind_rows(df %>%
            group_by(region = paste0('region', region)) %>%
            summarise(interact = "", V1 = n_distinct(loc)) %>%
            spread(region, V1),
          df %>%
            group_by(region = paste0('region', region),
                    interact = as.character(interact)) %>%
            summarise(V1 = n()) %>%
            spread(region, V1, fill = 0))
# A tibble: 8 x 3
#  interact region1 region2
#     <chr>   <dbl>   <dbl>
#1                3       5
#2      A_B       2       1
#3      B_C       3       0
#4      G_H       0       1
#5      I_J       0       1
#6      J_K       0       1
#7      L_M       0       1
#8      M_O       0       1
</code>```

Body:
I have a dataframe that looks like:

df<- data.frame(region= c("1","1","1","1","1","2","2","2","2","2","2"),loc=c("104","104","104","105","106","107","108", "109", "110", "110", "111"), interact= c("A_B", "B_C", "A_B", "B_C", "B_C", "A_B", "G_H", "I_J", "J_K", "L_M", "M_O"))

And I would like to change it from long to wide format so that the region number becomes the variable (column headings) and the rows become counts of the levels of interact occurring in that region. The caveat is I would also like the first row to be a count of unique loc levels in that region. I will first illustrate the intermediate df:

df2<- data.frame(interact= c("", "A_B", "B_C", "G_H", "I_J", "J_K",
 "L_M", "M_O"), region1= c("3", "2", "3", "0","0","0","0","0"),
 region2= c("5", "1", "0", "1","1","1","1","1"))

You'll notice that there were 3 unique levels in loc for region 1 and 5 unique levles in loc for region2; thus the first row of numbers indicate the unique loc count in that region. All rows to follow represent the frequency of each interaction type among all loc in that region. However, I do not want this interact column in the final dataframe so the final output should look like:

output<- data.frame(region1= c("3", "2", "3", "0","0","0","0","0"),
region2= c("5", "1", "0", "1","1","1","1","1"))

I have tried the following, but I get stuck adding a row with counts of unique loc in each region and I know my current steps are not the most efficient methods:

library(tidyr)
df<- df %>%
group_by(region, interact) %>%
summarise(freq = n())
data_wide <- spread(df, region, freq)
data_wide<- data_wide[,-1]

Body:
We can do this in two steps using data.table

library(data.table)
d1 <- dcast(setDT(df)[, .(interact = "", uniqueN(loc)), region],
         interact ~ paste0('region', region))
rbind(d1, dcast(df, interact ~ paste0('region', region), length))
#   interact region1 region2
#1:                3       5
#2:      A_B       2       1
#3:      B_C       3       0
#4:      G_H       0       1
#5:      I_J       0       1
#6:      J_K       0       1
#7:      L_M       0       1
#8:      M_O       0       1

Or using tidyverse

library(tidyverse)
bind_rows(df %>%
            group_by(region = paste0('region', region)) %>%
            summarise(interact = "", V1 = n_distinct(loc)) %>%
            spread(region, V1),
          df %>%
            group_by(region = paste0('region', region),
                    interact = as.character(interact)) %>%
            summarise(V1 = n()) %>%
            spread(region, V1, fill = 0))
# A tibble: 8 x 3
#  interact region1 region2
#     <chr>   <dbl>   <dbl>
#1                3       5
#2      A_B       2       1
#3      B_C       3       0
#4      G_H       0       1
#5      I_J       0       1
#6      J_K       0       1
#7      L_M       0       1
#8      M_O       0       1


问:
Explain db tag storage method
from this post What is the most efficient way to store tags in a database?

It was recommended to store tag tables like this.

```<code>Table: Item
Columns: ItemID, Title, Content

Table: Tag
Columns: TagID, Title

Table: ItemTag
Columns: ItemID, TagID
</code>```

And another SO post said the same thing. Can anyone explain why tags should be stored like this?
I am guessing ItemID is some internal val, title is the tag name (c++, sql, noob, etc)
content is whatever else data i want to store with my item.
why not something like

```<code>Table: Item
Columns: ItemID, Title, <more data i want>

Table: TagList
Columns: ItemID, Title
</code>```

title in item being "item name" and tag title being "c++" "sql" "noob" "etc"

答:
There's nothing wrong with the second design you show, the one with the TagList table, except that it takes more space.

That is, if you tag 10,000 items with the tag "database-design", then in the two-table design, you have to store that string 10,000 times.  If space-efficiency is more important, you could use the three-table design, which would only store the 4-byte integer ID for "database-design" 10,000 times.  A savings of 10 * 10,000 bytes.

Another difference is that in the three-table design, you could have more than one row in the Tag table with the same string, even though they have different integer ID values.  So in the ItemTag table, they would appear to be different tags, and you'd never know that they're actually tagged similarly.  Whereas in the two-table design, tags with the same spelling become grouped together implicitly.

Another point:  if you have the need to change the spelling of tags, then in the two-table design you have to update many rows.  In the three-table design, you only need to update a single row.

And finally, if you commonly need a list of unique tags, it's more speedy to query the Tags table in the three-table design, instead of needing a SELECT DISTINCT tag FROM TagList every time you need the unique list.  And the latter only gives you a list of tags in use, not a list of all eligible tags.

LastEditorDisplayName: Cade Roux

ContentLicense: CC BY-SA 2.5

Title: Explain db tag storage method

Body:
from this post What is the most efficient way to store tags in a database?

It was recommended to store tag tables like this.

Table: Item
Columns: ItemID, Title, Content

Table: Tag
Columns: TagID, Title

Table: ItemTag
Columns: ItemID, TagID

And another SO post said the same thing. Can anyone explain why tags should be stored like this?
I am guessing ItemID is some internal val, title is the tag name (c++, sql, noob, etc)
content is whatever else data i want to store with my item.
why not something like

Table: Item
Columns: ItemID, Title, <more data i want>

Table: TagList
Columns: ItemID, Title

title in item being "item name" and tag title being "c++" "sql" "noob" "etc"

OwnerDisplayName: Bill Karwin


问:
There is no .hgignore file after I do an initial hginit command
I've created my very first Mercurial repo on my machine. I used the hg init command on the directory.

Now I'm trying to use this ignore file, before uploading to BitBucket:

Mercurial .hgignore for Visual Studio 2008 projects

Where would I post Even Mien's configuration file? I can't find an hgignore file anywhere.

Thanks

答: Just make one in the top-level directory of the repository (the same place where the .hg folder is).</p>

OwnerDisplayName: delete


问:
CSS - Rating css system
I'm using some rating system css i've found on the web.
Currently i was able to put it work but there is an issue when mutiple ratings are shown.

Only the last rating class is working.

.rate {
  float: left;
  pointer-events: none;
}

.rate:not(:checked)>input {
  position: absolute;
  top: -9999px;
}

.rate:not(:checked)>label {
  float: right;
  width: 1em;
  overflow: hidden;
  white-space: nowrap;
  cursor: pointer;
  font-size: 30px;
  color: #ccc;
}

.rate:not(:checked)>label:before {
  content: '★ ';
}

.rate>input:checked~label {
  color: #ffc700;
}

.rate:not(:checked)>label:hover,
.rate:not(:checked)>label:hover~label {
  color: #deb217;
}

.rate>input:checked+label:hover,
.rate>input:checked+label:hover~label,
.rate>input:checked~label:hover,
.rate>input:checked~label:hover~label,
.rate>label:hover~input:checked~label {
  color: #c59b08;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="rate">
  <input type="radio" id="star5" name="rate" value="5" />
  <label for="star5" title="text">5 stars</label>
  <input type="radio" id="star4" name="rate" value="4" checked/>
  <label for="star4" title="text">4 stars</label>
  <input type="radio" id="star3" name="rate" value="3" />
  <label for="star3" title="text">3 stars</label>
  <input type="radio" id="star2" name="rate" value="2" />
  <label for="star2" title="text">2 stars</label>
  <input type="radio" id="star1" name="rate" value="1" />
  <label for="star1" title="text">1 star</label>
</div>

<div class="rate">
  <input type="radio" id="star5" name="rate" value="5" checked/>
  <label for="star5" title="text">5 stars</label>
  <input type="radio" id="star4" name="rate" value="4" />
  <label for="star4" title="text">4 stars</label>
  <input type="radio" id="star3" name="rate" value="3" />
  <label for="star3" title="text">3 stars</label>
  <input type="radio" id="star2" name="rate" value="2" />
  <label for="star2" title="text">2 stars</label>
  <input type="radio" id="star1" name="rate" value="1" />
  <label for="star1" title="text">1 star</label>
</div></code>```

Only the last div is correctly working.

答:
If you have the same "name" tag on all radio buttons, they will be treated as only one set of radio buttons even if they are in 2 different divs.

Also, it is bad practice to have duplicate ids on elements

To have it fixed, you should have your html like this https://jsfiddle.net/cornelraiu/70sk3ft6/1/:

```<code><div class="rate">
    <input type="radio" name="rate" value="5" />
    <label title="text">5 stars</label>
    <input type="radio" name="rate" value="4" checked/>
    <label title="text">4 stars</label>
    <input type="radio" name="rate" value="3" />
    <label title="text">3 stars</label>
    <input type="radio" name="rate" value="2" />
    <label title="text">2 stars</label>
    <input type="radio" name="rate" value="1" />
    <label title="text">1 star</label>
</div>

<div class="rate">
    <input type="radio" name="rate1" value="5" checked/>
    <label title="text">5 stars</label>
    <input type="radio" name="rate1" value="4" />
    <label title="text">4 stars</label>
    <input type="radio" name="rate1" value="3" />
    <label title="text">3 stars</label>
    <input type="radio" name="rate1" value="2" />
    <label title="text">2 stars</label>
    <input type="radio" name="rate1" value="1" />
    <label title="text">1 star</label>
</div>
</code>```

Title: CSS - Rating css system

Body:
I'm using some rating system css i've found on the web.
Currently i was able to put it work but there is an issue when mutiple ratings are shown.

Only the last rating class is working.

.rate {
  float: left;
  pointer-events: none;
}

.rate:not(:checked)>input {
  position: absolute;
  top: -9999px;
}

.rate:not(:checked)>label {
  float: right;
  width: 1em;
  overflow: hidden;
  white-space: nowrap;
  cursor: pointer;
  font-size: 30px;
  color: #ccc;
}

.rate:not(:checked)>label:before {
  content: '★ ';
}

.rate>input:checked~label {
  color: #ffc700;
}

.rate:not(:checked)>label:hover,
.rate:not(:checked)>label:hover~label {
  color: #deb217;
}

.rate>input:checked+label:hover,
.rate>input:checked+label:hover~label,
.rate>input:checked~label:hover,
.rate>input:checked~label:hover~label,
.rate>label:hover~input:checked~label {
  color: #c59b08;
}

  <input type="radio" id="star5" name="rate" value="5" />
  5 stars
  <input type="radio" id="star4" name="rate" value="4" checked/>
  4 stars
  <input type="radio" id="star3" name="rate" value="3" />
  3 stars
  <input type="radio" id="star2" name="rate" value="2" />
  2 stars
  <input type="radio" id="star1" name="rate" value="1" />
  1 star

  <input type="radio" id="star5" name="rate" value="5" checked/>
  5 stars
  <input type="radio" id="star4" name="rate" value="4" />
  4 stars
  <input type="radio" id="star3" name="rate" value="3" />
  3 stars
  <input type="radio" id="star2" name="rate" value="2" />
  2 stars
  <input type="radio" id="star1" name="rate" value="1" />
  1 star

Only the last div is correctly working.

Body:
If you have the same "name" tag on all radio buttons, they will be treated as only one set of radio buttons even if they are in 2 different divs.

Also, it is bad practice to have duplicate ids on elements

To have it fixed, you should have your html like this https://jsfiddle.net/cornelraiu/70sk3ft6/1/:

<div class="rate">
    <input type="radio" name="rate" value="5" />
    <label title="text">5 stars</label>
    <input type="radio" name="rate" value="4" checked/>
    <label title="text">4 stars</label>
    <input type="radio" name="rate" value="3" />
    <label title="text">3 stars</label>
    <input type="radio" name="rate" value="2" />
    <label title="text">2 stars</label>
    <input type="radio" name="rate" value="1" />
    <label title="text">1 star</label>
</div>

<div class="rate">
    <input type="radio" name="rate1" value="5" checked/>
    <label title="text">5 stars</label>
    <input type="radio" name="rate1" value="4" />
    <label title="text">4 stars</label>
    <input type="radio" name="rate1" value="3" />
    <label title="text">3 stars</label>
    <input type="radio" name="rate1" value="2" />
    <label title="text">2 stars</label>
    <input type="radio" name="rate1" value="1" />
    <label title="text">1 star</label>
</div>


问:
How to get sequence name list in sqlserver?
How to get list of sequence names in Postgres?

Today,I asked how to get the sequence name list in the postgresql,Thanks to DunnoHowToCode provides the answer for me.

Now,the same question I meet in sqlsever.I through

```<code>SELECT * FROM sys.SEQUENCES
</code>```

to get it,but anything I can't get.I want to get the sequence name list by sql statement in sqlsever.How can I do it?

答: You can view them in SSMS, in the Object Explorer:

Body:
How to get list of sequence names in Postgres?

Today,I asked how to get the sequence name list in the postgresql,Thanks to DunnoHowToCode provides the answer for me.

Now,the same question I meet in sqlsever.I through

SELECT * FROM sys.SEQUENCES

to get it,but anything I can't get.I want to get the sequence name list by sql statement in sqlsever.How can I do it?


问:
Partial view issue - jQuery not defined
I am facing jQuery loading issue in an ASP.NET MVC 5 project. I am trying to load a partial view so I have used

@Html.Action("GetView", "Home")

Partial view contains some jQuery functions. When it's loaded it shows jQuery not defined message, but jQuery is working on main page.

So I have tried two other methods to load the partial view and there is no issue of jQuery with these methods

```<code>@Html.Partial("_viewname")

@Ajax.BeginForm()
</code>```

Home Controller

```<code>public class HomeController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetView(string id = "")
        {
           return PartialView("_ViewName");

        }
    }
</code>```

_Layout.cshtml

```<code><!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
    @Scripts.Render("~/bundles/modernizr")
    @RenderSection("Head", false)
</head>
<body>
    <section >
        <div>
            @RenderBody()
        </div>

        <div>
            @RenderSection("Sidebar", false)
        </div>

    </section>

    <!-- jQuery -->
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("Scripts", false)
</body>
</code>```

Parent Page Index.cshtml

```<code>@{
    ViewBag.Title = "Admin";
}

<div id="main_content">
    @Html.Action("GetView", "Packages")
</div>
</code>```

Partial View _view.cshtml

```<code><div class="row">
    <div class="col-sm-12">
        <select>
            <option>1</option>
            <option>2</option>
        </select>
    </div>
</div>

<script type="text/javascript">

    $(document).ready(function () {
        $("select").addClass("form-control");
    });

</script>
</code>```

I think there is some jQuery loading issue, but I don't understand why this is happening on specific action.

Please suggest me solution for this issue.

答:
If you must run scripts on a partial view, as is the case when dynamically created content is returned when calling partial views from an AJAX call, you should find that the problem described in the question actually only happens on the initial parent page load. If this is the case, you can work around the problem by NOT loading the partial on the primary view. Instead, you can load the partial view using JQuery AFTER the initial page load.

So, instead of doing this inline with the HTML on the primary view:

```<code>@Html.Partial("YourCoolDynamicDashboard")
</code>```

Do this in a .js file or within your primary view's javascript tag:

```<code>$(document).ready(function () {
      $.get("/YourController/YourCoolDynamicDashboard", [<... data goes here...>], function (result) {
            $("#YourDashboardContainer").html(result);
      });
});
</code>```

This work around will allow you to run client-side JQuery code on both the primary view AND in the partial view.

Title: Partial view issue - jQuery not defined

Body:
I am facing jQuery loading issue in an ASP.NET MVC 5 project. I am trying to load a partial view so I have used

@Html.Action("GetView", "Home")

Partial view contains some jQuery functions. When it's loaded it shows jQuery not defined message, but jQuery is working on main page.

So I have tried two other methods to load the partial view and there is no issue of jQuery with these methods

@Html.Partial("_viewname")

@Ajax.BeginForm()

Home Controller

public class HomeController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetView(string id = "")
        {
           return PartialView("_ViewName");

        }
    }

_Layout.cshtml

<!DOCTYPE html>

    <title>@ViewBag.Title</title>
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
    @Scripts.Render("~/bundles/modernizr")
    @RenderSection("Head", false)

            @RenderBody()

            @RenderSection("Sidebar", false)

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("Scripts", false)

Parent Page Index.cshtml

@{
    ViewBag.Title = "Admin";
}

    @Html.Action("GetView", "Packages")

Partial View _view.cshtml

        <select>
            <option>1</option>
            <option>2</option>
        </select>

I think there is some jQuery loading issue, but I don't understand why this is happening on specific action.

Please suggest me solution for this issue.

Body:
If you must run scripts on a partial view, as is the case when dynamically created content is returned when calling partial views from an AJAX call, you should find that the problem described in the question actually only happens on the initial parent page load. If this is the case, you can work around the problem by NOT loading the partial on the primary view. Instead, you can load the partial view using JQuery AFTER the initial page load.

So, instead of doing this inline with the HTML on the primary view:

@Html.Partial("YourCoolDynamicDashboard")

Do this in a .js file or within your primary view's javascript tag:

$(document).ready(function () {
      $.get("/YourController/YourCoolDynamicDashboard", [<... data goes here...>], function (result) {
            $("#YourDashboardContainer").html(result);
      });
});

This work around will allow you to run client-side JQuery code on both the primary view AND in the partial view.


问:
Kubernetes CronJob
I am trying to run the Cron Job example provided on the Kubernetes web site. It says the prerequisites are Kubernetes cluster version >=1.5 (I am currently on 1.6.6) and batch/v2alpha1 API turned on.

The document mentioned that we need to pass "--runtime-config=batch/v2alpha1=true" argument while bringing up the API server to turn on the batch/v2alpha1 API, but it does not mention how exactly to do that. The link given for Turn on or off an API version for your cluster does not mention detailed procedures neither.

I am quite confused on where should I pass the "--runtime-config=batch/v2alpha1=true" argument, and how exactly should I do that.
I saw in some places mentioned that we could download kube-apiserver file, but I tired to run it without success, and I was quite confused about what kind of argument should I pass.

As mentioned above I am using a 1.6.6 kubernetes cluster, and I am running it on Google Cloud Platform.

Thanks for the clarification.

答:
on the master server api configuration stored in this location /etc/kubernetes/manifests/kube-apiserver.yaml.

take the backup of this file.

add the new argument in  command: section.

restart the node, it will start with new argument.

Title: Kubernetes CronJob


问:
Expected Declaration in UITableViewCell class
If I want to perform logic in a ViewController I put it in a function eg viewDidLoad or a button action.

But if I want to perform logic when a UITableViewCell class has been loaded, how do I do this?

```<code>class MapKitViewCell: UITableViewCell {
    @IBOutlet var the_map: MKMapView!
}
</code>```

I want to set the_map's delegate as itself, and add a polyline. I was able to do this in another viewController in viewDidLoad. Any ideas?

答: You can do that in cellForRow method. In this method, you are first dequeing a cell, set correct state and then return the cell to display on the window. You can do whatever you want to this cell element before returning it in this cellForRow method

Body:
If I want to perform logic in a ViewController I put it in a function eg viewDidLoad or a button action.

But if I want to perform logic when a UITableViewCell class has been loaded, how do I do this?

class MapKitViewCell: UITableViewCell {
    @IBOutlet var the_map: MKMapView!
}

I want to set the_map's delegate as itself, and add a polyline. I was able to do this in another viewController in viewDidLoad. Any ideas?


答:
You've got two problems:

Duplicate Ids. Ids have to be unique.

Your rating groups have the same name. Each group should have a distinct name

Fix that an all works.

.rate {
    float: left;
    /*pointer-events: none;*/
}

.rate:not(:checked) > input {
    position: absolute;
    top: -9999px;
}

.rate:not(:checked) > label {
    float: right;
    width: 1em;
    overflow: hidden;
    white-space: nowrap;
    cursor: pointer;
    font-size: 12px;
    color: #ccc;
}

.rate:not(:checked) > label:before { content: '★ '; }

.rate > input:checked ~ label { color: #ffc700; }

.rate:not(:checked) > label:hover, .rate:not(:checked) > label:hover ~ label { color: #deb217; }

.rate > input:checked + label:hover, .rate > input:checked + label:hover ~ label, .rate > input:checked ~ label:hover, .rate > input:checked ~ label:hover ~ label, .rate > label:hover ~ input:checked ~ label { color: #c59b08; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="rate">
    <input type="radio" id="v1_star5" name="rate1" value="5" />
    <label for="v1_star5" title="text">5 stars</label>
    <input type="radio" id="v1_star4" name="rate1" value="4" checked/>
    <label for="v1_star4" title="text">4 stars</label>
    <input type="radio" id="v1_star3" name="rate1" value="3" />
    <label for="v1_star3" title="text">3 stars</label>
    <input type="radio" id="v1_star2" name="rate1" value="2" />
    <label for="v1_star2" title="text">2 stars</label>
    <input type="radio" id="v1_star1" name="rate1" value="1" />
    <label for="v1_star1" title="text">1 star</label>
    </div>

   <div class="rate">
    <input type="radio" id="v2_star5" name="rate2" value="5" checked/>
    <label for="v2_star5" title="text">5 stars</label>
    <input type="radio" id="v2_star4" name="rate2" value="4" />
    <label for="v2_star4" title="text">4 stars</label>
    <input type="radio" id="v2_star3" name="rate2" value="3" />
    <label for="v2_star3" title="text">3 stars</label>
    <input type="radio" id="v2_star2" name="rate2" value="2" />
    <label for="v2_star2" title="text">2 stars</label>
    <input type="radio" id="v2_star1" name="rate2" value="1" />
    <label for="v2_star1" title="text">1 star</label>
    </div></code>```

I've removed the pointer-events style so you can see the full end result.

Title: CSS - Rating css system

Body:
You've got two problems:

Duplicate Ids. Ids have to be unique.

Your rating groups have the same name. Each group should have a distinct name

Fix that an all works.

.rate {
    float: left;
    /*pointer-events: none;*/
}

.rate:not(:checked) > input {
    position: absolute;
    top: -9999px;
}

.rate:not(:checked) > label {
    float: right;
    width: 1em;
    overflow: hidden;
    white-space: nowrap;
    cursor: pointer;
    font-size: 12px;
    color: #ccc;
}

.rate:not(:checked) > label:before { content: '★ '; }

.rate > input:checked ~ label { color: #ffc700; }

.rate:not(:checked) > label:hover, .rate:not(:checked) > label:hover ~ label { color: #deb217; }

.rate > input:checked + label:hover, .rate > input:checked + label:hover ~ label, .rate > input:checked ~ label:hover, .rate > input:checked ~ label:hover ~ label, .rate > label:hover ~ input:checked ~ label { color: #c59b08; }

<div class="rate">
    <input type="radio" id="v1_star5" name="rate1" value="5" />
    <label for="v1_star5" title="text">5 stars</label>
    <input type="radio" id="v1_star4" name="rate1" value="4" checked/>
    <label for="v1_star4" title="text">4 stars</label>
    <input type="radio" id="v1_star3" name="rate1" value="3" />
    <label for="v1_star3" title="text">3 stars</label>
    <input type="radio" id="v1_star2" name="rate1" value="2" />
    <label for="v1_star2" title="text">2 stars</label>
    <input type="radio" id="v1_star1" name="rate1" value="1" />
    <label for="v1_star1" title="text">1 star</label>
    </div>

   <div class="rate">
    <input type="radio" id="v2_star5" name="rate2" value="5" checked/>
    <label for="v2_star5" title="text">5 stars</label>
    <input type="radio" id="v2_star4" name="rate2" value="4" />
    <label for="v2_star4" title="text">4 stars</label>
    <input type="radio" id="v2_star3" name="rate2" value="3" />
    <label for="v2_star3" title="text">3 stars</label>
    <input type="radio" id="v2_star2" name="rate2" value="2" />
    <label for="v2_star2" title="text">2 stars</label>
    <input type="radio" id="v2_star1" name="rate2" value="1" />
    <label for="v2_star1" title="text">1 star</label>
    </div>

I've removed the pointer-events style so you can see the full end result.


问:
what is happening with my code when I try to insert my array ids?
I am trying to do a table for notifications using codeigniter and node.js for push notifications from database ,but however I did an array which contains my product ids from my session cart , but one I send them through my function looks like this on error output

```<code>INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES('low stock', 2, ('4169','4170','4173','4172','4175'), '1', 1499414552)
</code>```

how could I send all together , but not as I am sending I want to send my ids and then store them together with my notifications table  my code looks like  this

notifications function

```<code>public function index()
    {
        $this->session->carrito = $this->sale->checar_existe_carrito();
        $array = $this->sale->get_all_cart($this->session->carrito);
        $product_id = array();
        foreach ($array as $key => $value) {
             $product_id[] = $value['id'];
        }
        $this->json($product_id);
        $this->notification->addNotification('low stock', $product_id, $this->session->log['id'], 'low stock',now());
    }
</code>```

model

insert notifications

```<code>public function addNotification($message, $product_id, $user_id, $type = ''){
    $types = array('new' => 0, 'pending' => 1, 'low stock' => 2);
    if (isset($types[$type]) === false) {
        throw new \InvalidArgumentException('Value for third parameter must be one of new, pending, or low stock.');
    }
    $type = $types[$type];
    $timestamp = time();
    $query = "SELECT COUNT(*) AS notificationCount FROM storelte_notifications WHERE product_id IN ? AND type = ? ";
    $previousNotification = $this->db->query($query, array($product_id, $type))->result_array();
    if ($previousNotification[0]['notificationCount'] == 0) {
        $sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)";
        try {
            if ($this->db->query($sql, array($message, $type, $product_id, $user_id, $timestamp))) {
                return true;
            }else{
                return false;
            }
        } catch (Exception $e) {

        }
    }else{
        return true;
    }
}
</code>```

答:
Use a foreach loop:

```<code>$sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)";
try {
    foreach ($product_id as $pid) {
        if (!$this->db->query($sql, array($message, $type, $pid, $user_id, $timestamp))) {
            return false;
        }
    }
    return true;
} catch (Exception $e) {

}
</code>```

Body:
I am trying to do a table for notifications using codeigniter and node.js for push notifications from database ,but however I did an array which contains my product ids from my session cart , but one I send them through my function looks like this on error output

INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES('low stock', 2, ('4169','4170','4173','4172','4175'), '1', 1499414552)

how could I send all together , but not as I am sending I want to send my ids and then store them together with my notifications table  my code looks like  this

notifications function

public function index()
    {
        $this->session->carrito = $this->sale->checar_existe_carrito();
        $array = $this->sale->get_all_cart($this->session->carrito);
        $product_id = array();
        foreach ($array as $key => $value) {
             $product_id[] = $value['id'];
        }
        $this->json($product_id);
        $this->notification->addNotification('low stock', $product_id, $this->session->log['id'], 'low stock',now());
    }

model

insert notifications

public function addNotification($message, $product_id, $user_id, $type = ''){
    $types = array('new' => 0, 'pending' => 1, 'low stock' => 2);
    if (isset($types[$type]) === false) {
        throw new \InvalidArgumentException('Value for third parameter must be one of new, pending, or low stock.');
    }
    $type = $types[$type];
    $timestamp = time();
    $query = "SELECT COUNT(*) AS notificationCount FROM storelte_notifications WHERE product_id IN ? AND type = ? ";
    $previousNotification = $this->db->query($query, array($product_id, $type))->result_array();
    if ($previousNotification[0]['notificationCount'] == 0) {
        $sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)";
        try {
            if ($this->db->query($sql, array($message, $type, $product_id, $user_id, $timestamp))) {
                return true;
            }else{
                return false;
            }
        } catch (Exception $e) {

        }
    }else{
        return true;
    }
}

Body:
Use a foreach loop:

$sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)";
try {
    foreach ($product_id as $pid) {
        if (!$this->db->query($sql, array($message, $type, $pid, $user_id, $timestamp))) {
            return false;
        }
    }
    return true;
} catch (Exception $e) {

}


问:
Using a loop to create multiple dataframes from a single dataset
Quick question for you. I have the following:

```<code>a <- c(1,5,2,3,4,5,3,2,1,3)
b <- c("a","a","f","d","f","c","a","r","a","c")
c <- c(.2,.6,.4,.545,.98,.312,.112,.4,.9,.5)
df <- data.frame(a,b,c)
</code>```

What i am looking to do is utilize a for loop to create multiple data frames from rows based on the column contents of column B (i.e. a df for the "a," the "d," and so on).

At the same time, I would also like to name the data frame based on the corresponding value from column B (df will be named "a" for the data frame created from the "a."

I tried making it work based off the answers provided here Using a loop to create multiple data frames in R but i had no luck.

If it helps, I have variables created with levels() and nlevels() to use in the loop to keep it scalable based on how my data changes. Any help would be much appreciated.

Thanks!

答:
This should do:

```<code>require(dplyr)

df$b <- as.character(df$b)

col.filters <- unique(df$b)

lapply(seq_along(col.filters), function(x) {
  filter(df, b == col.filters[x])
  }
  ) -> list

names(list) <- col.filters

list2env(list, .GlobalEnv)
</code>```

Naturally, you don't need dplyr to do this. You can just use base syntax:

```<code>df$b <- as.character(df$b)

col.filters <- unique(df$b)

lapply(seq_along(col.filters), function(x) {
  df[df[, "b"] == col.filters[x], ]
  }
  ) -> list

names(list) <- col.filters

list2env(list, .GlobalEnv)
</code>```

But I find dplyrmuch more intuitive.

Cheers

Body:
Quick question for you. I have the following:

a <- c(1,5,2,3,4,5,3,2,1,3)
b <- c("a","a","f","d","f","c","a","r","a","c")
c <- c(.2,.6,.4,.545,.98,.312,.112,.4,.9,.5)
df <- data.frame(a,b,c)

What i am looking to do is utilize a for loop to create multiple data frames from rows based on the column contents of column B (i.e. a df for the "a," the "d," and so on).

At the same time, I would also like to name the data frame based on the corresponding value from column B (df will be named "a" for the data frame created from the "a."

I tried making it work based off the answers provided here Using a loop to create multiple data frames in R but i had no luck.

If it helps, I have variables created with levels() and nlevels() to use in the loop to keep it scalable based on how my data changes. Any help would be much appreciated.

Thanks!

Body:
This should do:

require(dplyr)

df$b <- as.character(df$b)

col.filters <- unique(df$b)

lapply(seq_along(col.filters), function(x) {
  filter(df, b == col.filters[x])
  }
  ) -> list

names(list) <- col.filters

list2env(list, .GlobalEnv)

Naturally, you don't need dplyr to do this. You can just use base syntax:

df$b <- as.character(df$b)

col.filters <- unique(df$b)

lapply(seq_along(col.filters), function(x) {
  df[df[, "b"] == col.filters[x], ]
  }
  ) -> list

names(list) <- col.filters

list2env(list, .GlobalEnv)

But I find dplyrmuch more intuitive.

Cheers


答: Just create a new text file named .hgignore at the root folder of your project and paste the content into it. </p>

Title: There is no .hgignore file after I do an initial hginit command

Body:
I've created my very first Mercurial repo on my machine. I used the hg init command on the directory.

Now I'm trying to use this ignore file, before uploading to BitBucket:

Mercurial .hgignore for Visual Studio 2008 projects

Where would I post Even Mien's configuration file? I can't find an hgignore file anywhere.

Thanks


问:
Cannot connect to http port on Azure Ubuntu VM
I have an Ubuntu VM running on Azure.  (Resource Manager rather than Classic)
I am running an application server on there (similar to Tomcat) that serves http on port 9001.

I created an Inbound rule to allow traffic on port 9001.

Also created an Outbound rule to allow traffic out on port 9001.

My application server is running (tested locally with curl).

When I try to test it remotely via http://:9001/somepath, the connection seems to be getting blocked.

I can successfully connect to this VM via SSH and SFTP

[update]  Here is my NSG.   This NSG is associated with the subnet of the VM.

NSG Image

答:
Please check your NSG settings, NSG is associated with the NIC & subnet, make sure you have add port 9001 to NSG inbound rules.

Please check your Ubuntu firewall settings, make sure you have allow port 9001.
Run this command to check it, sudo ufw status

Also, please check your application listening on port 9001, and bound IP same as 10.0.0.4or 0.0.0.0, if your application bound IP address is 127.0.0.1, it will work for localhost, we can't access it from outside. To check it, please run this command netstat -ant | grep 9001. like:

```<code>tcp        0      0 0.0.0.0:9001              0.0.0.0:*               LISTEN
</code>```

Update:

It is a NSG settings issue, please check your NSG settings:

1.subnet NSG, if the subnet associate with a NSG, we should add port 9001 to NSG inbound rules.

2.NSG settings:

Body:
Please check your NSG settings, NSG is associated with the NIC & subnet, make sure you have add port 9001 to NSG inbound rules.

Please check your Ubuntu firewall settings, make sure you have allow port 9001.
Run this command to check it, sudo ufw status

Also, please check your application listening on port 9001, and bound IP same as 10.0.0.4or 0.0.0.0, if your application bound IP address is 127.0.0.1, it will work for localhost, we can't access it from outside. To check it, please run this command netstat -ant | grep 9001. like:

tcp        0      0 0.0.0.0:9001              0.0.0.0:*               LISTEN

Update:

It is a NSG settings issue, please check your NSG settings:

1.subnet NSG, if the subnet associate with a NSG, we should add port 9001 to NSG inbound rules.

2.NSG settings:


问:
Dynamic panel Height based on screen size
How to get the panel height to increase dynamically based on screen size

```<code><div class="container-fluid">

<!--Heading-->
<div class="row " align="center">
    <h1 style="font-family: 'Roboto', sans-serif; font-size: 45px;"> Test Automation Inventory</h1>
</div>

<!--Table-->
<div class="row" >
    <div class="col-lg-12 col-md-12">
        <button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal" ng-click="Reset()"> Add New Test Details</button>
        <div class="panel panel-primary">
            <div class="panel-heading ">
                <h3 class=" panel-title pull-left" style="padding-top:7.5px">Test Automation Inventory</h3>

                <div class="input-group">
                    <input id="Special" type="text" class="form-control" placeholder="Search" autocomplete="off" focus ng-model="FilterItems">
                    <span class="input-group-btn">
                        <button class="btn btn-primary"><i class="glyphicon glyphicon-search"></i></button>
                    </span>
                </div>
            </div>
            <!-- style="overflow:auto; height:670px"-->
            <div class="panel-body scroll" style="overflow:auto; height:670px">

                <table class="table table-striped table-hover">

                    <tr ng-show="results.length==0">
                        <td style="vertical-align:middle;">No data found</td>
                    </tr>
                    <tr>
                        <th ng-repeat="c in columns" ng-click="ChangeOrder(c)">{{c.text}}</th>
                    </tr>
                    <tr class="animate-repeat" ng-repeat="Res in results | filter:FilterItems | orderBy: Column:reverse ">
                        <td> {{$index+1}}</td>
                        <td>{{Res.Test_Inventory_Group}}</td>
                        <td>{{Res.Test_Inventory_Application}}</td>
                        <td>{{Res.Test_Inventory_Count}}</td>
                        <td>
                            <button class="btn btn-danger">Delete Test</button>
                        </td>
                    </tr>

                </table>

            </div>
        </div>
    </div>
</div>
</code>```

I have a table inside panel body. where dynamically data would get added to it.
I want the panel to have scroll but it main page should not get the scroll.
The panel height to be [Windowheight - 10px]

Web page

I don't want the page to have scroll, I want only the panel to have scroll

答:
Try this css code:

```<code>.panel-body.scroll {  height: calc(100vh - 200px);  }
</code>```

Or

```<code><div class="panel-body scroll" style="overflow:auto; height: calc(100vh - 200px);">
</code>```

More details:

100vh is 100% viewport height/screen's height. See more.

calc is a calculator. In this case, it takes 100% of the screen's height and minuses 200px from it See more.

Body:
How to get the panel height to increase dynamically based on screen size

 Test Automation Inventory

        <button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal" ng-click="Reset()"> Add New Test Details</button>

Test Automation Inventory

                    <input id="Special" type="text" class="form-control" placeholder="Search" autocomplete="off" focus ng-model="FilterItems">

                        <button class="btn btn-primary"></button>

                        No data found

                        {{c.text}}

                         {{$index+1}}
                        {{Res.Test_Inventory_Group}}
                        {{Res.Test_Inventory_Application}}
                        {{Res.Test_Inventory_Count}}

                            <button class="btn btn-danger">Delete Test</button>

I have a table inside panel body. where dynamically data would get added to it.
I want the panel to have scroll but it main page should not get the scroll.
The panel height to be [Windowheight - 10px]

Web page

I don't want the page to have scroll, I want only the panel to have scroll

Body:
Try this css code:

.panel-body.scroll {  height: calc(100vh - 200px);  }

Or

<div class="panel-body scroll" style="overflow:auto; height: calc(100vh - 200px);">

More details:

100vh is 100% viewport height/screen's height. See more.

calc is a calculator. In this case, it takes 100% of the screen's height and minuses 200px from it See more.


问:
Drop/ Delete Database in Teradata
Please help with direction on how to drop a database in Teradata.

When I run the command DROP DATABASE database_name, I get the error message:

```<code>*** Failure 3552 Cannot DROP databases with tables, journal tables,
views, macros, or zones.
            Statement# 1, Info =0
*** Total elapsed time was 1 second.
</code>```

答:
You need to run this command first to delete all of the objects in the database:

```<code>DELETE DATABASE database_name;
</code>```

In order to drop a database with journal tables:

```<code>MODIFY DATABASE database_name AS DROP DEFAULT JOURNAL TABLE;
</code>```

Then run,

```<code>DROP DATABASE database_name
</code>```

to delete the database in Teradata

Title: Drop/ Delete Database in Teradata

Body:
Please help with direction on how to drop a database in Teradata.

When I run the command DROP DATABASE database_name, I get the error message:

*** Failure 3552 Cannot DROP databases with tables, journal tables,
views, macros, or zones.
            Statement# 1, Info =0
*** Total elapsed time was 1 second.

Body:
You need to run this command first to delete all of the objects in the database:

DELETE DATABASE database_name;

In order to drop a database with journal tables:

MODIFY DATABASE database_name AS DROP DEFAULT JOURNAL TABLE;

Then run,

DROP DATABASE database_name

to delete the database in Teradata


问:
Star rating using Font Awesome doesn't work properly on Edge and IE
The star rating using Font Awesome defined by width provided below is working fine on Chrome and Firefox, but on Edge and IE doesn't. Anyone know what could it be?

JSFiddle

Chrome and Firefox

Edge and IE

.star-rating {
  display: inline-block;
  position: relative;
  line-height: 1;
}
.star-rating:before,
.star-rating:after {
  content: "\f005\f005\f005\f005\f005";
  display: block;
  font-family: "FontAwesome";
  font-size: 25px;
  color: #ccc;
}
.star-rating:after {
  color: gold;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
}

.star-rating.s0:after {
  width: 0%;
}
.star-rating.s1:after {
  width: 10%;
}
.star-rating.s2:after {
  width: 20%;
}
.star-rating.s3:after {
  width: 30%;
}
.star-rating.s4:after {
  width: 40%;
}
.star-rating.s5:after {
  width: 50%;
}
.star-rating.s6:after {
  width: 60%;
}
.star-rating.s7:after {
  width: 70%;
}
.star-rating.s8:after {
  width: 80%;
}
.star-rating.s9:after {
  width: 90%;
}
.star-rating.s10:after {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<span class="star-rating s7"></span></code>```

答:
This is a bug that the M$ browser has when dealing with pseudo elements. The workaround is:

```<code> .star-rating {overflow: hidden;}
</code>```

Under a browser that is designed to comply to standards (i.e. real browsers such as Chrome and Firefox), just having .star-rating::after is good enough. Unfortunately, M$ browsers are garbage.

Check the styles in the developer tools and you'll see that all of the pseudo elements ::before and ::after are crossed out. This is one of the many bugs IE is infested with. Here are the symptoms:

The developer tools have all of the pseudo element styles crossed out

Although the styles look like they are disabled according to the developer tool, the majority of them are not.

If there is a behavior that is unique to only IE and/or Edge, then the bug's secondary side effect has manifested. There are style properties that are ignored when applied to a pseudo element when the parent element doesn't implicitly have the property itself.

Issue: In OP's specific case, the pseudo element: .star-rating::after property: overflow: hidden was ignored because IE requires the parent: .star-rating to have it as well.

  Workaround: Apply overflow: hidden to .star-rating

Demo (tested in Chrome, Firefox, and IE)

.star-rating {
  display: inline-block;
  position: relative;
  line-height: 1;
  overflow: hidden;
}
.star-rating:before,
.star-rating:after {
  content: "\f005\f005\f005\f005\f005";
  display: block;
  font-family: "FontAwesome";
  font-size: 25px;
  color: #ccc;
}
.star-rating:after {
  color: gold;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
}

.star-rating.s0:after {
  width: 0%;
}
.star-rating.s1:after {
  width: 10%;
}
.star-rating.s2:after {
  width: 20%;
}
.star-rating.s3:after {
  width: 30%;
}
.star-rating.s4:after {
  width: 40%;
}
.star-rating.s5:after {
  width: 50%;
}
.star-rating.s6:after {
  width: 60%;
}
.star-rating.s7:after {
  width: 70%;
}
.star-rating.s8:after {
  width: 80%;
}
.star-rating.s9:after {
  width: 90%;
}
.star-rating.s10:after {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<span class="star-rating s7"></span></code>```

Body:
The star rating using Font Awesome defined by width provided below is working fine on Chrome and Firefox, but on Edge and IE doesn't. Anyone know what could it be?

JSFiddle

Chrome and Firefox

Edge and IE

.star-rating {
  display: inline-block;
  position: relative;
  line-height: 1;
}
.star-rating:before,
.star-rating:after {
  content: "\f005\f005\f005\f005\f005";
  display: block;
  font-family: "FontAwesome";
  font-size: 25px;
  color: #ccc;
}
.star-rating:after {
  color: gold;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
}

.star-rating.s0:after {
  width: 0%;
}
.star-rating.s1:after {
  width: 10%;
}
.star-rating.s2:after {
  width: 20%;
}
.star-rating.s3:after {
  width: 30%;
}
.star-rating.s4:after {
  width: 40%;
}
.star-rating.s5:after {
  width: 50%;
}
.star-rating.s6:after {
  width: 60%;
}
.star-rating.s7:after {
  width: 70%;
}
.star-rating.s8:after {
  width: 80%;
}
.star-rating.s9:after {
  width: 90%;
}
.star-rating.s10:after {
  width: 100%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Body:
This is a bug that the M$ browser has when dealing with pseudo elements. The workaround is:

 .star-rating {overflow: hidden;}

Under a browser that is designed to comply to standards (i.e. real browsers such as Chrome and Firefox), just having .star-rating::after is good enough. Unfortunately, M$ browsers are garbage.

Check the styles in the developer tools and you'll see that all of the pseudo elements ::before and ::after are crossed out. This is one of the many bugs IE is infested with. Here are the symptoms:

The developer tools have all of the pseudo element styles crossed out

Although the styles look like they are disabled according to the developer tool, the majority of them are not.

If there is a behavior that is unique to only IE and/or Edge, then the bug's secondary side effect has manifested. There are style properties that are ignored when applied to a pseudo element when the parent element doesn't implicitly have the property itself.

Issue: In OP's specific case, the pseudo element: .star-rating::after property: overflow: hidden was ignored because IE requires the parent: .star-rating to have it as well.

  Workaround: Apply overflow: hidden to .star-rating

Demo (tested in Chrome, Firefox, and IE)

.star-rating {
  display: inline-block;
  position: relative;
  line-height: 1;
  overflow: hidden;
}
.star-rating:before,
.star-rating:after {
  content: "\f005\f005\f005\f005\f005";
  display: block;
  font-family: "FontAwesome";
  font-size: 25px;
  color: #ccc;
}
.star-rating:after {
  color: gold;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
}

.star-rating.s0:after {
  width: 0%;
}
.star-rating.s1:after {
  width: 10%;
}
.star-rating.s2:after {
  width: 20%;
}
.star-rating.s3:after {
  width: 30%;
}
.star-rating.s4:after {
  width: 40%;
}
.star-rating.s5:after {
  width: 50%;
}
.star-rating.s6:after {
  width: 60%;
}
.star-rating.s7:after {
  width: 70%;
}
.star-rating.s8:after {
  width: 80%;
}
.star-rating.s9:after {
  width: 90%;
}
.star-rating.s10:after {
  width: 100%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<span class="star-rating s7"></span>


问:
How to Join Tables with Empty Rows?
How do you return all rows from Table A, if you joined Table B, Table C, etc and each table joined may not have a matching record?

Example:

```<code>Table A         Table B         Table C
Row Letter      Row Shelter     Row Food
1   A           1   House       1   Bread
2   B           2   Shed        2   Cheese
3   C           3   Tent        3   Meat
4   D           4   Patio
5   E
</code>```

Results

```<code>Row Letter  Shelter Food
1   A       House   Bread
2   B       Shed    Cheese
3   C       Tent    Meat
4   D       Patio
5   E
</code>```

My query reduces the results based on each table that does not have a matching value, meaning no entry exists for that item.

答:
Use Outer Joins

```<code>select *
From TableA a
Left Join TableB b on a.Row = b.Row
Left Join TableC c on a.Row = c.Row
</code>```

Left Join will bring all the records from left table even though there is no matching record present in right table

Title: How to Join Tables with Empty Rows?

Body:
How do you return all rows from Table A, if you joined Table B, Table C, etc and each table joined may not have a matching record?

Example:

Table A         Table B         Table C
Row Letter      Row Shelter     Row Food
1   A           1   House       1   Bread
2   B           2   Shed        2   Cheese
3   C           3   Tent        3   Meat
4   D           4   Patio
5   E

Results

Row Letter  Shelter Food
1   A       House   Bread
2   B       Shed    Cheese
3   C       Tent    Meat
4   D       Patio
5   E

My query reduces the results based on each table that does not have a matching value, meaning no entry exists for that item.

Body:
Use Outer Joins

select *
From TableA a
Left Join TableB b on a.Row = b.Row
Left Join TableC c on a.Row = c.Row

Left Join will bring all the records from left table even though there is no matching record present in right table


问:
IIS 7.5 URL Rewrite: Redirect Rule does not appear to work from old domain to new domain
I am trying to understand why the following rule created in IIS is not working when a person tries to enter the site.

Basically we have an old domain and a new domain. I would like anyone going to the old domain to be redirected to a landing page on our new domain.

I am using ASP MVC4 for the site and I have added bindings for the domains and updated DNS as well.

My rule is:

```<code>               <rule name="http://www.olddomain.com to landing page" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <action type="Redirect" url="http://www.new-domain.co.uk/LandingPage" />
                <conditions logicalGrouping="MatchAny">
                    <add input="{HTTP_HOST}" pattern="http://www.olddomain.com" />
                    <add input="{HTTP_HOST}" pattern="http://olddomain.com" />
                    <add input="{HTTP_HOST}" pattern="http://www.olddomain.com/" />
                    <add input="{HTTP_HOST}" pattern="http://olddomain.com/" />
                </conditions>
            </rule>
</code>```

At the moment if someone enters the old domain address the redirect does not do anything, the website just loads as if you were entering via the new domain to the home page.

Can someone tell me where I am going wrong here?

UPDATE
The rule provided below still does not seem to work so I decided to just try and open my olddomain address in fiddler to see if I could see the redirect or response. All I get is a 200 HTTP response and nothing more. This makes me think that the rewrite rules are actually being ignored but I have no idea why.

答:
I had struggled on this for several days. 10-20 rewrite rule I tried and  reasons of failure are:

If you trying redirecting in VisualStudio(2012/2013/2015) it could not work in actual IIS hosted site as VS generates its own cert while debugging(when you specify in project properties) as well as permission issues are taken care by VS.

The site in IIS should have valid(no copy paste of file from thawte/verisign enabled website or even self signed generated by snk.exe) certificate; please dont assume that without valid cert you can. (self signed(also known as dev cert) in IIS 8 and 10 worked for me; difference between purchased and self signed is here https://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-in-iis-7.html). The certificate should be installed as IIS can have multiple certs but each web site should use its own separate cert.

The site bindings should have both http(80) and https(443)

Now redirection syntax comes in picture; several are out there on Internet; you can get the correct regular expression easily

Another side of story also has to be considered that redirecting can be handle using Global.asax->Application_BeginRequest or ActionFilter in MVC 4/5.
Doing redirection using config or programmatically can lead to different errors(TOO_MANY_REDIRECTS,    in web.config)

Another gotcha I faced is redirecting from http->https is working fine but I am not able to comeback from https->http;

Consider your scenario(and generally should not mix) out of the available choices

HttpRedirect:

```<code>Request 1 (from client):    Get file.htm
Response 1 (from server): The file is moved, please request the file newFileName.htm
Request 2 (from client):    Get newFileName.htm
Response 2 (from server): Here is the content of newFileName.htm
</code>```

UrlRewrite:

```<code>Request 1 (from client):     Get file.htm
URL Rewriting (on server):   Translate the URL file.htm to file.asp
Web application (on server): Process the request (run any code in file.asp)
Response 1 (from server):    Here is the content of file.htm (note that the client does not know that this is the content of file.asp)
whether you need HttpRedirect or UrlRewrite
https://weblogs.asp.net/owscott/rewrite-vs-redirect-what-s-the-difference
</code>```

Body:
I am trying to understand why the following rule created in IIS is not working when a person tries to enter the site.

Basically we have an old domain and a new domain. I would like anyone going to the old domain to be redirected to a landing page on our new domain.

I am using ASP MVC4 for the site and I have added bindings for the domains and updated DNS as well.

My rule is:

               <rule name="http://www.olddomain.com to landing page" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <action type="Redirect" url="http://www.new-domain.co.uk/LandingPage" />
                <conditions logicalGrouping="MatchAny">
                    <add input="{HTTP_HOST}" pattern="http://www.olddomain.com" />
                    <add input="{HTTP_HOST}" pattern="http://olddomain.com" />
                    <add input="{HTTP_HOST}" pattern="http://www.olddomain.com/" />
                    <add input="{HTTP_HOST}" pattern="http://olddomain.com/" />
                </conditions>
            </rule>

At the moment if someone enters the old domain address the redirect does not do anything, the website just loads as if you were entering via the new domain to the home page.

Can someone tell me where I am going wrong here?

UPDATE
The rule provided below still does not seem to work so I decided to just try and open my olddomain address in fiddler to see if I could see the redirect or response. All I get is a 200 HTTP response and nothing more. This makes me think that the rewrite rules are actually being ignored but I have no idea why.

Body:
I had struggled on this for several days. 10-20 rewrite rule I tried and  reasons of failure are:

If you trying redirecting in VisualStudio(2012/2013/2015) it could not work in actual IIS hosted site as VS generates its own cert while debugging(when you specify in project properties) as well as permission issues are taken care by VS.

The site in IIS should have valid(no copy paste of file from thawte/verisign enabled website or even self signed generated by snk.exe) certificate; please dont assume that without valid cert you can. (self signed(also known as dev cert) in IIS 8 and 10 worked for me; difference between purchased and self signed is here https://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-in-iis-7.html). The certificate should be installed as IIS can have multiple certs but each web site should use its own separate cert.

The site bindings should have both http(80) and https(443)

Now redirection syntax comes in picture; several are out there on Internet; you can get the correct regular expression easily

Another side of story also has to be considered that redirecting can be handle using Global.asax->Application_BeginRequest or ActionFilter in MVC 4/5.
Doing redirection using config or programmatically can lead to different errors(TOO_MANY_REDIRECTS,    in web.config)

Another gotcha I faced is redirecting from http->https is working fine but I am not able to comeback from https->http;

Consider your scenario(and generally should not mix) out of the available choices

HttpRedirect:

Request 1 (from client):    Get file.htm
Response 1 (from server): The file is moved, please request the file newFileName.htm
Request 2 (from client):    Get newFileName.htm
Response 2 (from server): Here is the content of newFileName.htm

UrlRewrite:

Request 1 (from client):     Get file.htm
URL Rewriting (on server):   Translate the URL file.htm to file.asp
Web application (on server): Process the request (run any code in file.asp)
Response 1 (from server):    Here is the content of file.htm (note that the client does not know that this is the content of file.asp)
whether you need HttpRedirect or UrlRewrite
https://weblogs.asp.net/owscott/rewrite-vs-redirect-what-s-the-difference

ContentLicense: CC BY-SA 4.0


问:
Binding Web Application, Site Collection, Sites and Library data to a Sharepoint 2007 dropdown list in a web part
A. I'd like to know the best way to retrieve the web applications, site collections, sites and libraries of a SharePoint 2007 install (on a farm) and display each of those data in a dropdown list of their own a web part.

B. What type of web part should be used

C. What object model or database/tables do I get those pieces of information from

For example:

"Web Applications" Dropdownlist1

"Site Collections" Dropdownlist2

"Sites" Dropdownlist3

"Libraries" in a scrollable Textarea

答:
```<code>SPFarm farm = SPFarm.Local;
            SPWebService service = farm.Services.GetValue<SPWebService>("");
            foreach (SPWebApplication webapp in service.WebApplications)
            {
                foreach (SPSite sitecoll in webapp.Sites)
                {
                    foreach (SPWeb web in sitecoll.AllWebs)
                    {
                        <<Use recursion here to Get sub WebS>>
                        web.Dispose();
                    }

                    sitecoll.Dispose();

                }

            }
</code>```

<p>the above code sample provides code to find listing of all webs in a spfarm you can use the above sample to find all webapplication, sitecollection, webs, use SPListto get all list item from splistcollection available in SPweb.lists </p>

Body:
SPFarm farm = SPFarm.Local;
            SPWebService service = farm.Services.GetValue<SPWebService>("");
            foreach (SPWebApplication webapp in service.WebApplications)
            {
                foreach (SPSite sitecoll in webapp.Sites)
                {
                    foreach (SPWeb web in sitecoll.AllWebs)
                    {
                        <<Use recursion here to Get sub WebS>>
                        web.Dispose();
                    }

                    sitecoll.Dispose();

                }

            }

the above code sample provides code to find listing of all webs in a spfarm you can use the above sample to find all webapplication, sitecollection, webs, use SPListto get all list item from splistcollection available in SPweb.lists


问:
Can I set listen URLs in appsettings.json in ASP.net Core 2.0 Preview?
I'm creating an ASP.net Core 2.0 app to run on the .net Core 2.0 runtime, both currently in their Preview versions. However, I cannot figure out how to have Kestrel use something other than the default http://localhost:5000 listen URL.

Most documentation that I could Google talks about a server.urls setting, which seems to have been changed even in 1.0-preview to just be urls, however neither works (turning on Debug logging has Kestrel telling me that no listen endpoints are configured).

A lot of documentation also talks about a hosting.json and that I can't use the default appsettings.json. However, if I compare the recommended approach of loading a new config, this looks pretty much exactly like what the new WebHost.CreateDefaultBuilder method does, except that it loads appsettings.json.

I currently don't understand how appsettings.json and IConfigureOptions<T> are related, if at all, so it's possible that my trouble stems from a lack of understanding of what KestrelServerOptionsSetup actually does.

答:
Works for me as it used to be

```<code>WebHost.CreateDefaultBuilder(args)
    .UseConfiguration( new ConfigurationBuilder().AddCommandLine(args).Build() )
    .UseStartup<Startup>()
    .Build();
</code>```

Then

```<code>dotnet myapp.dll --urls "http://*:5060;"
</code>```

Body:
Works for me as it used to be

WebHost.CreateDefaultBuilder(args)
    .UseConfiguration( new ConfigurationBuilder().AddCommandLine(args).Build() )
    .UseStartup<Startup>()
    .Build();

Then

dotnet myapp.dll --urls "http://*:5060;"


问:
How can I limit the length of a text field input in flutter?
The TextField widget doesn't seem to have a "limit" attribute to limit the number of characters that can be typed. How I can enforce that only a certain number of characters can be provided as input in a TextField Widget. I tried looking at the decoration property and potentially setting the limit there somehow but that didn't seem to work either. Is there a different widget I should be using?</p>

答:
You can control everything about the Text Field with the TextEditingController. So if you were to pair this information with an onChanged event from the TextField you could perform any logic you like in there. For example:

```<code>TextEditingController _controller = new TextEditingController();
String text = ""; // empty string to carry what was there before it onChanged
int maxLength = ...
...
new TextField(
    controller: _controller,
    onChanged: (String newVal) {
        if(newVal.length <= maxLength){
            text = newVal;
        }else{
            _controller.text = text;
        }

    }
)
</code>```

I am able to control the text field to stay within the guidelines because if it ever goes over it, it will revert to what it was before the last type.

Body:
You can control everything about the Text Field with the TextEditingController. So if you were to pair this information with an onChanged event from the TextField you could perform any logic you like in there. For example:

TextEditingController _controller = new TextEditingController();
String text = ""; // empty string to carry what was there before it onChanged
int maxLength = ...
...
new TextField(
    controller: _controller,
    onChanged: (String newVal) {
        if(newVal.length <= maxLength){
            text = newVal;
        }else{
            _controller.text = text;
        }

    }
)

I am able to control the text field to stay within the guidelines because if it ever goes over it, it will revert to what it was before the last type.