问:
Order By TableName and columnname
Lets say I have a table with following columns:

```<code>Id,TableName,Columnname
</code>```

Normally If I would like to do a select with ordering on TableName Primary and ColumnName secondary I would do

```<code>Select * From MyTable Order By TableName,ColumnName
</code>```

Now say I would like a special case of ordering depending on TableName

```<code>Select * From MyTable Order By Case
When TableName = 'Foo' Then '1'
When TableName = 'Bar' Then '2'
When TableName = 'Test' Then '3'
ELSE 1000 END;
</code>```

How do I combine the second alternative with the first alternative, that is special ordering on first TableName and then order the Columnnames with that TableName?

I'm running Microsoft SQL

Thanks in advance.

答:
The case method is fine.  I would often use this short-cut:

```<code>Select *
From MyTable
Order By charindex(TableName, ',Test,Bar,Foo,') desc
</code>```

This is a wee bit arcane.  charindex() returns the position of the name in the string.  So, this form will not work for all string values, but it can be generalized:

```<code>Order By charindex(',' + TableName + ',', ',Test,Bar,Foo,') desc
</code>```

The reversal of the list is to handle missing values.  These are assigned a value of 0, so by putting the values in reverse order, the missing ones come last.  Note that if I know all the values, then I would write this as:

```<code>Order By charindex(TableName, ',Foo,Bar,Test,') asc
</code>```

Title: Order By TableName and columnname

Body:
Lets say I have a table with following columns:

Id,TableName,Columnname

Normally If I would like to do a select with ordering on TableName Primary and ColumnName secondary I would do

Select * From MyTable Order By TableName,ColumnName

Now say I would like a special case of ordering depending on TableName

Select * From MyTable Order By Case
When TableName = 'Foo' Then '1'
When TableName = 'Bar' Then '2'
When TableName = 'Test' Then '3'
ELSE 1000 END;

How do I combine the second alternative with the first alternative, that is special ordering on first TableName and then order the Columnnames with that TableName?

I'm running Microsoft SQL

Thanks in advance.

Body:
The case method is fine.  I would often use this short-cut:

Select *
From MyTable
Order By charindex(TableName, ',Test,Bar,Foo,') desc

This is a wee bit arcane.  charindex() returns the position of the name in the string.  So, this form will not work for all string values, but it can be generalized:

Order By charindex(',' + TableName + ',', ',Test,Bar,Foo,') desc

The reversal of the list is to handle missing values.  These are assigned a value of 0, so by putting the values in reverse order, the missing ones come last.  Note that if I know all the values, then I would write this as:

Order By charindex(TableName, ',Foo,Bar,Test,') asc


来源: stackexchange

问:
Creating a custom transport connector in mule
I am attempting to create a custom transport in mule. I have followed the standard tutorial in mule and created the skeleton project.

Being a newcomer to mule, I am struggling to understand how to proceed from there. I would appreciate if you could help me answer the below questions:

I am attempting to create a custom protocol transport, does this mean I have to create my own inbound/outbound endpoints?

How to register the inbound/outbound and global endpoints?

How to use the NamespaceHandler to register the endpoints?

How to create transacted messages?

Is it possible to have more than one MessageReceiver based on the type of connection selected by the user?

答:
Once look into the below url for developing custom connector with step-by-step procedure. And in that connector java class we can define more operations with @Processor as per the requirement.

http://www.vanrish.com/blog/2016/09/28/mulesoft-connector-devkit-coding-deployment/

Regards,
Murali

ContentLicense: CC BY-SA 3.0


问:
Can I send an ACK response to a successfully received SYNACK using BSD raw sockets?
My code tries to manually establish a TCP handshaking, and then, it sends a data segment requesting a resource via HTTP GET.

I'm using raw sockets to craft the headers and send the packets, and libpcap in order to check for the received packet headers.

The SYN is successfully sent to the receiver, who then replies me with a SYNACK. At this point so far it works, but when I receive that SYNACK, I try to ACK it, and then send HTTP GET next, which doesn't look to work. I can see the headers are ok in wireshark.

So my questions are: can i ACK the SYNACK via raw sockets just as I receive it using the same socket I used to send the SYN? And is there any required OPTIONS to go along with the headers in order to accomplish that?

I'm ACKing that SYNACK, and just after that I send a segment with ACK and PSH flags set in order to request a resource via HTTP. I can see them both on wireshark, but I don't get a response from the server.

答: There's no reason you can't ACK using raw sockets, however your OS's kernel stack will also see the received SYNACK which it isn't expecting and send a RST. Are you doing anything to prevent that from happening? Otherwise, maybe you aren't sending the right SEQ/ACK numbers.

ContentLicense: CC BY-SA 2.5


问:
React Sortable Ordering Issue

As you can see in the GIF while ordering items in the list seems that the placeholder element get overlapped by the others. My code logic it's quite equal to the example.

The grey background it's an absolute positioned element.

This is my actual code:

```<code>const DragHandleElement = SortableHandle(() => <span style={handleStyle} ><DragHandle /></span>);

const SortableItem = SortableElement(({content}) => {
  return (
    <div style={menuItemStyle}>
      <DragHandleElement />
      <div style={menuContentStyle}>
        {Utils.getMainDesc(content)}
      </div>
    </div>
  );
});

class VirtualList extends Component {
  render() {
    let {items} = this.props;

    return (
      <AutoSizer>
        {({ width, height }) => (
          <List
            ref={(instance) => {
              console.log(instance);
              this.List = instance;
            }}
            rowHeight={80}
            rowRenderer={({index}) => {
              let {content} = items[index];
              return <SortableItem key={'sort_item_'+index} index={index} content={content} />;
            }}
            rowCount={items.length}
            height={height}
            width={width}
          />
        )}
      </AutoSizer>
    );
  }
}

const SortableList = SortableContainer(VirtualList, {withRef: true});

<SortableList
  ref={(instance) => {
    this.SortableList = instance;
  }}
  lockAxis='y'
  useDragHandle={true}
  items={menu.content}
  onSortEnd={({oldIndex, newIndex}) => this.props.onSortEnd(oldIndex, newIndex, this.SortableList)}
  helperClass={'higher'}
/>
</code>```

答:
As im using the sortable component inside an absolute positioned element it needs a reference to the container. Adding the getContainer prop solved my problem:</p>

```<code><SortableList
  ....
  getContainer={() => {
    return ReactDOM.findDOMNode(this.refs['menu'])
  }}
/>
</code>```

Title: React Sortable Ordering Issue

Body:
As you can see in the GIF while ordering items in the list seems that the placeholder element get overlapped by the others. My code logic it's quite equal to the example.

The grey background it's an absolute positioned element.

This is my actual code:

const DragHandleElement = SortableHandle(() => <DragHandle />);

const SortableItem = SortableElement(({content}) => {
  return (

      <DragHandleElement />

        {Utils.getMainDesc(content)}

  );
});

class VirtualList extends Component {
  render() {
    let {items} = this.props;

    return (
      <AutoSizer>
        {({ width, height }) => (
          <List
            ref={(instance) => {
              console.log(instance);
              this.List = instance;
            }}
            rowHeight={80}
            rowRenderer={({index}) => {
              let {content} = items[index];
              return <SortableItem key={'sort_item_'+index} index={index} content={content} />;
            }}
            rowCount={items.length}
            height={height}
            width={width}
          />
        )}
      </AutoSizer>
    );
  }
}

const SortableList = SortableContainer(VirtualList, {withRef: true});

<SortableList
  ref={(instance) => {
    this.SortableList = instance;
  }}
  lockAxis='y'
  useDragHandle={true}
  items={menu.content}
  onSortEnd={({oldIndex, newIndex}) => this.props.onSortEnd(oldIndex, newIndex, this.SortableList)}
  helperClass={'higher'}
/>

Body:
As im using the sortable component inside an absolute positioned element it needs a reference to the container. Adding the getContainer prop solved my problem:

<SortableList
  ....
  getContainer={() => {
    return ReactDOM.findDOMNode(this.refs['menu'])
  }}
/>


问:
If condition wrongly working
The Following PHP if condition statement is processing wrong and is not working.

File $fname has text values: "990,1000" with a comma in between:

```<code>$myfile = fopen($fname, "r") or die("<script
type='text/javascript'>window.location.href =
'http://www.autorekrooter.com/activation.html';</script>");
$dt=fread($myfile,filesize($fname));
//File fname has values: "990, 1000"
fclose($myfile);
$myArray = explode(',', $dt);
//Now checking if Limit expired or not?
echo "<br>myArray[0] values is: " . $myArray[0] . " myArray[1] value is: " .
$myArray[1];
if ($myArray[0]>=$myArray[1]){
echo "<script>alert('You can't proceed further');</script>";
//echo "<script type='text/javascript'>window.location.href = 'register.html';</script>";
exit();
}
else{
echo "<script type='text/javascript'>window.location.href =
'gui.php';</script>";
echo "You can proceed";
exit();
}
</code>```

When I run the above in a php file the if statement always takes value of myArray[0] >= myArray[1] as true and show the reigster.html whereas in the $fname file it is 990,1000 myArray[0]=990 and myArray[1]=1000 so myArray[0] should not be greater than myArray[1] and the else statement should run but the opposite is happening.

Any suggestions as to why this is not working?

Many Thanks in advance for your answers.

答:
You probably have a newline (\n or \r\n) at the end of your file ($myfile). So myArray[1] actually looks like "1000\n".

var_dump("990" >= "1000\n"); returns bool(true).

You're comparing strings that PHP can't convert to numbers so you get an unexpected result.

Title: If condition wrongly working

Body:
The Following PHP if condition statement is processing wrong and is not working.

File $fname has text values: "990,1000" with a comma in between:

$myfile = fopen($fname, "r") or die("");
$dt=fread($myfile,filesize($fname));
//File fname has values: "990, 1000"
fclose($myfile);
$myArray = explode(',', $dt);
//Now checking if Limit expired or not?
echo "
myArray[0] values is: " . $myArray[0] . " myArray[1] value is: " .
$myArray[1];
if ($myArray[0]>=$myArray[1]){
echo "";
//echo "";
exit();
}
else{
echo "";
echo "You can proceed";
exit();
}

When I run the above in a php file the if statement always takes value of myArray[0] >= myArray[1] as true and show the reigster.html whereas in the $fname file it is 990,1000 myArray[0]=990 and myArray[1]=1000 so myArray[0] should not be greater than myArray[1] and the else statement should run but the opposite is happening.

Any suggestions as to why this is not working?

Many Thanks in advance for your answers.


问:
Ruby on Rails 4.2, stack level too deep, associations and delegate()
I understand the cause of a Stack Level Too Deep error. I am failing to spot where/why it is occurring in my code base.

I've implemented a multi-model, multi-step wizard. The first two models (User and Company) are working, it is when I attempt to add in the third (Address) I get the error.

I suspect the error is related to the associations between the models, although I've failed to debug.

The code snippets below function correctly except when I add the 3 lines (marked with comments in the snippet) too the file app/wizards/user_wizard/step1.rb.

Relevant Models

app/models/company.rb

```<code>class Company < ActiveRecord::Base
  include Validatable::Company

  # Associations:
  has_many :addresses, inverse_of: :company
  accepts_nested_attributes_for :addresses, reject_if: :all_blank

  has_many :employees, inverse_of: :company
  accepts_nested_attributes_for :employees, reject_if: :all_blank

  has_many :licenses, inverse_of: :company
  accepts_nested_attributes_for :licenses, reject_if: :all_blank

  has_many :vehicles, inverse_of: :company
  accepts_nested_attributes_for :vehicles, reject_if: :all_blank

  has_one :user, inverse_of: :company
end
</code>```

app/models/address.rb

```<code>class Address < ActiveRecord::Base
  # Associations:
  belongs_to :company, inverse_of: :addresses

  has_many :licenses, inverse_of: :address
  accepts_nested_attributes_for :licenses, reject_if: :all_blank

  has_many :initial_analyses, inverse_of: :address
  accepts_nested_attributes_for :initial_analyses, reject_if: :all_blank
end
</code>```

app/models/user.rb

```<code>class User < ActiveRecord::Base
  include SoftDeletable
  include Validatable::User

  # Constants:
  MARKER_ATTRIBUTES = %w[user_name].freeze # get marked with '(deleted)'
  DEPENDANT_CHILDREN = %w[none].freeze # child resources to be deleted

  # Associations:
  belongs_to :role, inverse_of: :users

  belongs_to :company, inverse_of: :user
  accepts_nested_attributes_for :company, reject_if: :all_blank

  has_many :auto_quotes, inverse_of: :user
end
</code>```

db/schema.rb

```<code>ActiveRecord::Schema.define(version: 20170616131833) do

  create_table "addresses", force: :cascade do |t|
    t.integer  "company_id"
    t.text     "site_name"
    t.string   "premises_code"
    t.string   "exempt_premises_code"
    t.text     "address"
    t.string   "city"
    t.string   "county"
    t.string   "sic_code"
    t.string   "postcode"
    t.string   "country"
    t.boolean  "sic_update"
    t.boolean  "deleted",              default: false
    t.datetime "created_at",                           null: false
    t.datetime "updated_at",                           null: false
    t.datetime "deleted_at"
  end

  create_table "companies", force: :cascade do |t|
    t.string   "company_name"
    t.string   "registration_number"
    t.string   "type_of_business"
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
    t.datetime "deleted_at"
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.integer  "failed_attempts",        default: 0,  null: false
    t.string   "unlock_token"
    t.datetime "locked_at"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "user_name"
    t.datetime "deleted_at"
    t.integer  "role_id"
    t.integer  "company_id"
    t.string   "invitation_token"
    t.datetime "invitation_created_at"
    t.datetime "invitation_sent_at"
    t.datetime "invitation_accepted_at"
    t.integer  "invitation_limit"
    t.integer  "invited_by_id"
    t.string   "invited_by_type"
    t.integer  "invitations_count",      default: 0
  end

  add_index "users", ["company_id"], name: "index_users_on_company_id", unique: true
  add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["invitation_token"], name: "index_users_on_invitation_token", unique: true
  add_index "users", ["invitations_count"], name: "index_users_on_invitations_count"
  add_index "users", ["invited_by_id"], name: "index_users_on_invited_by_id"
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  add_index "users", ["unlock_token"], name: "index_users_on_unlock_token", unique: true
end
</code>```

Wizards

app/wizards/user_wizard/base.rb

```<code>module UserWizard
  class Base
    include ActiveModel::Model

    STEPS = %w[step1 step2].freeze

    attr_accessor :user

    delegate(*::User.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :user)

    def initialize(user_attributes)
      @user = ::User.new(user_attributes)
    end
  end
end
</code>```

app/wizards/user_wizard/step1.rb

```<code>module UserWizard
  class Step1 < UserWizard::Base
    include Validatable::Company

    attr_accessor :company

    # One of 3 lines triggering circular reference by adding in Address model
    attr_accessor :address

    delegate(*::Company.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :company)

    # One of 3 lines triggering circular reference by adding in Address model
    delegate(*::Address.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :address)

    def initialize(user_attributes)
      super

      @company = @user.build_company

      # One of 3 lines triggering circular reference by adding in Address model
      @address = @user.company.addresses.build
    end
  end
end
</code>```

app/wizards/user_wizard/step2.rb

ommitted as it is irrelevant. code fails before ever instantiating this class

答:
address has an address attribute. So the delegate method is trying to create a method address that will be delegated to address.

I'd suggest this:

```<code>module UserWizard
  class Step1 < UserWizard::Base
    include Validatable::Company

    attr_accessor :company

    # One of 3 lines triggering circular reference by adding in Address model
    attr_accessor :company_address

    delegate(*::Company.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :company)

    # One of 3 lines triggering circular reference by adding in Address model
    delegate(*::Address.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :company_address)

    def initialize(user_attributes)
      super

      @company = @user.build_company

      # One of 3 lines triggering circular reference by adding in Address model
      @company_address = @user.company.addresses.build
    end
  end
end
</code>```

Body:
I understand the cause of a Stack Level Too Deep error. I am failing to spot where/why it is occurring in my code base.

I've implemented a multi-model, multi-step wizard. The first two models (User and Company) are working, it is when I attempt to add in the third (Address) I get the error.

I suspect the error is related to the associations between the models, although I've failed to debug.

The code snippets below function correctly except when I add the 3 lines (marked with comments in the snippet) too the file app/wizards/user_wizard/step1.rb.

Relevant Models

app/models/company.rb

class Company < ActiveRecord::Base
  include Validatable::Company

  # Associations:
  has_many :addresses, inverse_of: :company
  accepts_nested_attributes_for :addresses, reject_if: :all_blank

  has_many :employees, inverse_of: :company
  accepts_nested_attributes_for :employees, reject_if: :all_blank

  has_many :licenses, inverse_of: :company
  accepts_nested_attributes_for :licenses, reject_if: :all_blank

  has_many :vehicles, inverse_of: :company
  accepts_nested_attributes_for :vehicles, reject_if: :all_blank

  has_one :user, inverse_of: :company
end

app/models/address.rb

class Address < ActiveRecord::Base
  # Associations:
  belongs_to :company, inverse_of: :addresses

  has_many :licenses, inverse_of: :address
  accepts_nested_attributes_for :licenses, reject_if: :all_blank

  has_many :initial_analyses, inverse_of: :address
  accepts_nested_attributes_for :initial_analyses, reject_if: :all_blank
end

app/models/user.rb

class User < ActiveRecord::Base
  include SoftDeletable
  include Validatable::User

  # Constants:
  MARKER_ATTRIBUTES = %w[user_name].freeze # get marked with '(deleted)'
  DEPENDANT_CHILDREN = %w[none].freeze # child resources to be deleted

  # Associations:
  belongs_to :role, inverse_of: :users

  belongs_to :company, inverse_of: :user
  accepts_nested_attributes_for :company, reject_if: :all_blank

  has_many :auto_quotes, inverse_of: :user
end

db/schema.rb

ActiveRecord::Schema.define(version: 20170616131833) do

  create_table "addresses", force: :cascade do |t|
    t.integer  "company_id"
    t.text     "site_name"
    t.string   "premises_code"
    t.string   "exempt_premises_code"
    t.text     "address"
    t.string   "city"
    t.string   "county"
    t.string   "sic_code"
    t.string   "postcode"
    t.string   "country"
    t.boolean  "sic_update"
    t.boolean  "deleted",              default: false
    t.datetime "created_at",                           null: false
    t.datetime "updated_at",                           null: false
    t.datetime "deleted_at"
  end

  create_table "companies", force: :cascade do |t|
    t.string   "company_name"
    t.string   "registration_number"
    t.string   "type_of_business"
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
    t.datetime "deleted_at"
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.integer  "failed_attempts",        default: 0,  null: false
    t.string   "unlock_token"
    t.datetime "locked_at"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "user_name"
    t.datetime "deleted_at"
    t.integer  "role_id"
    t.integer  "company_id"
    t.string   "invitation_token"
    t.datetime "invitation_created_at"
    t.datetime "invitation_sent_at"
    t.datetime "invitation_accepted_at"
    t.integer  "invitation_limit"
    t.integer  "invited_by_id"
    t.string   "invited_by_type"
    t.integer  "invitations_count",      default: 0
  end

  add_index "users", ["company_id"], name: "index_users_on_company_id", unique: true
  add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["invitation_token"], name: "index_users_on_invitation_token", unique: true
  add_index "users", ["invitations_count"], name: "index_users_on_invitations_count"
  add_index "users", ["invited_by_id"], name: "index_users_on_invited_by_id"
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  add_index "users", ["unlock_token"], name: "index_users_on_unlock_token", unique: true
end

Wizards

app/wizards/user_wizard/base.rb

module UserWizard
  class Base
    include ActiveModel::Model

    STEPS = %w[step1 step2].freeze

    attr_accessor :user

    delegate(*::User.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :user)

    def initialize(user_attributes)
      @user = ::User.new(user_attributes)
    end
  end
end

app/wizards/user_wizard/step1.rb

module UserWizard
  class Step1 < UserWizard::Base
    include Validatable::Company

    attr_accessor :company

    # One of 3 lines triggering circular reference by adding in Address model
    attr_accessor :address

    delegate(*::Company.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :company)

    # One of 3 lines triggering circular reference by adding in Address model
    delegate(*::Address.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :address)

    def initialize(user_attributes)
      super

      @company = @user.build_company

      # One of 3 lines triggering circular reference by adding in Address model
      @address = @user.company.addresses.build
    end
  end
end

app/wizards/user_wizard/step2.rb

ommitted as it is irrelevant. code fails before ever instantiating this class

Body:
address has an address attribute. So the delegate method is trying to create a method address that will be delegated to address.

I'd suggest this:

module UserWizard
  class Step1 < UserWizard::Base
    include Validatable::Company

    attr_accessor :company

    # One of 3 lines triggering circular reference by adding in Address model
    attr_accessor :company_address

    delegate(*::Company.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :company)

    # One of 3 lines triggering circular reference by adding in Address model
    delegate(*::Address.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :company_address)

    def initialize(user_attributes)
      super

      @company = @user.build_company

      # One of 3 lines triggering circular reference by adding in Address model
      @company_address = @user.company.addresses.build
    end
  end
end


问:
How can I achive this target with css?
If you will enter the main page of youtube and try to shrink thw width of it, then the videos amount will shrink also.

So for example, if you have this screen(width: 500px;):

```<code> _____      _____     _____     _____
|     |    |     |   |     |   |     |
|_____|    |_____|   |_____|   |_____|
</code>```

Then if you shrink the screen ti be with width: 300px;, just two videos will appear on the screan, and the other two videos will get the property visibility with the value hidden (I assume this what happends...).

```<code> _____      _____
|     |    |     |
|_____|    |_____|
</code>```

How can I exactly get this aim to be done?
I thought about giving any video another id (like "video-1" etcetera...), and with the abbility of using @media screen... - just change the visibility property of each video each time.

I wanted to know the optimal and shorter way to do that, before im doing my way.
You know... to learn new thought it is a good thing to do :)

答:
You do not need to set the 'bleeded div's' (those dropping off the screen) to visibility hidden.

You can achieve this with a div as a mask wherein the smaller div's reside.

Set this mask to the same height as the smaller div's therein. Set the CSS attribute overflow-y to hidden. All the smaller div's inside need to be floated with float:left.

This way you get the effect you are looking for.

Example:

HTML

```<code><div class="mask">
  <div class="inner">
    ...
  </div>
  <div class="inner">
    ...
  </div>
  <div class="inner">
    ...
  </div>
  <div class="inner">
    ...
  </div>
  <div class="inner">
    ...
  </div>
</div>
</code>```

CSS:

```<code>.mask {height:200px;width:auto;overflow-y:hidden}
.mask .inner {float:left;height:200px;width:200px;margin-right:10px}
</code>```

Title: How can I achive this target with css?

Body:
If you will enter the main page of youtube and try to shrink thw width of it, then the videos amount will shrink also.

So for example, if you have this screen(width: 500px;):

 _____      _____     _____     _____
|     |    |     |   |     |   |     |
|_____|    |_____|   |_____|   |_____|

Then if you shrink the screen ti be with width: 300px;, just two videos will appear on the screan, and the other two videos will get the property visibility with the value hidden (I assume this what happends...).

 _____      _____
|     |    |     |
|_____|    |_____|

How can I exactly get this aim to be done?
I thought about giving any video another id (like "video-1" etcetera...), and with the abbility of using @media screen... - just change the visibility property of each video each time.

I wanted to know the optimal and shorter way to do that, before im doing my way.
You know... to learn new thought it is a good thing to do :)

Body:
You do not need to set the 'bleeded div's' (those dropping off the screen) to visibility hidden.

You can achieve this with a div as a mask wherein the smaller div's reside.

Set this mask to the same height as the smaller div's therein. Set the CSS attribute overflow-y to hidden. All the smaller div's inside need to be floated with float:left.

This way you get the effect you are looking for.

Example:

HTML

<div class="mask">
  <div class="inner">
    ...
  </div>
  <div class="inner">
    ...
  </div>
  <div class="inner">
    ...
  </div>
  <div class="inner">
    ...
  </div>
  <div class="inner">
    ...
  </div>
</div>

CSS:

.mask {height:200px;width:auto;overflow-y:hidden}
.mask .inner {float:left;height:200px;width:200px;margin-right:10px}


问:
Detect whether test has failed within fixture
I am debugging an intermittent test failure. For this purposes I want to dump a lot of debug information if a test failed. Dumping debug stuff is quite slow process which produces a lot of data, so I do not want to do this for every test.

I am using pytest and yield autouse fixture should work great

```<code>@pytest.yield_fixture(scope="function", autouse=True)
def dump_on_failue(request):
    prepare_debug_dump()

    yield

    if test_failed(request):
        debug_dump()
</code>```

The problem is that I can't figure out how do I detect whether test has failed or not. There was a questions already and even note on pytest website:

```<code>    if request.node.rep_setup.failed:
        print ("setting up a test failed!", request.node.nodeid)
    elif request.node.rep_setup.passed:
        if request.node.rep_call.failed:
            print ("executing test failed", request.node.nodeid)
</code>```

Unfortunately this code does not work anymore. There are no rep_setup and rep_calls symbols in node object. I tried to dig request and node object, but no luck.

Anybody knows how to detect whether test failed?

答:
There are no rep_setup and rep_calls symbols in node object.

No.rep_setup and rep_calls symbols are still there.

Add this code into your root conftest.py. It will check pass/fail for every test function.

```<code>import pytest

@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
    rep = __multicall__.execute()
    setattr(item, "rep_" + rep.when, rep)
    return rep

@pytest.fixture(scope='function', autouse=True)
def test_debug_log(request):
    def test_result():
        if request.node.rep_setup.failed:
            print ("setting up a test failed!", request.node.nodeid)
        elif request.node.rep_setup.passed:
            if request.node.rep_call.failed:
                print ("executing test failed", request.node.nodeid)
    request.addfinalizer(test_result)
</code>```

Body:
I am debugging an intermittent test failure. For this purposes I want to dump a lot of debug information if a test failed. Dumping debug stuff is quite slow process which produces a lot of data, so I do not want to do this for every test.

I am using pytest and yield autouse fixture should work great

@pytest.yield_fixture(scope="function", autouse=True)
def dump_on_failue(request):
    prepare_debug_dump()

    yield

    if test_failed(request):
        debug_dump()

The problem is that I can't figure out how do I detect whether test has failed or not. There was a questions already and even note on pytest website:

    if request.node.rep_setup.failed:
        print ("setting up a test failed!", request.node.nodeid)
    elif request.node.rep_setup.passed:
        if request.node.rep_call.failed:
            print ("executing test failed", request.node.nodeid)

Unfortunately this code does not work anymore. There are no rep_setup and rep_calls symbols in node object. I tried to dig request and node object, but no luck.

Anybody knows how to detect whether test failed?

Body:
There are no rep_setup and rep_calls symbols in node object.

No.rep_setup and rep_calls symbols are still there.

Add this code into your root conftest.py. It will check pass/fail for every test function.

import pytest

@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
    rep = __multicall__.execute()
    setattr(item, "rep_" + rep.when, rep)
    return rep

@pytest.fixture(scope='function', autouse=True)
def test_debug_log(request):
    def test_result():
        if request.node.rep_setup.failed:
            print ("setting up a test failed!", request.node.nodeid)
        elif request.node.rep_setup.passed:
            if request.node.rep_call.failed:
                print ("executing test failed", request.node.nodeid)
    request.addfinalizer(test_result)


问:
Ranges in Kotlin below API 21
I want to store key-value pairs like < 4.1, 29..35 > which I can do with a HashMap<Double, Range<Int>>:

```<code>val womanMap: HashMap<Double, Range<Int>> = hashMapOf()

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun createMap() {
    //This both requires API 21
    val range = Range(29,35)
    womanMap[4.6] = Range.create(29,35)
}
</code>```

How can I do this below API level 21?

答:
Range is a class in the Android SDK, this is tied to API 21. You could use IntRange provided by the Kotlin standard library instead though.

You can find usage examples for Kotlin ranges here.

Here's what their basic usage looks like:

```<code>val range = 1..10    // creation
println(range.first) // 1
println(range.last)  // 10
println(5 in range)  // true
</code>```

Title: Ranges in Kotlin below API 21

Body:
I want to store key-value pairs like < 4.1, 29..35 > which I can do with a HashMap<Double, Range<Int>>:

val womanMap: HashMap<Double, Range<Int>> = hashMapOf()

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun createMap() {
    //This both requires API 21
    val range = Range(29,35)
    womanMap[4.6] = Range.create(29,35)
}

How can I do this below API level 21?

Body:
Range is a class in the Android SDK, this is tied to API 21. You could use IntRange provided by the Kotlin standard library instead though.

You can find usage examples for Kotlin ranges here.

Here's what their basic usage looks like:

val range = 1..10    // creation
println(range.first) // 1
println(range.last)  // 10
println(5 in range)  // true


问:
How to set text-decoration: underline only for specific content
I have a input tag and where I am getting input value like this.

```<code>input.value += " " + value + ";" ;
</code>```

In my css I have text-decoration: underline; but here underline is coming in "space" and ";" both the place. Is there any way I can decorate only text part.

My Code is like :

```<code>var div = document.getElementById(divID);

var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "openingList()" onkeyup="openingList()" style="width:30%;" >' +
    '<div id="triggers">' + '<img class="trigger" onclick ="deleteValue()" src="css/clearT.png" id="cross" />' + '<img class="trigger" src="css/combo_arrow.png" onclick = "openingList()" id="arrow" />' + '</div>' +
    '<ul id="myUL" hidden=true>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';

div.innerHTML = myTable;

function selectItem(input, value) {
    var newinput = input.value.split(';');
    newinput[newinput.length - 1] = "";
    input.value = newinput.join(";");
    input.value += " " + value + ";" + "";
}
</code>```

Current it is coming like this.

What exactly I want here

答:
Okay after having a thorough look at the problem, I have actually realized that there is not any simple solution. As styles can apply to the entirety of an element only, a solution will require at least one element per required style.

Solution

You cannot achieve this with a single input element. Also, JavaScript is required for a solution. So, there are three sections of the input:

that before the point at which changes are being applied

that after the point at which changes are being applied

that at the point the changes are being applied

You should initially include a regular input element and forgo any of the required styling. Use JavaScript to replace the input with a suitable container element. This can be styled to mimic an input element.

As you add values, use JavaScript to identify the above-mentioned three divisions. Wrap them in suitable elements (spans would be ideal) and style as needed.

Consider the following starting point:

```<code><div class="input">
  <span class="before"> </span>
  <span class="edited">value</span>
  <span class="after">;</span>
</div>
</code>```

This will serve as a proper solution to the mentioned problem and also for similar future problems that you encounter.

ContentLicense: CC BY-SA 4.0

Body:
I have a input tag and where I am getting input value like this.

input.value += " " + value + ";" ;

In my css I have text-decoration: underline; but here underline is coming in "space" and ";" both the place. Is there any way I can decorate only text part.

My Code is like :

var div = document.getElementById(divID);

var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "openingList()" onkeyup="openingList()" style="width:30%;" >' +
    '
' + '' + '' + '
' +
    '
' + '
' + '' + '
' + '
';

div.innerHTML = myTable;

function selectItem(input, value) {
    var newinput = input.value.split(';');
    newinput[newinput.length - 1] = "";
    input.value = newinput.join(";");
    input.value += " " + value + ";" + "";
}

Current it is coming like this.

What exactly I want here

Body:
Okay after having a thorough look at the problem, I have actually realized that there is not any simple solution. As styles can apply to the entirety of an element only, a solution will require at least one element per required style.

Solution

You cannot achieve this with a single input element. Also, JavaScript is required for a solution. So, there are three sections of the input:

that before the point at which changes are being applied

that after the point at which changes are being applied

that at the point the changes are being applied

You should initially include a regular input element and forgo any of the required styling. Use JavaScript to replace the input with a suitable container element. This can be styled to mimic an input element.

As you add values, use JavaScript to identify the above-mentioned three divisions. Wrap them in suitable elements (spans would be ideal) and style as needed.

Consider the following starting point:

<div class="input">
  <span class="before"> </span>
  <span class="edited">value</span>
  <span class="after">;</span>
</div>

This will serve as a proper solution to the mentioned problem and also for similar future problems that you encounter.


问:
Getting duplicate keys in YAML using Python
We are in need of parsing YAML files which contain duplicate keys and all of these need to be parsed. It is not enough to skip duplicates. I know this is against the YAML spec and I would like to not have to do it, but a third-party tool used by us enables this usage and we need to deal with it.

File example:

```<code>build:
  step: 'step1'

build:
  step: 'step2'
</code>```

After parsing we should have a similar data structure to this:

```<code>yaml.load('file.yml')
# [('build', [('step', 'step1')]), ('build', [('step', 'step2')])]
</code>```

dict can no longer be used to represent the parsed contents.

I am looking for a solution in Python and I didn't find a library supporting this, have I missed anything?

Alternatively, I am happy to write my own thing but would like to make it as simple as possible. ruamel.yaml looks like the most advanced YAML parser in Python and it looks moderately extensible, can it be extended to support duplicate fields?

答:
If you can modify the input data very slightly, you should be able to do this by converting the single yaml-like file into multiple yaml documents. yaml documents can be in the same file if they're separated by --- on a line by itself, and you handily appear to have entries separated by two newlines next to each other:

```<code>with open('file.yml', 'r') as f:
    data = f.read()
    data = data.replace('\n\n', '\n---\n')

    for document in yaml.load_all(data):
        print(document)
</code>```

Output:

```<code>{'build': {'step': 'step1'}}
{'build': {'step': 'step2'}}
</code>```

Body:
We are in need of parsing YAML files which contain duplicate keys and all of these need to be parsed. It is not enough to skip duplicates. I know this is against the YAML spec and I would like to not have to do it, but a third-party tool used by us enables this usage and we need to deal with it.

File example:

build:
  step: 'step1'

build:
  step: 'step2'

After parsing we should have a similar data structure to this:

yaml.load('file.yml')
# [('build', [('step', 'step1')]), ('build', [('step', 'step2')])]

dict can no longer be used to represent the parsed contents.

I am looking for a solution in Python and I didn't find a library supporting this, have I missed anything?

Alternatively, I am happy to write my own thing but would like to make it as simple as possible. ruamel.yaml looks like the most advanced YAML parser in Python and it looks moderately extensible, can it be extended to support duplicate fields?

Body:
If you can modify the input data very slightly, you should be able to do this by converting the single yaml-like file into multiple yaml documents. yaml documents can be in the same file if they're separated by --- on a line by itself, and you handily appear to have entries separated by two newlines next to each other:

with open('file.yml', 'r') as f:
    data = f.read()
    data = data.replace('\n\n', '\n---\n')

    for document in yaml.load_all(data):
        print(document)

Output:

{'build': {'step': 'step1'}}
{'build': {'step': 'step2'}}


问:
Getting integer box widths instead of decimal values: Math.ceil() doesn't round up
I have a Bootstrap navbar. Inspecting with Chrome DevTools I noticed that this (and other browsers, I suppose) returns decimal box widths instead of integers (i.e. 83.06 instead of 83).

For a pixel-perfect alignment with some other elements I need to 'convert to integer' this number, and to avoid button collapse in 2+ words items I need to 'round up' it: in short, 83.06 should become 84 (and not 83).

The only way I'm aware of is with JavaScript, so I did this script:

```<code>$(window).on('resize', function(){ // recalculate when resizing window
  if (window.innerWidth > 768) { // only in 'desktop' version(s), smaller devices don't need recalculation
    $('.navbar-nav').find('> li:not(.hidden-sm)').each(function(){
      var width = $(this).children('a').outerWidth(); // for each valid 'li', take its 'a' descendant width
      console.log(width); // watch what happens
      $(this).width(Math.ceil(width)); // change item width with a 'rounded up' value
    })
  }
}).resize();
</code>```

Here is the code snippet (jsFiddle):

$(window).on('resize', function(){ // recalculate when resizing window
  if (window.innerWidth > 768) { // only in 'desktop' version(s)
    $('.navbar-nav').find('> li:not(.hidden-sm)').each(function(){
      var width = $(this).children('a').outerWidth(); // for each valid 'li', take its 'a' descendant width
      console.log(width); // watch what happens
      $(this).width(Math.ceil(width)); // change item width with a 'rounded up' value
    })
  }
}).resize();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active">Link One<span class="sr-only">(current)</span></li>
        <li>Link Two, Long</li>
        <li class="dropdown">
          Dropdown <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Action</li>
            <li>Another action</li>
            <li>Something else here</li>
          </ul>
        </li>
        <li class="hidden-sm">Link Three: too long to fit, hide on small devices</li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav></code>```

Pretty straight, right? But it doesn't work as expected: items' original widths (86.05, 124.17 and 107.7 according to Chrome DevTools) are not always rounded up despite the Math.ceil() function and I end up with 86, 124 and 108 (only the latter is right; the first two items 'collapse' because there is not enough space). Shouldn't Math.ceil() always round up? Very weird...

"Ok", I thought, "let's find a workaround": so I swapped Math.ceil() with parseInt() and add at least +1 pixel, like this other snippet (jsFiddle):

$(window).on('resize', function(){ // recalculate when resizing window
  if (window.innerWidth > 768) { // only in 'desktop' version(s)
    $('.navbar-nav').find('> li:not(.hidden-sm)').each(function(){
      var width = $(this).children('a').outerWidth(); // for each valid 'li', take its 'a' descendant width
      console.log(width); // watch what happens
      $(this).width(parseInt(width)+1); // change item width with a 'rounded up' value
    })
  }
}).resize();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active">Link One<span class="sr-only">(current)</span></li>
        <li>Link Two, Long</li>
        <li class="dropdown">
          Dropdown <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Action</li>
            <li>Another action</li>
            <li>Something else here</li>
          </ul>
        </li>
        <li class="hidden-sm">Link Three: too long to fit, hide on small devices</li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav></code>```

Good, buttons don't collapse but... try to resize the window: buttons grow forever, maybe because I'm adding 1 pixel to each iteration: this is worse than before...

Now I am stuck and can't imagine other ways to go: any solution to get integers rounded up without ending with all these crazy results, please? Thank you

答:
Your problem is that jQuery's .width() already internally rounds the width values to the closest integer (so: 86.05 => 86 , 124.17 => 124 , 107.7 => 108).

So the values you retrieve using .width() and perform your rounding calculations on, are already integers, and therefor they have no effect whatsoever:)

This can be resolved by using JavaScript's native .getBoundingClientRect():

This will return the actual floating-point width (got it from this answer).

```<code>var width = $(this).children('a')[0].getBoundingClientRect().width;
</code>```

You could leave it at that, but now the widths of all those lis are always reset, whether they already have been or not.

To prevent that, I used an if-clause to check if the width is not already an integer, and only then gets the element actually resized.

This is all you need for that (which I got from this answer):

```<code>if (width%1 !== 0) {$(this).width(Math.ceil(width));}
</code>```

But to be safe I would also remove .children('a'), and measure the lis themselves:

```<code>var width = $(this)[0].getBoundingClientRect().width;
</code>```

Apparently the a automatically fills the entire li, but the li also auto-scales to the a, and since you're performing the .width() operation on the li, it seems safer and more logical to also check the width of that same element.

Alternatively, you could set the width() of the a instead of the li.

See code snippet for a demo  (put snippet in "Full page" to test):

$(window).on('resize', function(){ // recalculate when resizing window
  if (window.innerWidth > 768) { // only in 'desktop' version(s)
    $('.navbar-nav').find('> li:not(.hidden-sm)').each(function(){
      var width = $(this)[0].getBoundingClientRect().width; // for each valid 'li', take its 'a' descendant width
      if (width%1 !== 0) {$(this).width(Math.ceil(width));} // if width isn't already an integer, round up
      console.log(width, 'resize: '+(width%1 !== 0));
    });
  }
}).resize();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active">Link One<span class="sr-only">(current)</span></li>
        <li>Link Two, Long</li>
        <li class="dropdown">
          Dropdown <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Action</li>
            <li>Another action</li>
            <li>Something else here</li>
          </ul>
        </li>
        <li class="hidden-sm">Link Three: too long to fit, hide on small devices</li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav></code>```

jsfiddle: https://jsfiddle.net/c7927ud1/6/

Body:
I have a Bootstrap navbar. Inspecting with Chrome DevTools I noticed that this (and other browsers, I suppose) returns decimal box widths instead of integers (i.e. 83.06 instead of 83).

For a pixel-perfect alignment with some other elements I need to 'convert to integer' this number, and to avoid button collapse in 2+ words items I need to 'round up' it: in short, 83.06 should become 84 (and not 83).

The only way I'm aware of is with JavaScript, so I did this script:

$(window).on('resize', function(){ // recalculate when resizing window
  if (window.innerWidth > 768) { // only in 'desktop' version(s), smaller devices don't need recalculation
    $('.navbar-nav').find('> li:not(.hidden-sm)').each(function(){
      var width = $(this).children('a').outerWidth(); // for each valid 'li', take its 'a' descendant width
      console.log(width); // watch what happens
      $(this).width(Math.ceil(width)); // change item width with a 'rounded up' value
    })
  }
}).resize();

Here is the code snippet (jsFiddle):

$(window).on('resize', function(){ // recalculate when resizing window
  if (window.innerWidth > 768) { // only in 'desktop' version(s)
    $('.navbar-nav').find('> li:not(.hidden-sm)').each(function(){
      var width = $(this).children('a').outerWidth(); // for each valid 'li', take its 'a' descendant width
      console.log(width); // watch what happens
      $(this).width(Math.ceil(width)); // change item width with a 'rounded up' value
    })
  }
}).resize();

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Link One(current)

Link Two, Long

          Dropdown

Action

Another action

Something else here

Link Three: too long to fit, hide on small devices

Pretty straight, right? But it doesn't work as expected: items' original widths (86.05, 124.17 and 107.7 according to Chrome DevTools) are not always rounded up despite the Math.ceil() function and I end up with 86, 124 and 108 (only the latter is right; the first two items 'collapse' because there is not enough space). Shouldn't Math.ceil() always round up? Very weird...

"Ok", I thought, "let's find a workaround": so I swapped Math.ceil() with parseInt() and add at least +1 pixel, like this other snippet (jsFiddle):

$(window).on('resize', function(){ // recalculate when resizing window
  if (window.innerWidth > 768) { // only in 'desktop' version(s)
    $('.navbar-nav').find('> li:not(.hidden-sm)').each(function(){
      var width = $(this).children('a').outerWidth(); // for each valid 'li', take its 'a' descendant width
      console.log(width); // watch what happens
      $(this).width(parseInt(width)+1); // change item width with a 'rounded up' value
    })
  }
}).resize();

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Link One(current)

Link Two, Long

          Dropdown

Action

Another action

Something else here

Link Three: too long to fit, hide on small devices

Good, buttons don't collapse but... try to resize the window: buttons grow forever, maybe because I'm adding 1 pixel to each iteration: this is worse than before...

Now I am stuck and can't imagine other ways to go: any solution to get integers rounded up without ending with all these crazy results, please? Thank you

Body:
Your problem is that jQuery's .width() already internally rounds the width values to the closest integer (so: 86.05 => 86 , 124.17 => 124 , 107.7 => 108).

So the values you retrieve using .width() and perform your rounding calculations on, are already integers, and therefor they have no effect whatsoever:)

This can be resolved by using JavaScript's native .getBoundingClientRect():

This will return the actual floating-point width (got it from this answer).

var width = $(this).children('a')[0].getBoundingClientRect().width;

You could leave it at that, but now the widths of all those lis are always reset, whether they already have been or not.

To prevent that, I used an if-clause to check if the width is not already an integer, and only then gets the element actually resized.

This is all you need for that (which I got from this answer):

if (width%1 !== 0) {$(this).width(Math.ceil(width));}

But to be safe I would also remove .children('a'), and measure the lis themselves:

var width = $(this)[0].getBoundingClientRect().width;

Apparently the a automatically fills the entire li, but the li also auto-scales to the a, and since you're performing the .width() operation on the li, it seems safer and more logical to also check the width of that same element.

Alternatively, you could set the width() of the a instead of the li.

See code snippet for a demo  (put snippet in "Full page" to test):

$(window).on('resize', function(){ // recalculate when resizing window
  if (window.innerWidth > 768) { // only in 'desktop' version(s)
    $('.navbar-nav').find('> li:not(.hidden-sm)').each(function(){
      var width = $(this)[0].getBoundingClientRect().width; // for each valid 'li', take its 'a' descendant width
      if (width%1 !== 0) {$(this).width(Math.ceil(width));} // if width isn't already an integer, round up
      console.log(width, 'resize: '+(width%1 !== 0));
    });
  }
}).resize();

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link One<span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link Two, Long</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
          </ul>
        </li>
        <li class="hidden-sm"><a href="#">Link Three: too long to fit, hide on small devices</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

jsfiddle: https://jsfiddle.net/c7927ud1/6/


问:
Analytics - Email tracking
I'm trying to track my email links with Google Analytics, but for some reasons it does not work.
Here is my code:

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

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'xxxxxx']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</code>```

and here's the onClick function in page source code:

```<code><a href="mailto:mail@mail.sk" onClick="_gaq.push(['_trackEvent', 'Index','Klik - email','mail@mail.sk']);">mail@mail.sk</a>
</code>```

I tried same tracking for link on other page and it worked. After I installed GA Debug, I found out that when I'm tracking mailto link, error shows up - Failed to load resource: mailto:mail@mail.sk

Does somebody have any ideas why there is an error and how to fix it?
Thanks

答:
Wild guess :

Does adding javascript: before the content of your onClick even solves it ?

```<code><a href="mailto:mail@mail.sk" onClick="javascript:_gaq.push(['_trackEvent', 'Index','Klik - email','mail@mail.sk']);">mail@mail.sk</a>
</code>```

Title: Analytics - Email tracking

Body:
I'm trying to track my email links with Google Analytics, but for some reasons it does not work.
Here is my code:

and here's the onClick function in page source code:

mail@mail.sk

I tried same tracking for link on other page and it worked. After I installed GA Debug, I found out that when I'm tracking mailto link, error shows up - Failed to load resource: mailto:mail@mail.sk

Does somebody have any ideas why there is an error and how to fix it?
Thanks

Body:
Wild guess :

Does adding javascript: before the content of your onClick even solves it ?

<a href="mailto:mail@mail.sk" onClick="javascript:_gaq.push(['_trackEvent', 'Index','Klik - email','mail@mail.sk']);">mail@mail.sk</a>


问:
Laravel Passport Password Grant - Client authentication failed
After hearing a lot about laravel passport, i thought of implementing it into my new project where my requirement is to create an API that'll be used in a mobile app.

So my mobile app is a client, which will further have its users.

I followed the steps mentioned by Taylor and also read about it here. In a nutshell I followed these steps:

Installed laravel/passport.

Created a website user.

Generated passport keys php artisan passport:install

Generated client_id and client_secret using php artisan passport:client

Added redirection and callback routes in web.php

Authorized the user and got the final access token.

Then I tried calling api/user( with Header Authorization containing value Bearer eyJ0eXAiOiJKV1...(token)

I received the data. Pretty simple and neat.

But my app users won't have these details. So I thought of configuring Password Grant Tokens which fits perfectly in my requirement.

Now starts the real headache. I've been trying to set this up for the last 3 days and continuously getting

```<code>{"error":"invalid_client","message":"Client authentication failed"}
</code>```

I've tried almost every guide I followed online: Redirection Issues, Add Atleast One Scope Solution, P100Y Issue etc.

But I'm still getting invalid client error. Here's what I'm passing through POSTMAN to oauth/token:

```<code>{
    "grant_type": "password,"
    "client_id": "3,"
    "client_secret": "8BUPCSyYEdsgtZFnD6bFG6eg7MKuuKJHLsdW0k6g,"
    "username": "test@gmail.com,"
    "password": "123456,"
    "scope": ""
}
</code>```

Any help would be appreciated.

答:
you can define a two variables like

```<code>$client_id = '111';
$client_secret = '1212';
</code>```

and the condition is in your function like this

```<code>protected $clientID = '578324956347895';
protected $clinetSecret ='hflieryt478';

public function index(Request $request)
{

    if (!($request->input('clientID') && $request->input('clinetSecret'))) {
        return false;
    }

    $project = User::all();

   return $project
}
</code>```

Body:
After hearing a lot about laravel passport, i thought of implementing it into my new project where my requirement is to create an API that'll be used in a mobile app.

So my mobile app is a client, which will further have its users.

I followed the steps mentioned by Taylor and also read about it here. In a nutshell I followed these steps:

Installed laravel/passport.

Created a website user.

Generated passport keys php artisan passport:install

Generated client_id and client_secret using php artisan passport:client

Added redirection and callback routes in web.php

Authorized the user and got the final access token.

Then I tried calling api/user( with Header Authorization containing value Bearer eyJ0eXAiOiJKV1...(token)

I received the data. Pretty simple and neat.

But my app users won't have these details. So I thought of configuring Password Grant Tokens which fits perfectly in my requirement.

Now starts the real headache. I've been trying to set this up for the last 3 days and continuously getting

{"error":"invalid_client","message":"Client authentication failed"}

I've tried almost every guide I followed online: Redirection Issues, Add Atleast One Scope Solution, P100Y Issue etc.

But I'm still getting invalid client error. Here's what I'm passing through POSTMAN to oauth/token:

{
    "grant_type": "password,"
    "client_id": "3,"
    "client_secret": "8BUPCSyYEdsgtZFnD6bFG6eg7MKuuKJHLsdW0k6g,"
    "username": "test@gmail.com,"
    "password": "123456,"
    "scope": ""
}

Any help would be appreciated.

Body:
you can define a two variables like

$client_id = '111';
$client_secret = '1212';

and the condition is in your function like this

protected $clientID = '578324956347895';
protected $clinetSecret ='hflieryt478';

public function index(Request $request)
{

    if (!($request->input('clientID') && $request->input('clinetSecret'))) {
        return false;
    }

    $project = User::all();

   return $project
}


问:
Extract first integer in a string with PHP
Consider the following strings:

```<code>$strings = array(
    "8.-10. stage",
    "8. stage"
);
</code>```

I would like to extract the first integer of each string, so it would return

```<code>8
8
</code>```

I tried to filter out numbers with preg_replace but it returns all integers and I only want the first.

```<code>foreach($strings as $string)
{
    echo preg_replace("/[^0-9]/", '',$string);
}
</code>```

Any suggestions?

答:
if you have Notice in PHP 7 +

Notice:  Only variables should be passed by reference in YOUR_DIRECTORY_FILE.php on line LINE_NUMBER

By using this code

```<code>echo reset(array_filter(preg_split("/\D+/", $string)));
</code>```

Change code to

```<code>$var = array_filter(preg_split("/\D+/", $string));
return reset($var);
</code>```

And enjoy! Best Regards Ovasapov

Body:
Consider the following strings:

$strings = array(
    "8.-10. stage",
    "8. stage"
);

I would like to extract the first integer of each string, so it would return

8
8

I tried to filter out numbers with preg_replace but it returns all integers and I only want the first.

foreach($strings as $string)
{
    echo preg_replace("/[^0-9]/", '',$string);
}

Any suggestions?

Body:
if you have Notice in PHP 7 +

Notice:  Only variables should be passed by reference in YOUR_DIRECTORY_FILE.php on line LINE_NUMBER

By using this code

echo reset(array_filter(preg_split("/\D+/", $string)));

Change code to

$var = array_filter(preg_split("/\D+/", $string));
return reset($var);

And enjoy! Best Regards Ovasapov


答:
Use IntRange instead:

```<code>val womanMap: HashMap<Double, IntRange> = hashMapOf()

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun createMap() {
        val range = 29..35
        womanMap[4.6] = 29..35
    }
</code>```

Note that 29..35 is a closed interval:

```<code>for (a in 29..35) print("$a ") // >>> 29 30 31 32 33 34 35
</code>```

To create a range which does not include its end element use 29 until 35:

```<code>for (a in 29 until 35) print("$a ") // >>> 29 30 31 32 33 34
</code>```

For more info: Ranges

Title: Ranges in Kotlin below API 21

Body:
Use IntRange instead:

val womanMap: HashMap<Double, IntRange> = hashMapOf()

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun createMap() {
        val range = 29..35
        womanMap[4.6] = 29..35
    }

Note that 29..35 is a closed interval:

for (a in 29..35) print("$a ") // >>> 29 30 31 32 33 34 35

To create a range which does not include its end element use 29 until 35:

for (a in 29 until 35) print("$a ") // >>> 29 30 31 32 33 34

For more info: Ranges


问:
Navigate to a cell in a DataFrame using a set of criteria
I have a csv table like so:

```<code>a, b, c, d
value, value, value, value
value, value, value, value
</code>```

which I'm loading into a DataFrame. I also have a dictionary that looks like this:

```<code>data = {'a': some_value, 'b' = some_value, 'c' = some_value}
</code>```

I want to navigate to the cell in column d where the row has values a, b and c as specified by this dictionary. I know that there exists exactly one cell that matches these criteria. How can I do this?

Body:
I have a csv table like so:

a, b, c, d
value, value, value, value
value, value, value, value

which I'm loading into a DataFrame. I also have a dictionary that looks like this:

data = {'a': some_value, 'b' = some_value, 'c' = some_value}

I want to navigate to the cell in column d where the row has values a, b and c as specified by this dictionary. I know that there exists exactly one cell that matches these criteria. How can I do this?

Body:
Another way, could be using pd.query

In [1009]: query = ' and '.join(['%s == %s' % (x, lookup[x]) for x in lookup])

In [1010]: query
Out[1010]: 'a == 2 and c == 2 and b == 2'

In [1011]: data.query(query)
Out[1011]:
   a  b  c  d
1  2  2  2  2

Details

In [1012]: lookup
Out[1012]: {'a': 2, 'b': 2, 'c': 2}

In [1013]: data
Out[1013]:
   a  b  c  d
0  1  1  1  1
1  2  2  2  2
2  3  3  3  3
3  4  4  4  4


问:
where does back event is handel in swift 3.0
I want to refresh the whole page controller on back press.
I am navigating the viewcontroller using code.

My Code

```<code>let GTC = self.storyboard?.instantiateViewController(withIdentifier: "GoToCart")as! GoToCart
self.navigationController?.pushViewController(GTC, animated: true)
</code>```

答:
viewWillAppear(_:)

viewWillAppear is called the first time the view is displayed as well as when the view is displayed again, so it can be called multiple times during the life of the view controller object. It’s called when the view is about to appear as a result of the user tapping the back button, when the view controller’s tab is selected in a tab bar controller etc. Make sure to call super.viewWillAppear() at some point in the implementation. You can refresh your UI in this method

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // Reload the UI
}
</code>```

Body:
I want to refresh the whole page controller on back press.
I am navigating the viewcontroller using code.

My Code

let GTC = self.storyboard?.instantiateViewController(withIdentifier: "GoToCart")as! GoToCart
self.navigationController?.pushViewController(GTC, animated: true)

Body:
viewWillAppear(_:)

viewWillAppear is called the first time the view is displayed as well as when the view is displayed again, so it can be called multiple times during the life of the view controller object. It’s called when the view is about to appear as a result of the user tapping the back button, when the view controller’s tab is selected in a tab bar controller etc. Make sure to call super.viewWillAppear() at some point in the implementation. You can refresh your UI in this method

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // Reload the UI
}


问:
Real world experiences with the ADO.NET Entity Framework and unit testing
I am investigating the ADO.NET Entity Framework in combination with unit testing. A recommended way is described by Scott Allan:

Testability and Entity Framework 4.0

The article involves the code generation with POCOS.

My first impression: The manual effort to introduce and maintain this architecture is high. Before a deep dive I am interested in any real world experience.

答: To add what @Craig Stuntz entioned, I'd recommend you take a look at the EF Futures Code-First. It's in CTP5 right now, and RC/Beta soon. I've been using it for two separate projects recently and it's awesome. I personally hate using a visual editor when this should be really driven by the code. I've found POCO to be awesome for writing a project.</p>


问:
Create a pandas map with two arguments
I'm working with the "titanic.csv" https://www.kaggle.com/c/titanic/data, trying to find the teenager survival rate from the age column. I was able to create a 'under10' series with

```<code>under10 = (titanic['Age'] < 10).map({True:'under 10', False:'over 10'})
under10_survived_1 = titanic.groupby(under10)['Survived'].mean()
</code>```

But when I tried to do the same with teenager range, error was given.

```<code>teenager = (titanic['Age'] < 20 and titanic['Age'] > 10).map({True:'Teenager', False:'Not Teenager'})
teenager = (titanic['Age'] < 20 & titanic['Age'] > 10).map({True:'Teenager', False:'Not Teenager'})

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

Any suggestion on how to fix this issue?

答:
Add double () for each condition, because operator precedence:

```<code>teenager = ((titanic['Age'] < 20) & (titanic['Age'] > 10))
                        .map({True:'Teenager', False:'Not Teenager'})
</code>```

Alternative solution:

```<code>teenager = np.where((titanic['Age'] < 20) & (titanic['Age'] > 10)),'Teenager','Not Teenager')
</code>```

Title: Create a pandas map with two arguments

Body:
I'm working with the "titanic.csv" https://www.kaggle.com/c/titanic/data, trying to find the teenager survival rate from the age column. I was able to create a 'under10' series with

under10 = (titanic['Age'] < 10).map({True:'under 10', False:'over 10'})
under10_survived_1 = titanic.groupby(under10)['Survived'].mean()

But when I tried to do the same with teenager range, error was given.

teenager = (titanic['Age'] < 20 and titanic['Age'] > 10).map({True:'Teenager', False:'Not Teenager'})
teenager = (titanic['Age'] < 20 & titanic['Age'] > 10).map({True:'Teenager', False:'Not Teenager'})

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Any suggestion on how to fix this issue?

Body:
Add double () for each condition, because operator precedence:

teenager = ((titanic['Age'] < 20) & (titanic['Age'] > 10))
                        .map({True:'Teenager', False:'Not Teenager'})

Alternative solution:

teenager = np.where((titanic['Age'] < 20) & (titanic['Age'] > 10)),'Teenager','Not Teenager')


问:
Hosting MongoDB database on AWS : EC2 or S3?
I have a NodeJS WebApp which will soon run on an EC2 instance.
This WebApp will have to store numerous files (less than 10 MB a file) into a MongoDB database.

My question is the following : Would it be wiser to host the database on S3 or EC2 ? And what would be the difference if I hosted it either on S3 or EC2 ?

EDIT : Ok, I'll add more specifications to help you understand better the situation.

My company needs a tool to retrieve and upload files, which I did via a WebApp created by myself (with NodeJS + React + Express).

These files are raw-data files, and I also need to link files between each other (for example, a raw-data file will be associated with its specs file in order to know how to decode it). Also, and that's why I chose a NOSQL database, some vars in these raw-data files will have to be stored with these files in order to get useful variables faster.

My enterprise has an enterprise account for AWS and in the EC2 instances dashboard, only the t2.micro is free to use. I will also specify that I'm doing an internship, so I'm not in position to negociate a budget ...

答:
tldr: You cannot host MongoDB database on S3.

S3 is an object store, it is not a FileSystem.

If you want to run a mongoDB instance, you will need to spin an ec2 instance and install it on an attached EBS volume. If you plan to have a lot of IOPS you should probably run an I3 instance and have either GP2 or IO1 EBS volume. If you dont plan a high usage to the DB, you can target M4 or C4 with GP2 (maybe start with that and go with other instance type if necessary)

If you ned to store files within your DB, host them directly in your mongoDB instance, access will be much faster, it is reasonably cheap and you can benefit from mongodb feature on BSon (index, search etc)


问:
Best way to run python script on raspberry pi 3 from android mobile phone
Can anybody tell me which would be the fastets, best and easiest ways to somehow run python scripts on my raspberry from my android phone. I tried via ssh but it never worked. Bluetooth connection would be also okay, but I couldn't find a good how-to for that.

Thanks for your replies.

答:
So which wasn't working? The ssh or running the scripts? Do you have the scripts made already or are you changing them using the phone? If you have the scripts stored on the rpi you could run them over the SSH using commands like:

```<code>python script.py
</code>```

personally I use JuiceSSH for connecting to raspberry pi from my cellphone. You either need to be on the same network or setup somekind of a dynamic dns service to connect over the network. I have used successfully No-Ip on my rpi to this purpose.

edit:
what are you trying to achieve with the scripts?

Body:
So which wasn't working? The ssh or running the scripts? Do you have the scripts made already or are you changing them using the phone? If you have the scripts stored on the rpi you could run them over the SSH using commands like:

python script.py

personally I use JuiceSSH for connecting to raspberry pi from my cellphone. You either need to be on the same network or setup somekind of a dynamic dns service to connect over the network. I have used successfully No-Ip on my rpi to this purpose.

edit:
what are you trying to achieve with the scripts?


问:
Master Slave Approach in RDS Mysql Database
How can I implement Master Slave approach in RDS database? Actually what i want is, for improving the performance I want to implement Master Slave approach in my RDS Database. I think if i can separate the read and create/update operations into different databases I can improve the perfomace. How can I implement this?  </p>

答:
This is actually very easy with RDS - you just need to create an RDS Read Replica. This will do the replication asynchronously, which will improve your RDS write replica performance by not overloading it.

Note, different types of read replicas are available depending on the SQL flavour you use. Generally there are up to 5 direct read replicas of an instance, but Aurora for example offers 15.

Please see:
https://aws.amazon.com/rds/details/read-replicas/


问:
Loading async data into a data model on init
How do I load data from an async callback into the parent class attributes?

I have a database in Firebase which holds my user profiles. I want to be able to pass in the node key and have it populate the object with the given values.

Because it works async, I am getting the default values from the object because the callback completes after the class init.

Obviously I'm new to Swift so apologies if the terminology is sketchy.

I read this thread which talked about inversion of control pattern, and whilst it made sense, I couldn't work out how to actually initiate the class.

UserProfile.swift:

```<code>import UIKit
import Firebase
import FBSDKCoreKit

class UserProfile{

    var ref: DatabaseReference!

    var uid : String = ""
    var name : String = ""
    var location : String = ""
    //var posts = [String]()

    init(uid : String) {
        self.ref = Database.database().reference().child("user_profiles").child(uid)
        self.ref.observeSingleEvent(of: .value, with: { (snapshot) in
            let userObj = snapshot.value as? [String : AnyObject] ?? [:]
            self.uid = uid
            self.name = userObj["name"] as! String
            self.location = userObj["location"] as! String
        })
    }
}
</code>```

ViewController.swift

```<code>let user = UserProfile(uid : "NODEKEYINFIREBASE")
print(user)
</code>```

Output:

```<code>()
</code>```

答:
I'm not sure, that it is best practice, but I'm using completion handler for it.

Example:

1) Data item:

```<code>class Item {
   // properties...

   init(snapshot: [String: Any], _ key: String,
        completion: @escaping (_ item: Item) -> Void) {
     // some inits

     // some async task starts
         // completion(item)
   }
}
</code>```

2) Use:

```<code>let _ = Item(snapshot: value!, key) { item in
            // some tasks.. like
            self.newItem = item // or other
        }
</code>```

I think you should get the idea.

Hope it helps

Body:
How do I load data from an async callback into the parent class attributes?

I have a database in Firebase which holds my user profiles. I want to be able to pass in the node key and have it populate the object with the given values.

Because it works async, I am getting the default values from the object because the callback completes after the class init.

Obviously I'm new to Swift so apologies if the terminology is sketchy.

I read this thread which talked about inversion of control pattern, and whilst it made sense, I couldn't work out how to actually initiate the class.

UserProfile.swift:

import UIKit
import Firebase
import FBSDKCoreKit

class UserProfile{

    var ref: DatabaseReference!

    var uid : String = ""
    var name : String = ""
    var location : String = ""
    //var posts = [String]()

    init(uid : String) {
        self.ref = Database.database().reference().child("user_profiles").child(uid)
        self.ref.observeSingleEvent(of: .value, with: { (snapshot) in
            let userObj = snapshot.value as? [String : AnyObject] ?? [:]
            self.uid = uid
            self.name = userObj["name"] as! String
            self.location = userObj["location"] as! String
        })
    }
}

ViewController.swift

let user = UserProfile(uid : "NODEKEYINFIREBASE")
print(user)

Output:

()

Body:
I'm not sure, that it is best practice, but I'm using completion handler for it.

Example:

1) Data item:

class Item {
   // properties...

   init(snapshot: [String: Any], _ key: String,
        completion: @escaping (_ item: Item) -> Void) {
     // some inits

     // some async task starts
         // completion(item)
   }
}

2) Use:

let _ = Item(snapshot: value!, key) { item in
            // some tasks.. like
            self.newItem = item // or other
        }

I think you should get the idea.

Hope it helps


问:
UINavigationController Drill Down with Table View
I have a UITableView which lists the contents of my document directory. I have some zip files in that. If I touch a file in the UITableView, the corresponding zip file is unzipped and extracted in a temporary directory (NSTemporaryDirectory()).

The problem is how to navigate the contents which I extracted in a tableView. If suppose, the extracted zip file contains folders, I should able to view them in a tableView. Actually the flow should be like a drill-down.

I am able to extract the zip files, but problem is, have to navigate to them in a UITableView.

This is my didSelectRowAtIndexPath: part:

```<code>NSString *filePath = //filePath;
if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
    NSLog(@"File exists at path: %@",filePath);
} else {
    NSLog(@"File does not exists at path: %@", filePath);
}

NSString *tmpDir =NSTemporaryDirectory();
ZipArchive *zip = [[ZipArchive alloc] init];
BOOL result = NO;

if ([zip UnzipOpenFile:filePath]) {
    //zip file is there
    if ([zip UnzipFileTo:tmpDir overWrite:YES]) {
        //unzipped successfully
        NSLog(@"Archive unzip Success");
        result= YES;
    } else {
        NSLog(@"Failure To Extract Archive, maybe password?");
    }
} else  {
    NSLog(@"Failure To Open Archive");
}

if ([[NSFileManager defaultManager] fileExistsAtPath:tmpDir isDirectory:&isDir] && isDir) {
    NSLog(@"Its Folder");
    //Prepare to tableview.
    RootViewController *rvController =[[RootViewController alloc]initWithNibName:@"RootViewController"bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:rvController animated:YES];
}
</code>```

But this is not working. It's pushing the same contents in the document directory in the tableView.

答:
You need to use a UINavigationController that will handle the drill down.  Each drill down is a new UITableViewController.

You need a second UITableViewController subclass that will handle displaying the files contained in the zip.  It could have a NSString property that is the full path to the zip folder.  It uses the list of files in that directory as the data source.

Add the original tableView (controller) to the UINavigationController's rootView at startup.  When you tap the tableView that lists the zip files, you push onto the UINavigationController your second UITableViewController with a reference to the extracted files (a new folder?).

```<code>[UINavigationwController pushViewController:nextTableView animated:YES];
</code>```

See this legacy code example from Apple about drilling down in a UINavigationController. Also, check out the docs on UINavigationController from Apple.

Body:
I have a UITableView which lists the contents of my document directory. I have some zip files in that. If I touch a file in the UITableView, the corresponding zip file is unzipped and extracted in a temporary directory (NSTemporaryDirectory()).

The problem is how to navigate the contents which I extracted in a tableView. If suppose, the extracted zip file contains folders, I should able to view them in a tableView. Actually the flow should be like a drill-down.

I am able to extract the zip files, but problem is, have to navigate to them in a UITableView.

This is my didSelectRowAtIndexPath: part:

NSString *filePath = //filePath;
if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
    NSLog(@"File exists at path: %@",filePath);
} else {
    NSLog(@"File does not exists at path: %@", filePath);
}

NSString *tmpDir =NSTemporaryDirectory();
ZipArchive *zip = [[ZipArchive alloc] init];
BOOL result = NO;

if ([zip UnzipOpenFile:filePath]) {
    //zip file is there
    if ([zip UnzipFileTo:tmpDir overWrite:YES]) {
        //unzipped successfully
        NSLog(@"Archive unzip Success");
        result= YES;
    } else {
        NSLog(@"Failure To Extract Archive, maybe password?");
    }
} else  {
    NSLog(@"Failure To Open Archive");
}

if ([[NSFileManager defaultManager] fileExistsAtPath:tmpDir isDirectory:&isDir] && isDir) {
    NSLog(@"Its Folder");
    //Prepare to tableview.
    RootViewController *rvController =[[RootViewController alloc]initWithNibName:@"RootViewController"bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:rvController animated:YES];
}

But this is not working. It's pushing the same contents in the document directory in the tableView.

Body:
You need to use a UINavigationController that will handle the drill down.  Each drill down is a new UITableViewController.

You need a second UITableViewController subclass that will handle displaying the files contained in the zip.  It could have a NSString property that is the full path to the zip folder.  It uses the list of files in that directory as the data source.

Add the original tableView (controller) to the UINavigationController's rootView at startup.  When you tap the tableView that lists the zip files, you push onto the UINavigationController your second UITableViewController with a reference to the extracted files (a new folder?).

[UINavigationwController pushViewController:nextTableView animated:YES];

See this legacy code example from Apple about drilling down in a UINavigationController. Also, check out the docs on UINavigationController from Apple.