问:
Width="600" on parent table not respected in Outlook
I've built a responsive email which works in the majority of email clients

However in Outlook the parent table that makes the content 600 wide is not being respected - resulting in a broken layout.
>Image of broken email in outlook

I'm really stuck . Does anyone know why this might be happening?

JS Fiddle of my code --> https://jsfiddle.net/2m05tzf5/

```<code><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<td>
<center>
<!--[if (gte mso 9)|(IE)]>
<table width="600" align="center" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<![endif]-->
<table width="600" align="center" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse;" class="emailwrapto100pc" id="content">
</code>```

答: Try using CSS table{table-layout: fixed; width: 600px;}. Keep in mind that not all attributes and CSS rules are supported in all e-mail parsers


来源: stackexchange

问:
How to cut box corner Using CSS with transparent background?
I want to cut left top corner of a box using CSS like this.

keep in mind that background is transparent.

答:
With a pseudo and transform you can do that, and it has good browser support (from IE9)

body {
  background: url(https://picsum.photos/400/300) center / cover;
}

div {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
}

div::before {
  content: '';
  position: absolute;
  left: calc(50% + 25px);             /*  25px is height/width of the cut  */
  top: calc(50% + 25px);
  width: 141.5%;
  height: 141.5%;
  transform: translate(-50%,-50%)  rotate(45deg);
  background: #eee;
  opacity: 0.8;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

As pointed out, if you need it to scale on different aspect ratio's, use this

body {
  background: url(https://picsum.photos/400/300) center / cover;
}

div {
  position: relative;
  width: 80vw;
  height: 80vh;
  overflow: hidden;
}

div::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 1000%;
  height: 5000%;
  transform: rotate(45deg) translate(25px,-50%);   /* 25px for the cut height/width */
  transform-origin: left top;
  background: #eee;
  opacity: 0.8;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

ContentLicense: CC BY-SA 3.0

Body:
With a pseudo and transform you can do that, and it has good browser support (from IE9)

body {
  background: url(https://picsum.photos/400/300) center / cover;
}

div {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
}

div::before {
  content: '';
  position: absolute;
  left: calc(50% + 25px);             /*  25px is height/width of the cut  */
  top: calc(50% + 25px);
  width: 141.5%;
  height: 141.5%;
  transform: translate(-50%,-50%)  rotate(45deg);
  background: #eee;
  opacity: 0.8;
}

<div></div>

As pointed out, if you need it to scale on different aspect ratio's, use this

body {
  background: url(https://picsum.photos/400/300) center / cover;
}

div {
  position: relative;
  width: 80vw;
  height: 80vh;
  overflow: hidden;
}

div::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 1000%;
  height: 5000%;
  transform: rotate(45deg) translate(25px,-50%);   /* 25px for the cut height/width */
  transform-origin: left top;
  background: #eee;
  opacity: 0.8;
}

<div></div>


问:
xpath syntax for grabbing text data after a strong tag containing header text
```<code><li><strong>Movie Title:</strong> Training Day</li>
</code>```

How do I grab the textual content in this li tag; "Training Day"?

So I need to say 'if the strong tag has 'Movie Title' in it, return 'Training Day'.

I have tried stuff using the "following-sibling", but don't seem to be able to get this right.

Another attempt was

```<code>//li/text()[preceding::strong[contains(text(),'Movie Title')]]
</code>```

But this returns ALL text, not just what is inside the li class.

答:
Actually //li/text() should return "Training Day", while //li//text()- both "Training Day" and "Movie Title:"

You can try more specific XPath

```<code>//li[starts-with(., "Movie Title:")]//text()[not(parent::strong)]
</code>```

to get "Training Day" only

Body:
Movie Title: Training Day

How do I grab the textual content in this li tag; "Training Day"?

So I need to say 'if the strong tag has 'Movie Title' in it, return 'Training Day'.

I have tried stuff using the "following-sibling", but don't seem to be able to get this right.

Another attempt was

//li/text()[preceding::strong[contains(text(),'Movie Title')]]

But this returns ALL text, not just what is inside the li class.

Body:
Actually //li/text() should return "Training Day", while //li//text()- both "Training Day" and "Movie Title:"

You can try more specific XPath

//li[starts-with(., "Movie Title:")]//text()[not(parent::strong)]

to get "Training Day" only


问:
Routing Laravel namepsace issue
When I remove the inital use Illuminate\Http\Request and add use App\Item instead in the Controller file, the items/create route responds with a 404.  How can I still use the App\Item namespace and get to the items/create route? I've tried adding both, but does not work.

web.php

```<code>Route::get('items', 'ItemsController@index');
Route::get('items/{item}', 'ItemsController@show');
Route::get('items/create', 'ItemsController@create');
</code>```

ItemsController.php

```<code><?php

namespace App\Http\Controllers;

use App\Item;

class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show(Item $item){
      return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}
</code>```

Item.php

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    //
}
</code>```

答:
The problem is that laravel tries to match the routes in the order they are declared and the items/{item} route will match all routes starting with items/, including items/create. And because of the route model binding, Laravel tries to load an Item with ID create which obviously doesn't exist, so it throws a 404 error.

Route model binding in the docs:

Since the $user variable is type-hinted as the App\User Eloquent model
  and the variable name matches the {user} URI segment, Laravel will
  automatically inject the model instance that has an ID matching the
  corresponding value from the request URI. If a matching model instance
  is not found in the database, a 404 HTTP response will automatically
  be generated.

To fix it simply change the order of your routes and put items/{item} after all other item/* routes:

```<code>Route::get('items', 'ItemsController@index');
Route::get('items/create', 'ItemsController@create');
Route::get('items/{item}', 'ItemsController@show');
</code>```

Title: Routing Laravel namepsace issue

Body:
When I remove the inital use Illuminate\Http\Request and add use App\Item instead in the Controller file, the items/create route responds with a 404.  How can I still use the App\Item namespace and get to the items/create route? I've tried adding both, but does not work.

web.php

Route::get('items', 'ItemsController@index');
Route::get('items/{item}', 'ItemsController@show');
Route::get('items/create', 'ItemsController@create');

ItemsController.php

<?php

namespace App\Http\Controllers;

use App\Item;

class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show(Item $item){
      return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}

Item.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    //
}

Body:
The problem is that laravel tries to match the routes in the order they are declared and the items/{item} route will match all routes starting with items/, including items/create. And because of the route model binding, Laravel tries to load an Item with ID create which obviously doesn't exist, so it throws a 404 error.

Route model binding in the docs:

Since the $user variable is type-hinted as the App\User Eloquent model
  and the variable name matches the {user} URI segment, Laravel will
  automatically inject the model instance that has an ID matching the
  corresponding value from the request URI. If a matching model instance
  is not found in the database, a 404 HTTP response will automatically
  be generated.

To fix it simply change the order of your routes and put items/{item} after all other item/* routes:

Route::get('items', 'ItemsController@index');
Route::get('items/create', 'ItemsController@create');
Route::get('items/{item}', 'ItemsController@show');


问:
Laravel polymorphic relations and many ifs
I'm still learning Laravel, and I still have one thing I'm stuck on. In my transactions table in my database, I have two fields for a polymorphic relation:

```<code>paymentable_id
paymentable_type
</code>```

So I can add a Payment Plan or a Savings Plan or any other model, to a transaction.

The way I am doing this is, by having a couple of radio buttons in my view, to select which model has to be added. After making a selection, a dropdown appears to select which one has to be added, and this will submit a Payment Plan ID for example.

In my controller, I am then checking which has been submitted, and then attaching that one to my transaction:

```<code>if ($request['plan_id'])
{
    $plan = Plan::find($request['plan_id']);

    $plan->transactions()->save($transaction);
}

if ($request['saving_id'])
{
    $saving = Saving::find($request['saving_id']);

    $saving->transactions()->save($transaction);
}

// And a couple more, for Fixed Payments, Subscriptions, Budgets, and so on.
</code>```

And this is where I am stuck, I do not know the proper way to accomplish this, or even if polymorphic is the way to go for this (I'm pretty sure that it is though). Having like 5+ if's in my controller, or anywhere else for that matter, seems wrong to me.

答:
A simple solution, though might not be practicable, is to change your form to pass two values: 'plan_type', 'plan_id'. Then in your controller, you check which plan type is requested and defer to its model'

```<code>$planType = "App\\" . $request['plan_type'];

$plan = $planType::find($request['plan_id']);

$plan->transactions()->save($transaction);
</code>```

Of course, you need to validate the data, and check that the type submitted exists.

Body:
I'm still learning Laravel, and I still have one thing I'm stuck on. In my transactions table in my database, I have two fields for a polymorphic relation:

paymentable_id
paymentable_type

So I can add a Payment Plan or a Savings Plan or any other model, to a transaction.

The way I am doing this is, by having a couple of radio buttons in my view, to select which model has to be added. After making a selection, a dropdown appears to select which one has to be added, and this will submit a Payment Plan ID for example.

In my controller, I am then checking which has been submitted, and then attaching that one to my transaction:

if ($request['plan_id'])
{
    $plan = Plan::find($request['plan_id']);

    $plan->transactions()->save($transaction);
}

if ($request['saving_id'])
{
    $saving = Saving::find($request['saving_id']);

    $saving->transactions()->save($transaction);
}

// And a couple more, for Fixed Payments, Subscriptions, Budgets, and so on.

And this is where I am stuck, I do not know the proper way to accomplish this, or even if polymorphic is the way to go for this (I'm pretty sure that it is though). Having like 5+ if's in my controller, or anywhere else for that matter, seems wrong to me.

Body:
A simple solution, though might not be practicable, is to change your form to pass two values: 'plan_type', 'plan_id'. Then in your controller, you check which plan type is requested and defer to its model'

$planType = "App\\" . $request['plan_type'];

$plan = $planType::find($request['plan_id']);

$plan->transactions()->save($transaction);

Of course, you need to validate the data, and check that the type submitted exists.


问:
How to insert html in a child component in angular?
I'm trying to insert html into a child component. Basically something like this:

<custom-container>
Parnet content
</custom-container>

I can find references for passing data to child component but not able to find how to pass actual html inside my selector?

答:
You can also use <ng-content> with select attribute

Parent Component:

```<code><child-component>
    <div sample>Content form parent</div>
</child-component>
</code>```

Child Component:

```<code>something..
<ng-content select="[sample]"></ng-content>
some more...
</code>```

Output:

```<code>something..
<div>Content from parent</div>
some more...
</code>```

More details here

Body:
You can also use <ng-content> with select attribute

Parent Component:

<child-component>
    <div sample>Content form parent</div>
</child-component>

Child Component:

something..
<ng-content select="[sample]"></ng-content>
some more...

Output:

something..
<div>Content from parent</div>
some more...

More details here


问:
list.appendChild(TOCEntry) shows type Error: its not a function
```<code>function createTOC(){

    var list = document.getElementsByTagName("ul");
    var headingText;
    var TOCEntry;
    var i;
    for( i=1; i<=10; i++){
        headingText = document.getElementById(i);
        TOCEntry = document.createElement("li");
        TOCEntry = "<a href=#" + i + ">" + headingText + "</a>";
        list.appendChild(TOCEntry);
    }
}
</code>```

list.appendChild(TOCEntry) shows type Error: its not a function.

答:
You can try this out.
First, create a dom element
then assign its innerHTML
then add it to Dom</p>

```<code>  function createTOC(){

    var list = document.getElementById("id of ul");
    var headingText;
    var TOCEntry;
    var i;
    for( i=1; i<=10; i++){
       headingText = document.getElementById(i);
       TOCEntry = document.createElement("li");
       TOCEntryData = "<a href=#" + i + ">" + headingText + "</a>";
       TOCEntry.innerHtml = TOCEntryData;
       list.appendChild(TOCEntry);
    }
  }
</code>```

Body:
function createTOC(){

    var list = document.getElementsByTagName("ul");
    var headingText;
    var TOCEntry;
    var i;
    for( i=1; i<=10; i++){
        headingText = document.getElementById(i);
        TOCEntry = document.createElement("li");
        TOCEntry = "" + headingText + "";
        list.appendChild(TOCEntry);
    }
}

list.appendChild(TOCEntry) shows type Error: its not a function.

Body:
You can try this out.
First, create a dom element
then assign its innerHTML
then add it to Dom

  function createTOC(){

    var list = document.getElementById("id of ul");
    var headingText;
    var TOCEntry;
    var i;
    for( i=1; i<=10; i++){
       headingText = document.getElementById(i);
       TOCEntry = document.createElement("li");
       TOCEntryData = "<a href=#" + i + ">" + headingText + "</a>";
       TOCEntry.innerHtml = TOCEntryData;
       list.appendChild(TOCEntry);
    }
  }


问:
Xamarin UI Design - Xaml ToolBox
Hello Every one  iam  a beginner in Xamarin - Cross platforms

so when i downloaded it and starts to work on it ,    it has not  a UI ToolBox  like  the Android Studio   like a Mobile Device  which we Drag and drop the items and start to code    thats what i mean

is there some thing like that in Xaml -Xamarin Portable Shared  platforms

Or a Plugin  in NuGet   Display a ToolBox  with drag and drop  in Portable  App  [Andrid - Windows phone - IOS ]  all togethet

答:
There is no drag and drop in xamarin ,you need to code front end manually.
Xamarin has a xaml preview to show how the UI you coded looks.</p>

Title: Xamarin UI Design - Xaml ToolBox


问:
How to get selected row in NSTableView? view(atColumn:row:makeIfNecessary:) return nil
I have a NSTableview whose content is bound to NSArrayController.
And its selectionIndexes is bound to arrayController's selectionIndexes.
And this arrayController is bound to a NSManagedObjectContext.

Because arrayController's selectsInsertedObjects is true, so when I add an object to NSManagedObjectContext, tableViewSelectionDidChange(_ notification: Notification) will be called. I set a breakpoint here and debug in console (I set tableview's delegate to itself):

```<code>(lldb) po selectedRow
11
(lldb) po selectedCell()
nil
(lldb) po numberOfColumns
2
(lldb) po numberOfRows
12
(lldb) po view(atColumn: 0, row: 0, makeIfNecessary: false)
nil
(lldb) po view(atColumn: 0, row: selectedRow, makeIfNecessary: false)
nil
</code>```

I can see serval rows in the tableview.

But why po view(atColumn: 0, row: 0, makeIfNecessary: false) return nil?

How can I get the selected row in the delegate method tableViewSelectionDidChange(_ notification: Notification) ?

答:
I suspect that the table view posts NSTableViewSelectionDidChangeNotification before updating its layout. So you're asking the table view for a subview before it has created the subview.

This is what the makeIfNecessary parameter is for. Try it this way:

```<code>po view(atColumn: 0, row: selectedRow, makeIfNecessary: true)
</code>```

Body:
I have a NSTableview whose content is bound to NSArrayController.
And its selectionIndexes is bound to arrayController's selectionIndexes.
And this arrayController is bound to a NSManagedObjectContext.

Because arrayController's selectsInsertedObjects is true, so when I add an object to NSManagedObjectContext, tableViewSelectionDidChange(_ notification: Notification) will be called. I set a breakpoint here and debug in console (I set tableview's delegate to itself):

(lldb) po selectedRow
11
(lldb) po selectedCell()
nil
(lldb) po numberOfColumns
2
(lldb) po numberOfRows
12
(lldb) po view(atColumn: 0, row: 0, makeIfNecessary: false)
nil
(lldb) po view(atColumn: 0, row: selectedRow, makeIfNecessary: false)
nil

I can see serval rows in the tableview.

But why po view(atColumn: 0, row: 0, makeIfNecessary: false) return nil?

How can I get the selected row in the delegate method tableViewSelectionDidChange(_ notification: Notification) ?

Body:
I suspect that the table view posts NSTableViewSelectionDidChangeNotification before updating its layout. So you're asking the table view for a subview before it has created the subview.

This is what the makeIfNecessary parameter is for. Try it this way:

po view(atColumn: 0, row: selectedRow, makeIfNecessary: true)


问:
How can I clear an SQLite database each time I start my application?
I want my SQLite database instance to be wiped away when the program starts.

What I tried was make a method on my class MyDBAdapter.java like this:

```<code>public class MyDbAdapter {
    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";

    private static final int DATABASE_VERSION = 2;
    private final Context mCtx;
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }

    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    public List<Friend> retrieveAllUsers()
    {
        List <Friend> friends=new ArrayList<Friend>();

        Cursor result=fetchAllUsers();

        if( result.moveToFirst() ){
            do{
                //note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
                friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
            }while( result.moveToNext() );
        }

        return friends;
    }

}
</code>```

What is the best way to do this?

答:
Beside onCreate() and onUpgrade() you can override onOpen(). Drop all tables there and call onCreate().

```<code>public class MyApplication extends Application {
    protected static final String           LOG_TAG = "MyApplication";

    private static DatabaseAdapter          mDb;

    private static MyApplication    mInstance;

    /**
     * @return The instance of the database adapter.
     */
    public static DatabaseAdapter getDatabaseAdapter() {
        return mDb;
    }

    /**
     * @return The instance of the application.
     */
    public static Context getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.w(LOG_TAG, "Application::onCreate");
        mInstance = this;
        mDb = new DatabaseAdapter();
    }

    @Override
    public void onTerminate() {
        // Close the internal db
        getDatabaseAdapter().close(DatabaseAdapter.INTERNAL);

        Log.e(LOG_TAG, "::onTerminate::");
        super.onTerminate();
    }
}
</code>```

The advantage of subclassing Application is that this will be called always when your application is started or terminated. Independent of the activity that is started.
Global operations like open/close a database should be placed here.

Documentation:

Base class for those who need to
  maintain global application state. You
  can provide your own implementation by
  specifying its name in your
  AndroidManifest.xml's
  tag, which will cause that class to be
  instantiated for you when the process
  for your application/package is
  created.

Body:
I want my SQLite database instance to be wiped away when the program starts.

What I tried was make a method on my class MyDBAdapter.java like this:

public class MyDbAdapter {
    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";

    private static final int DATABASE_VERSION = 2;
    private final Context mCtx;
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }

    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    public List<Friend> retrieveAllUsers()
    {
        List <Friend> friends=new ArrayList<Friend>();

        Cursor result=fetchAllUsers();

        if( result.moveToFirst() ){
            do{
                //note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
                friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
            }while( result.moveToNext() );
        }

        return friends;
    }

}

What is the best way to do this?

Body:
Beside onCreate() and onUpgrade() you can override onOpen(). Drop all tables there and call onCreate().

public class MyApplication extends Application {
    protected static final String           LOG_TAG = "MyApplication";

    private static DatabaseAdapter          mDb;

    private static MyApplication    mInstance;

    /**
     * @return The instance of the database adapter.
     */
    public static DatabaseAdapter getDatabaseAdapter() {
        return mDb;
    }

    /**
     * @return The instance of the application.
     */
    public static Context getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.w(LOG_TAG, "Application::onCreate");
        mInstance = this;
        mDb = new DatabaseAdapter();
    }

    @Override
    public void onTerminate() {
        // Close the internal db
        getDatabaseAdapter().close(DatabaseAdapter.INTERNAL);

        Log.e(LOG_TAG, "::onTerminate::");
        super.onTerminate();
    }
}

The advantage of subclassing Application is that this will be called always when your application is started or terminated. Independent of the activity that is started.
Global operations like open/close a database should be placed here.

Documentation:

Base class for those who need to
  maintain global application state. You
  can provide your own implementation by
  specifying its name in your
  AndroidManifest.xml's
  tag, which will cause that class to be
  instantiated for you when the process
  for your application/package is
  created.

ContentLicense: CC BY-SA 2.5


问:
Compiler gives warning on performSelectorOnMainThread:@selector(delegateMethod)
I have an NSOperation that wraps some web service functionality. The NSOperation has a delegate that is to be messaged when the operation is over.

As the NSOperation lives on a different thread I have to make the call like this:

```<code>[delegate performSelectorOnMainThread:@selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];
</code>```

It works just fine, but it gives me a warning:

warning:
  '-performSelectorOnMainThread:withObject:waitUntilDone:'
  not found in protocol(s)

I completely agree with the compiler on this one, it sees a delegate, it checks the protocol, it finds no declaration of a performSelector method.

My question is: can I remove the warning by making this call in a different manner?

My two guesses are that I could (1) write a method called

```<code>- (void) callDelegateMethodOnMainThred {
    [delegate getDealersIDSuccess:result]
}
</code>```

and call that through performSelectorOnMainThread, but I find that solution to be cumbersome and an extra, hard to read, step on top of the delegation.

The second solution could be to cast the delegate to the type of my parent object inside the selector, but that is just plain crazy and goes against the delegate encapsulation pattern.

I would really appreciate a third solution from someone with a better understanding of the language:)

Thank you in advance.

EDIT: Added delegate declaration:

```<code>id <ISDealersIDDelegate> delegate;
</code>```

I declare my delegate as id. The delegate it self extends UIViewController.

I could see that declaring it NSObject would work.

答:
1) Declare your delegate's protocol to extend the NSObject protocol in the .h file

```<code>@protocol YourDelegateProtocol <NSObject>
</code>```

2) Cast to NSObject in your call

```<code>[(NSObject*)delegate performSelectorOnMainThread:@selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];
</code>```

I definitely recommend number (1).

Body:
I have an NSOperation that wraps some web service functionality. The NSOperation has a delegate that is to be messaged when the operation is over.

As the NSOperation lives on a different thread I have to make the call like this:

[delegate performSelectorOnMainThread:@selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];

It works just fine, but it gives me a warning:

warning:
  '-performSelectorOnMainThread:withObject:waitUntilDone:'
  not found in protocol(s)

I completely agree with the compiler on this one, it sees a delegate, it checks the protocol, it finds no declaration of a performSelector method.

My question is: can I remove the warning by making this call in a different manner?

My two guesses are that I could (1) write a method called

- (void) callDelegateMethodOnMainThred {
    [delegate getDealersIDSuccess:result]
}

and call that through performSelectorOnMainThread, but I find that solution to be cumbersome and an extra, hard to read, step on top of the delegation.

The second solution could be to cast the delegate to the type of my parent object inside the selector, but that is just plain crazy and goes against the delegate encapsulation pattern.

I would really appreciate a third solution from someone with a better understanding of the language:)

Thank you in advance.

EDIT: Added delegate declaration:

id <ISDealersIDDelegate> delegate;

I declare my delegate as id. The delegate it self extends UIViewController.

I could see that declaring it NSObject would work.

Body:
1) Declare your delegate's protocol to extend the NSObject protocol in the .h file

@protocol YourDelegateProtocol <NSObject>

2) Cast to NSObject in your call

[(NSObject*)delegate performSelectorOnMainThread:@selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];

I definitely recommend number (1).


问:
Would cuDNN v6.0 work with TensorFlow currently?
Do we specifically need cuDNN v5.1 (as suggested) for TensorFlow, or would the latest version (v6.0) work as well? Is there backward compatibility in cuDNN versions?</p>

答:
No, cuDNN 6.0 is not supported in the latest 1.2 version. But there is a hope: the official release notes tell the following:

TensorFlow 1.2 may be the last time we build with cuDNN 5.1. Starting
  with TensorFlow 1.3, we will try to build all our prebuilt binaries
  with cuDNN 6.0. While we will try to keep our source code compatible
  with cuDNN 5.1, it will be best effort.

So hopefully the next 1.3 version will use cuDNN 6.0. Especially now, when 7.0 is right around the corner.


问:
rmarkdown - embed sparkline into a bootstrap popover
I'm trying to display a sparkline in a popover. I'm using rmarkdown to create my html document.

Here is my attempt:

```<code>---
title: "test_embed_popup"
author: "me"
date: "16 June 2017"
output: html_document
---

```{r}
library(sparkline)
library(htmltools)
library(bsplus)

bsplus::use_bs_popover()

button_content <-
  spk_chr(c(1:5))

tags$button(type = "button", class = "btn btn-default", "A button") %>%
  bs_embed_popover(title = "I'm a popover", content = button_content, html = "true") %>%
  sparkline::spk_add_deps()
```
</code>```

when i knit this document, the button with the popover appears however no sparkline is in the popover. I would like to display the sparkline in the popover.

Any help much appreciated.

答:
I have fiddled with this a bit - I think that the underlying problem is that the JavaScript is not being executed. This is discussed here:

Execute JS inside of a Bootstrap popover

I think the proposed solution is probably out of scope (at least for now) for bsplus - but I've made an issue to remind myself.

Body:
I'm trying to display a sparkline in a popover. I'm using rmarkdown to create my html document.

Here is my attempt:

---
title: "test_embed_popup"
author: "me"
date: "16 June 2017"
output: html_document
---

```{r}
library(sparkline)
library(htmltools)
library(bsplus)

bsplus::use_bs_popover()

button_content <-
  spk_chr(c(1:5))

tags$button(type = "button", class = "btn btn-default", "A button") %>%
  bs_embed_popover(title = "I'm a popover", content = button_content, html = "true") %>%
  sparkline::spk_add_deps()
```

when i knit this document, the button with the popover appears however no sparkline is in the popover. I would like to display the sparkline in the popover.

Any help much appreciated.


问:
sonar analysis for .net core project
Hi all am using sonarqube v5.6.6

plugins:

Sonarqube v5.6.6

sonar fxcop plugin v1.0

Sonar c# v6.0

I am trying to do sonar analysis for .Net core(v1.1) project(c# language) build using VS2017 community edition. i searched in net regarding this issue & got few links like link1, link2, link3 of stackoverflow but all points the sonar
 JIRATkt167 and its states that closed but still i didn't get any idea for how to run the sonar anlysis for .Net core project.

So please suggest me any documents or video to run same.

Please feel free to ask if you need any further details. sample code(which i used to do sonar analysis).

答:
Sorry its a false alarm i didn't get the point in the JIRATkt167 they have moved the issue to new tkt JIRAtkt310 & this new tkt is still open & still the issue is not resolved.

Thanks & Regards

Vival

Title: sonar analysis for .net core project


问:
Why does git uses 2 different commands to show HEAD?
I noticed there are 2 HEADs:

.git\HEAD

.git\refs\remotes\origin\HEAD

When I use git show-ref HEAD, it only gives me this:

```<code>ce0762c073b407d794f54f0b5d2a50375fdcb609 refs/remotes/origin/HEAD
</code>```

Whle when I use git rev-parse HEAD, it gives me the value of .git\HEAD:

```<code>a758e523fe40e799194878bac567b7f4b8eec2b9
</code>```

Why Git use 2 different commands to show HEAD? Any strong reason?

答:
git-show-ref shows a list of references in your repository and their commit IDs. It should probably be called git-show-refs. It's preferred over directly referencing files in the .git directory.

When you say git show-ref HEAD you're not asking for HEAD. What you're asking for is any references in the list which match the pattern HEAD. HEAD itself is normally filtered out, so you get refs/remotes/origin/HEAD. You can include HEAD with --head.

```<code>$ git show-ref --head HEAD
f37beeea95f3b0e6b064f6d4b5f835a058e0568c HEAD
aa1124b89f38eed793e2b9f2d2b2ba5d80a27a20 refs/remotes/origin/HEAD
</code>```

So you shouldn't be using git show-ref <ref> to look up references.

git-rev-parse takes a revision parameter and gives back a commit ID. Its meant to deal with the myriad different ways you can refer to a commit. For example...

```<code>$ git rev-parse --verify master
aa1124b89f38eed793e2b9f2d2b2ba5d80a27a20
$ git rev-parse --verify heads/master
aa1124b89f38eed793e2b9f2d2b2ba5d80a27a20
$ git rev-parse --verify refs/heads/master
aa1124b89f38eed793e2b9f2d2b2ba5d80a27a20
</code>```

git rev-parse --verify <ref> is what you should be using to look up the commit ID of a reference.

ContentLicense: CC BY-SA 4.0

Body:
I noticed there are 2 HEADs:

.git\HEAD

.git\refs\remotes\origin\HEAD

When I use git show-ref HEAD, it only gives me this:

ce0762c073b407d794f54f0b5d2a50375fdcb609 refs/remotes/origin/HEAD

Whle when I use git rev-parse HEAD, it gives me the value of .git\HEAD:

a758e523fe40e799194878bac567b7f4b8eec2b9

Why Git use 2 different commands to show HEAD? Any strong reason?

Body:
git-show-ref shows a list of references in your repository and their commit IDs. It should probably be called git-show-refs. It's preferred over directly referencing files in the .git directory.

When you say git show-ref HEAD you're not asking for HEAD. What you're asking for is any references in the list which match the pattern HEAD. HEAD itself is normally filtered out, so you get refs/remotes/origin/HEAD. You can include HEAD with --head.

$ git show-ref --head HEAD
f37beeea95f3b0e6b064f6d4b5f835a058e0568c HEAD
aa1124b89f38eed793e2b9f2d2b2ba5d80a27a20 refs/remotes/origin/HEAD

So you shouldn't be using git show-ref <ref> to look up references.

git-rev-parse takes a revision parameter and gives back a commit ID. Its meant to deal with the myriad different ways you can refer to a commit. For example...

$ git rev-parse --verify master
aa1124b89f38eed793e2b9f2d2b2ba5d80a27a20
$ git rev-parse --verify heads/master
aa1124b89f38eed793e2b9f2d2b2ba5d80a27a20
$ git rev-parse --verify refs/heads/master
aa1124b89f38eed793e2b9f2d2b2ba5d80a27a20

git rev-parse --verify <ref> is what you should be using to look up the commit ID of a reference.


问:
What is query_cache_min_res_unit in mysql mariadb?
What is query_cache_min_res_unit option in mysql when setting query caching. Also i have seen a word block when reading about query_cache_min_res_unit on the internet but i didn't understand what that block word mean.

Can any one tell me in simple and easy words what these two means and where and why these two are used ?

答:
Have a look here:
https://mariadb.com/kb/en/mariadb/query-cache/

It says:

There are two main ways to limit the size of the query cache. First,
  the overall size in bytes is determined by the query_cache_size server
  variable. About 40KB is needed for various query cache structures.

The query cache size is allocated in 1024 byte-blocks, thus it should
  be set to a multiple of 1024.

The query result is stored using a minimum block size of
  query_cache_min_res_unit. Check two conditions to use a good value of
  this variable: Query cache insert result blocks with locks, each new
  block insert lock query cache, a small value will increase locks and
  fragmentation and waste less memory for small results, a big value
  will increase memory use wasting more memory for small results but it
  reduce locks. Test with your workload for fine tune this variable.


问:
webview memory leak in OSX
How to avoid memory leak of webview
when i close webview window memory is not release which is consume by webview.
i am tried many solutions from existing answers like

1. load blank page in webview

2. stop loading

3. webview=nil

4. delegate=nil

5. clear cache

6. clear cookies

答:
It is amazing that the memory leak occurs in Mac OS befor 10.12, such as 10.11, 10.11.

Although the webview dealloc normally, the occupied memory only release half and the app memory still remain heigh.

However, the occupied memory in OS 10.12 & 10.13 is entirely releaase after the webview dealloc

Title: webview memory leak in OSX


问:
MOD Function Exclusively Uses Long Variables In Excel VBA
UPDATED
I'm cleaning up this post after its resolution. To summarize, I was making a user defined formula for excel that calculated the next highest prime number (=NextHighestPrimeNumber(100) returns 101). As I begin experimenting, I noticed the formula would error on around 2.1 billion. I assumed it might have been connected to my variable so I tried DOUBLE, but I still received errors.

Here is the function:

```<code>Function NextHighestPrimeNumber(StartingNumber As Double) As Variant
Dim CeilingTest As Long
Dim i As Long

If StartingNumber < 11 Then
            If StartingNumber > 6 Then
                NextHighestPrimeNumber = 11

            ElseIf StartingNumber > 4 Then
                NextHighestPrimeNumber = 7

            ElseIf StartingNumber > 2 Then
                NextHighestPrimeNumber = 5

            ElseIf StartingNumber > 0 Then
                NextHighestPrimeNumber = 3

            ElseIf StartingNumber = 0 Then
                NextHighestPrimeNumber = 1

            Else
                NextHighestPrimeNumber = "Pick A Positive Integer"

            End If

        Exit Function

Else

    'Create Array
    ReDim Prime_Array(0 To 4) As Double
    GoTo StartArrayPopulate
DoneWithStartingArray:

    If StartingNumber Mod 2 = 0 Then
        StartingNumber = StartingNumber - 1
    End If

NewNumber:
        StartingNumber = StartingNumber + 2
        CeilingTest = Int(VBA.Sqr(StartingNumber))

    'Array loop
    For i = LBound(Prime_Array) To UBound(Prime_Array)
        If Prime_Array(i) > CeilingTest Then
            NextHighestPrimeNumber = StartingNumber
            Exit Function
        ElseIf StartingNumber Mod Prime_Array(i) = 0 Then GoTo NewNumber

        End If
    Next i

    'Add new Array Value
ExpandDim:
    ReDim Preserve Prime_Array(UBound(Prime_Array) + 1)
    Prime_Array(UBound(Prime_Array)) = NextHighestPrimeNumber(Prime_Array(UBound(Prime_Array) - 1))

    'test if bigger than cieling
    If Prime_Array(UBound(Prime_Array)) > CeilingTest Then
        NextHighestPrimeNumber = StartingNumber
        Exit Function

    ElseIf StartingNumber Mod Prime_Array(UBound(Prime_Array)) = 0 Then GoTo NewNumber

    Else
        GoTo ExpandDim
    End If

End If

Exit Function

StartArrayPopulate:

Prime_Array(0) = 3
Prime_Array(1) = 5
Prime_Array(2) = 7
Prime_Array(3) = 11
Prime_Array(4) = 13

GoTo DoneWithStartingArray

End Function
</code>```

答:
The issue is because the VBA MOD function ALWAYS converts the numerator to a LONG variable, even when it is previously defined as Double or is a hard coded number!

Test yourself:

MsgBox (2147483647) mod 3 'Maximum Long Value

Vs.

MsgBox (2147483647 + 1) mod 3'Oh False!

I used the INT function to duplicate the mod calculation Numerator -(INT(Numerator /Denominator)*Denominator) but there are a lot of other creative ways to avoid. Even Evaluate with the excel MOD function worked correctly.

Bottomline: I'm never going to use MOD for any calculations that could potentially be exceeding 2 Billion

I've cleaned up my code significantly since my first post and left the bad rows commented out that were throwing errors flagged with `zz failed code:

```<code>Function NextHighestPrimeNumber(StartingNumber As Double) As Variant
Dim CeilingTest As Long
Dim i As Long

If StartingNumber < 11 Then
            If StartingNumber > 6 Then
                NextHighestPrimeNumber = 11

            ElseIf StartingNumber > 4 Then
                NextHighestPrimeNumber = 7

            ElseIf StartingNumber > 2 Then
                NextHighestPrimeNumber = 5

            ElseIf StartingNumber > 0 Then
                NextHighestPrimeNumber = 3

            ElseIf StartingNumber = 0 Then
                NextHighestPrimeNumber = 1

            Else
                NextHighestPrimeNumber = "Pick A Positive Integer"

            End If

        Exit Function

Else

    'Create Array
    ReDim Prime_Array(0 To 4) As Double
    GoTo StartArrayPopulate
DoneWithStartingArray:

    'zz failed code: If StartingNumber Mod 2 = 0 Then
    If StartingNumber - (Int(StartingNumber / 2) * 2) = 0 Then
        StartingNumber = StartingNumber - 1
    End If

NewNumber:
        StartingNumber = StartingNumber + 2
        CeilingTest = INT(VBA.Sqr(StartingNumber))

    'Array loop
    For i = LBound(Prime_Array) To UBound(Prime_Array)
        If Prime_Array(i) > CeilingTest Then
            NextHighestPrimeNumber = StartingNumber
            Exit Function
        'zz failed code: ElseIf StartingNumber Mod Prime_Array(i) = 0 Then
GoTo NewNumber
        ElseIf StartingNumber - (Int(StartingNumber / Prime_Array(i)) * Prime_Array(i)) = 0 Then GoTo NewNumber
        End If
    Next i

    'Add new Array Value
ExpandDim:
    ReDim Preserve Prime_Array(UBound(Prime_Array) + 1)
    Prime_Array(UBound(Prime_Array)) = NextHighestPrimeNumber(Prime_Array(UBound(Prime_Array) - 1))

    'test if bigger than ceiling
    If Prime_Array(UBound(Prime_Array)) > CeilingTest Then
        NextHighestPrimeNumber = StartingNumber
        Exit Function

    'zz failed code: ElseIf StartingNumber Mod Prime_Array(UBound(Prime_Array)) = 0 Then GoTo NewNumber
    ElseIf StartingNumber - (Int(StartingNumber / Prime_Array(UBound(Prime_Array))) * Prime_Array(UBound(Prime_Array))) = 0 Then GoTo NewNumber

    Else
        GoTo ExpandDim
    End If

End If

Exit Function

StartArrayPopulate:
Prime_Array(0) = 3
Prime_Array(1) = 5
Prime_Array(2) = 7
Prime_Array(3) = 11
Prime_Array(4) = 13

GoTo DoneWithStartingArray

End Function
</code>```

Body:
UPDATED
I'm cleaning up this post after its resolution. To summarize, I was making a user defined formula for excel that calculated the next highest prime number (=NextHighestPrimeNumber(100) returns 101). As I begin experimenting, I noticed the formula would error on around 2.1 billion. I assumed it might have been connected to my variable so I tried DOUBLE, but I still received errors.

Here is the function:

Function NextHighestPrimeNumber(StartingNumber As Double) As Variant
Dim CeilingTest As Long
Dim i As Long

If StartingNumber < 11 Then
            If StartingNumber > 6 Then
                NextHighestPrimeNumber = 11

            ElseIf StartingNumber > 4 Then
                NextHighestPrimeNumber = 7

            ElseIf StartingNumber > 2 Then
                NextHighestPrimeNumber = 5

            ElseIf StartingNumber > 0 Then
                NextHighestPrimeNumber = 3

            ElseIf StartingNumber = 0 Then
                NextHighestPrimeNumber = 1

            Else
                NextHighestPrimeNumber = "Pick A Positive Integer"

            End If

        Exit Function

Else

    'Create Array
    ReDim Prime_Array(0 To 4) As Double
    GoTo StartArrayPopulate
DoneWithStartingArray:

    If StartingNumber Mod 2 = 0 Then
        StartingNumber = StartingNumber - 1
    End If

NewNumber:
        StartingNumber = StartingNumber + 2
        CeilingTest = Int(VBA.Sqr(StartingNumber))

    'Array loop
    For i = LBound(Prime_Array) To UBound(Prime_Array)
        If Prime_Array(i) > CeilingTest Then
            NextHighestPrimeNumber = StartingNumber
            Exit Function
        ElseIf StartingNumber Mod Prime_Array(i) = 0 Then GoTo NewNumber

        End If
    Next i

    'Add new Array Value
ExpandDim:
    ReDim Preserve Prime_Array(UBound(Prime_Array) + 1)
    Prime_Array(UBound(Prime_Array)) = NextHighestPrimeNumber(Prime_Array(UBound(Prime_Array) - 1))

    'test if bigger than cieling
    If Prime_Array(UBound(Prime_Array)) > CeilingTest Then
        NextHighestPrimeNumber = StartingNumber
        Exit Function

    ElseIf StartingNumber Mod Prime_Array(UBound(Prime_Array)) = 0 Then GoTo NewNumber

    Else
        GoTo ExpandDim
    End If

End If

Exit Function

StartArrayPopulate:

Prime_Array(0) = 3
Prime_Array(1) = 5
Prime_Array(2) = 7
Prime_Array(3) = 11
Prime_Array(4) = 13

GoTo DoneWithStartingArray

End Function

Body:
The issue is because the VBA MOD function ALWAYS converts the numerator to a LONG variable, even when it is previously defined as Double or is a hard coded number!

Test yourself:

MsgBox (2147483647) mod 3 'Maximum Long Value

Vs.

MsgBox (2147483647 + 1) mod 3'Oh False!

I used the INT function to duplicate the mod calculation Numerator -(INT(Numerator /Denominator)*Denominator) but there are a lot of other creative ways to avoid. Even Evaluate with the excel MOD function worked correctly.

Bottomline: I'm never going to use MOD for any calculations that could potentially be exceeding 2 Billion

I've cleaned up my code significantly since my first post and left the bad rows commented out that were throwing errors flagged with `zz failed code:

Function NextHighestPrimeNumber(StartingNumber As Double) As Variant
Dim CeilingTest As Long
Dim i As Long

If StartingNumber < 11 Then
            If StartingNumber > 6 Then
                NextHighestPrimeNumber = 11

            ElseIf StartingNumber > 4 Then
                NextHighestPrimeNumber = 7

            ElseIf StartingNumber > 2 Then
                NextHighestPrimeNumber = 5

            ElseIf StartingNumber > 0 Then
                NextHighestPrimeNumber = 3

            ElseIf StartingNumber = 0 Then
                NextHighestPrimeNumber = 1

            Else
                NextHighestPrimeNumber = "Pick A Positive Integer"

            End If

        Exit Function

Else

    'Create Array
    ReDim Prime_Array(0 To 4) As Double
    GoTo StartArrayPopulate
DoneWithStartingArray:

    'zz failed code: If StartingNumber Mod 2 = 0 Then
    If StartingNumber - (Int(StartingNumber / 2) * 2) = 0 Then
        StartingNumber = StartingNumber - 1
    End If

NewNumber:
        StartingNumber = StartingNumber + 2
        CeilingTest = INT(VBA.Sqr(StartingNumber))

    'Array loop
    For i = LBound(Prime_Array) To UBound(Prime_Array)
        If Prime_Array(i) > CeilingTest Then
            NextHighestPrimeNumber = StartingNumber
            Exit Function
        'zz failed code: ElseIf StartingNumber Mod Prime_Array(i) = 0 Then
GoTo NewNumber
        ElseIf StartingNumber - (Int(StartingNumber / Prime_Array(i)) * Prime_Array(i)) = 0 Then GoTo NewNumber
        End If
    Next i

    'Add new Array Value
ExpandDim:
    ReDim Preserve Prime_Array(UBound(Prime_Array) + 1)
    Prime_Array(UBound(Prime_Array)) = NextHighestPrimeNumber(Prime_Array(UBound(Prime_Array) - 1))

    'test if bigger than ceiling
    If Prime_Array(UBound(Prime_Array)) > CeilingTest Then
        NextHighestPrimeNumber = StartingNumber
        Exit Function

    'zz failed code: ElseIf StartingNumber Mod Prime_Array(UBound(Prime_Array)) = 0 Then GoTo NewNumber
    ElseIf StartingNumber - (Int(StartingNumber / Prime_Array(UBound(Prime_Array))) * Prime_Array(UBound(Prime_Array))) = 0 Then GoTo NewNumber

    Else
        GoTo ExpandDim
    End If

End If

Exit Function

StartArrayPopulate:
Prime_Array(0) = 3
Prime_Array(1) = 5
Prime_Array(2) = 7
Prime_Array(3) = 11
Prime_Array(4) = 13

GoTo DoneWithStartingArray

End Function


问:
Why does the using directive not "associate" with ordinary functions?
According to this question it is valid to define class methods after a using directive, instead of enclosing them within a namespace block.

However, that seems not to be the case for ordinary functions. Consider:

Greeting.hh

```<code>#pragma once

namespace NS
{
    class Greeting
    {
    public:
        void hello();
    };

    void otherHello();
}
</code>```

Greeting.cc

```<code>#include "Greeting.hh"
#include <iostream>

using namespace NS;

void Greeting::hello()
{
    std::cout << "Greeting::hello" << std::endl;
}

void otherHello()
{
    std::cout << "otherHello" << std::endl;
}
</code>```

main.cc

```<code>#include "Greeting.hh"

int main()
{
    NS::Greeting o;
    o.hello();
    NS::otherHello();
}
</code>```

This won't compile, yielding the following error message:

```<code>undefined reference to `NS::otherHello()'
</code>```

Further inspection indicates that otherHello's symbol is not preceded by the namespace, while Greeting::hello's is:

```<code>g++ -std=c++14 -pedantic -Wall -c Greeting.cc
nm -C Greeting.o | grep T
000000000000002a T otherHello()
0000000000000000 T NS::Greeting::hello()
</code>```

Does this contradict with the Standard reference from the accepted answer?

"During unqualified name lookup (3.4.1), the names appear as if they
  were declared in the nearest enclosing namespace which contains both
  the using-directive and the nominated namespace."

答:
What's important to remember is that

Function declarations in different namespaces don't interfere with each other.

A definition of a function is also a declaration.

[namespace.def/4]

The enclosing namespaces of a declaration are those namespaces in
  which the declaration lexically appears, except for a redeclaration of
  a namespace member outside its original namespace (e.g., a definition
  as specified in [namespace.memdef]). Such a redeclaration has the same
  enclosing namespaces as the original declaration.

So let's look at the otherHello definition. Where does it lexically appear? In the global namespace of course. That's also the point of declaration for it. Which means the enclosing namespace is the global one, and you end up with a declaration of ::otherHello.

So no, this doesn't contradict the standard quote from the accepted answer to the other question. Member functions can be defined outside of the class, so long as they are qualified by their class name ([class.mfct/4]):

If the definition of a member function is lexically outside its class
  definition, the member function name shall be qualified by its class
  name using the :: operator.

So we need only ask, does Greeting name the same class as NS::Greeting? Why, yes it does. The using directive is responsible for that.

I'll add this segment in the hope of clarifying. Consider this code snippet:

```<code>namespace NS1 {
    namespace NS2 {
        void hello();
    }
}

using namespace NS1;

void NS2::hello() {

}

int main() {
    NS1::NS2::hello();
    return 0;
}
</code>```

When the compiler encounters NS2::hello being defined it preforms name lookup for that declarator id. According to [basic.lookup.qual/3]:

In a declaration in which the declarator-id is a qualified-id, names
  used before the qualified-id being declared are looked up in the
  defining namespace scope; names following the qualified-id are looked
  up in the scope of the member's class or namespace.

So NS2 is looked up in the defining scope (the global one), and according to the unqualified name lookup rule you quoted, it is found and resolved as NS1::NS2. That's how NS2::hello is associated with NS1::NS2::hello and resolved as defining it.

In the global namespace of the OP, otherHello isn't preceded by anything. Therefore name lookup doesn't occur. It immediately defines that function in the enclosing namespace, as I previously quoted.

Body:
According to this question it is valid to define class methods after a using directive, instead of enclosing them within a namespace block.

However, that seems not to be the case for ordinary functions. Consider:

Greeting.hh

#pragma once

namespace NS
{
    class Greeting
    {
    public:
        void hello();
    };

    void otherHello();
}

Greeting.cc

#include "Greeting.hh"
#include <iostream>

using namespace NS;

void Greeting::hello()
{
    std::cout << "Greeting::hello" << std::endl;
}

void otherHello()
{
    std::cout << "otherHello" << std::endl;
}

main.cc

#include "Greeting.hh"

int main()
{
    NS::Greeting o;
    o.hello();
    NS::otherHello();
}

This won't compile, yielding the following error message:

undefined reference to `NS::otherHello()'

Further inspection indicates that otherHello's symbol is not preceded by the namespace, while Greeting::hello's is:

g++ -std=c++14 -pedantic -Wall -c Greeting.cc
nm -C Greeting.o | grep T
000000000000002a T otherHello()
0000000000000000 T NS::Greeting::hello()

Does this contradict with the Standard reference from the accepted answer?

"During unqualified name lookup (3.4.1), the names appear as if they
  were declared in the nearest enclosing namespace which contains both
  the using-directive and the nominated namespace."

Body:
What's important to remember is that

Function declarations in different namespaces don't interfere with each other.

A definition of a function is also a declaration.

[namespace.def/4]

The enclosing namespaces of a declaration are those namespaces in
  which the declaration lexically appears, except for a redeclaration of
  a namespace member outside its original namespace (e.g., a definition
  as specified in [namespace.memdef]). Such a redeclaration has the same
  enclosing namespaces as the original declaration.

So let's look at the otherHello definition. Where does it lexically appear? In the global namespace of course. That's also the point of declaration for it. Which means the enclosing namespace is the global one, and you end up with a declaration of ::otherHello.

So no, this doesn't contradict the standard quote from the accepted answer to the other question. Member functions can be defined outside of the class, so long as they are qualified by their class name ([class.mfct/4]):

If the definition of a member function is lexically outside its class
  definition, the member function name shall be qualified by its class
  name using the :: operator.

So we need only ask, does Greeting name the same class as NS::Greeting? Why, yes it does. The using directive is responsible for that.

I'll add this segment in the hope of clarifying. Consider this code snippet:

namespace NS1 {
    namespace NS2 {
        void hello();
    }
}

using namespace NS1;

void NS2::hello() {

}

int main() {
    NS1::NS2::hello();
    return 0;
}

When the compiler encounters NS2::hello being defined it preforms name lookup for that declarator id. According to [basic.lookup.qual/3]:

In a declaration in which the declarator-id is a qualified-id, names
  used before the qualified-id being declared are looked up in the
  defining namespace scope; names following the qualified-id are looked
  up in the scope of the member's class or namespace.

So NS2 is looked up in the defining scope (the global one), and according to the unqualified name lookup rule you quoted, it is found and resolved as NS1::NS2. That's how NS2::hello is associated with NS1::NS2::hello and resolved as defining it.

In the global namespace of the OP, otherHello isn't preceded by anything. Therefore name lookup doesn't occur. It immediately defines that function in the enclosing namespace, as I previously quoted.


问:
Gradle - Intellij modules workspace
Is there a way to have different modules in Intellij depends on my current working environment?

E.g.
Workspace:

Module A - Android App

Module B - Android Lib

Module C - Acceptance Tests

Module D - Feature Tests

Module E - Android Test App for libs

Configuration 1 - working on app and lib

Module A

Module B

Configuration 2 - working on tester app

Module A

Module B

Module E

Configuration 3 - tests

all modules

I'm using gradle building tool and I store my modules in settings.gradle.
I would be appreciate to be able to manipulate the list of modules in settings.gradle file from the Intellij however it could be some better way for it.

答:
The only way (that I know of) to do this to create new blank IntelliJ projects for each configuration and then import the modules in which you are interested into each project.

EDIT: A second way that might work for you is to use the favourites. Open up the favourites windows and add 3 new favourites lists, one for each set up. Then go to a module in the project view and select "add to favourites" and select the relevant list. Repeat this for each module and list.

Again it's not quite what you want but might be good enough.

Title: Gradle - Intellij modules workspace


问:
How to set confirm message for reset button?
This is my current code:

<%= button_tag "Reset", type: :reset, data: { confirm: 'Are you sure?' } %>

which generates:

<button name="button" type="reset" data-confirm="Are you sure?">Reset</button>

The confirm message doesn’t show at all. So I have to change to this:

<button type="reset" onclick="return confirm('Are you sure?')" />

This one works! But is there any way I can do this in a more railsy way?

If I remove type: :reset, the message shows but that obviously is not what I want to do.

答:
Try with:

```<code><%= button_tag( :type => 'reset', :class => "btn", :data => { :confirm => 'Are you sure?' }) do %>
Reset
<% end %>
</code>```

I have tested in on rails 4.2.4 and it works fine.

Body:
Try with:

<%= button_tag( :type => 'reset', :class => "btn", :data => { :confirm => 'Are you sure?' }) do %>
Reset
<% end %>

I have tested in on rails 4.2.4 and it works fine.


问:
OpenMP seems not running in parallel
I am trying my first openmp program in c++, my code is:

```<code>#pragma omp parallel for num_threads(2)
for (int i=0;i<16;++i)
{
    printf( "Thread %d works with idx %d\n", omp_get_thread_num(), i);
}
</code>```

I compiled with g++ -O3 -fopenmp -std=c++11

However, when I run the program, I got:

```<code>Thread 0 works with idx 0
Thread 0 works with idx 1
Thread 0 works with idx 2
Thread 0 works with idx 3
Thread 0 works with idx 4
Thread 0 works with idx 5
Thread 0 works with idx 6
Thread 0 works with idx 7
Thread 1 works with idx 8
Thread 1 works with idx 9
Thread 1 works with idx 10
Thread 1 works with idx 11
Thread 1 works with idx 12
Thread 1 works with idx 13
Thread 1 works with idx 14
Thread 1 works with idx 15
</code>```

Is it running in parallel? I was expecting something like thread0 - thread1 - thread0 - thread1, one after another.

What would be the problem here?

答:
Yes, it is running in parallel. You can seen the IDs from two different threads being printed.

I was expecting something like thread0 - thread1 - thread0 - thread1,
  one after another.

Since you did not defined the scheduling of your parallel loop, by default it will divide the loop iterations into blocks and assign them to the threads. In your case thread 0 have the block from 0 to 7 and thread 1 the block from 8 - 15.

If you want threads to work in a round-robin fashion (one after the another) you have to declare a static parallel for with scheduling of chunk = 1, like : #pragma omp parallel for schedule (static,1)

```<code>#pragma omp parallel for schedule (static,1) num_threads(2)
for (int i=0;i<16;++i)
{
    printf( "Thread %d works with idx %d\n", omp_get_thread_num(), i);
}
</code>```

More about the openMP Loop static Scheduling :

Divide the loop into equal-sized chunks or as equal as possible in the
  case where the number of loop iterations is not evenly divisible by
  the number of threads multiplied by the chunk size. By default, chunk
  size is loop_count/number_of_threads.Set chunk to 1 to interleave the
  iterations.

Source : OpenMP* Loop Scheduling

Title: OpenMP seems not running in parallel

Body:
I am trying my first openmp program in c++, my code is:

#pragma omp parallel for num_threads(2)
for (int i=0;i<16;++i)
{
    printf( "Thread %d works with idx %d\n", omp_get_thread_num(), i);
}

I compiled with g++ -O3 -fopenmp -std=c++11

However, when I run the program, I got:

Thread 0 works with idx 0
Thread 0 works with idx 1
Thread 0 works with idx 2
Thread 0 works with idx 3
Thread 0 works with idx 4
Thread 0 works with idx 5
Thread 0 works with idx 6
Thread 0 works with idx 7
Thread 1 works with idx 8
Thread 1 works with idx 9
Thread 1 works with idx 10
Thread 1 works with idx 11
Thread 1 works with idx 12
Thread 1 works with idx 13
Thread 1 works with idx 14
Thread 1 works with idx 15

Is it running in parallel? I was expecting something like thread0 - thread1 - thread0 - thread1, one after another.

What would be the problem here?

Body:
Yes, it is running in parallel. You can seen the IDs from two different threads being printed.

I was expecting something like thread0 - thread1 - thread0 - thread1,
  one after another.

Since you did not defined the scheduling of your parallel loop, by default it will divide the loop iterations into blocks and assign them to the threads. In your case thread 0 have the block from 0 to 7 and thread 1 the block from 8 - 15.

If you want threads to work in a round-robin fashion (one after the another) you have to declare a static parallel for with scheduling of chunk = 1, like : #pragma omp parallel for schedule (static,1)

#pragma omp parallel for schedule (static,1) num_threads(2)
for (int i=0;i<16;++i)
{
    printf( "Thread %d works with idx %d\n", omp_get_thread_num(), i);
}

More about the openMP Loop static Scheduling :

Divide the loop into equal-sized chunks or as equal as possible in the
  case where the number of loop iterations is not evenly divisible by
  the number of threads multiplied by the chunk size. By default, chunk
  size is loop_count/number_of_threads.Set chunk to 1 to interleave the
  iterations.

Source : OpenMP* Loop Scheduling


问:
Comparing two columns in excel, inserting blank rows and moving associated data

I entered the Cells in Column A, B, C, D, AND I Want the result as entered in F, G, H, I, so what formula i should insert i the cells

答:
F3 would be:

```<code>=IF(ISERROR(MATCH(ROW()-2,A:A,0)),"",ROW()-2)
</code>```

And G3:

```<code>=IF(LEN(F3),INDEX(B:B,MATCH(F3,A:A,0)),"")
</code>```

copy F3:G3 to H3:I3 and "auto fill" down as you need to

Body:
F3 would be:

=IF(ISERROR(MATCH(ROW()-2,A:A,0)),"",ROW()-2)

And G3:

=IF(LEN(F3),INDEX(B:B,MATCH(F3,A:A,0)),"")

copy F3:G3 to H3:I3 and "auto fill" down as you need to


问:
Endless RecyclerView data loading logic is not consistent on all devices
I'm loading data from SQLite database in RecyclerView in batch of 25 records per load cycle. I figure out every thing but having problem with logic of calling data loading method in RecyclerView scroll listener.

Problem is list is loading nicely on scroll of recyclerView in emulator but when i tested in physical device, on Lenovo Phab 2 it worked fine but in Mi note 3, list doesn't load consistenly (sometime it loads, sometime not) more records on reaching bottom of scroll.

Below is the code I'm using in RecyclerView scrolle listener

```<code>private val RecyclerView_ScrollListener = object : RecyclerView.OnScrollListener(){
    override fun onScrolled(recyclerView1: RecyclerView?, dx: Int, dy: Int) {
        super.onScrolled(recyclerView1, dx, dy)

        if (dy > 0) {
            if (limit < rowCount_fromDatabase) {
                visibleItemCount = layoutManager_MemberList.childCount
                totalItemCount = layoutManager_MemberList.itemCount
                firstVisibleItemPosition = layoutManager_MemberList.findFirstVisibleItemPosition()

                if (visibleItemCount + firstVisibleItemPosition >= totalItemCount) {
                    limit += 25
                    load_Data()
                }
            }
        }
}
</code>```

答:
I have written a class, that works with all types of LayoutManagers. It was tested on emulators and real devices.

It has blockers for preventing double loading of next page. When Listener.onListEndReached() returns true, it won't be called again, untill RecyclerViewOnScrollUpdater.loading will be set to false.

Also you can set visibleThreshold and enable/disable page loading via setting enabled.

Body:
I'm loading data from SQLite database in RecyclerView in batch of 25 records per load cycle. I figure out every thing but having problem with logic of calling data loading method in RecyclerView scroll listener.

Problem is list is loading nicely on scroll of recyclerView in emulator but when i tested in physical device, on Lenovo Phab 2 it worked fine but in Mi note 3, list doesn't load consistenly (sometime it loads, sometime not) more records on reaching bottom of scroll.

Below is the code I'm using in RecyclerView scrolle listener

private val RecyclerView_ScrollListener = object : RecyclerView.OnScrollListener(){
    override fun onScrolled(recyclerView1: RecyclerView?, dx: Int, dy: Int) {
        super.onScrolled(recyclerView1, dx, dy)

        if (dy > 0) {
            if (limit < rowCount_fromDatabase) {
                visibleItemCount = layoutManager_MemberList.childCount
                totalItemCount = layoutManager_MemberList.itemCount
                firstVisibleItemPosition = layoutManager_MemberList.findFirstVisibleItemPosition()

                if (visibleItemCount + firstVisibleItemPosition >= totalItemCount) {
                    limit += 25
                    load_Data()
                }
            }
        }
}


问:
Hide/show more text within a certain length across multiple fields
I want to have a text to only be a certain amount of characters/length and after that length, I want to put a link to reveal the full length of the text. But not only that, I want this functionality working across multiple text fields. In this case I'm using Laravel, hence the blade template.

HTML/Blade:

```<code>@foreach ($statuses as $status)
   <div class="status-body" data-body-status-id="{{ $status->id }}">
       <div class="status-body-text status-body-text-{{ $status->id }}">{!! $status->body !!}</div>
   </div>
   <div class="btn-overflow btn-overflow-{{ $status->id }}" data-id-value="{{ $status->id }}">Show</div>
@endforeach
</code>```

Scripts:

```<code>var text = $('.status-body-text'),
     btn = $('.btn-overflow'),
       h = text[0].scrollHeight;

if(h > 45) {
    btn.addClass('less');
    btn.css('display', 'block');
}

btn.click(function(e)
{
  e.stopPropagation();

  if (btn.hasClass('less')) {
      btn.removeClass('less');
      btn.addClass('more');
      btn.text('Hide');

      text.animate({'height': h});
  } else {
      btn.addClass('less');
      btn.removeClass('more');
      btn.text('Show');
      text.animate({'height': '45px'});
  }
});
</code>```

Styling:

```<code>.btn-overflow {
display: none;
border-radius: 3px;
text-align: center;
width: 42px;
margin: 0 auto;

}
.status-body-text {
height:45px;
display:block;
overflow:hidden;
word-break: break-word;
word-wrap: break-word;
}
</code>```

Working fiddle: https://jsfiddle.net/jmzqsc1r/1/

Now as you can see, the intended functionality works. The exceeding text is hidden, the show button only shows up when .status-body-text exceeds 45px, the animation is nice, etc.

The problem is that this solution is only intended for a single one of these  on the page, whereas on my page I may have hundreds of these. As you can expect, only the first .status-body-text is hidden initially (if it exceeds 45px), and a show/hide button affects all .status-body-text fields.

My attempt at fixing this was to try to implement data attributes identifiers, but I couldn't seem to find a good solution.

The identifiers are still in the markup, such as btn-overflow-{{ $status->id }}, which will have the same ending number as its corresponding status-body-text-{{ $status->id }}.

Any help would be appreciated.

Edit:

Shiladitya's answer was helpful, but if you reduce the text size of the second text box, it still shows the Show button. Alternatively, if you reduce the size of the first text box, the show button doesn't appear on the second box. Like so: jsfiddle.net/jmzqsc1r/4

答:
Here you go with the solution https://jsfiddle.net/jmzqsc1r/3/

var text = $('.status-body-text'),
     btn = $('.btn-overflow'),
       h = text[0].scrollHeight;

if(h > 45) {
 btn.addClass('less');
 btn.css('display', 'block');
}

btn.click(function(e)
{
  e.stopPropagation();

  if ($(this).hasClass('less')) {
      $(this).removeClass('less');
      $(this).addClass('more');
      $(this).text('Hide');

      $('#cont' + $(this).attr('val')).animate({'height': h});
  } else {
      $(this).addClass('less');
      $(this).removeClass('more');
      $(this).text('Show');
       $('#cont' + $(this).attr('val')).animate({'height': '45px'});
  }
}); ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-overflow {
display: none;
border-radius: 3px;
text-align: center;
margin: 0 auto;
}
.status-body-text {
height:45px;
display:block;
overflow:hidden;
word-break: break-word;
word-wrap: break-word;
}</code>```

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.sad sdadsadsadsadsa
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.sad sdadsadsadsadsa

Show

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.sad sdadsadsadsadsa
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.sad sdadsadsadsadsa

Show```

I just modified part of the code & it works as you are expecting it.

Body:
I want to have a text to only be a certain amount of characters/length and after that length, I want to put a link to reveal the full length of the text. But not only that, I want this functionality working across multiple text fields. In this case I'm using Laravel, hence the blade template.

HTML/Blade:

@foreach ($statuses as $status)

id }}">

id }}">{!! $status->body !!}

id }}" data-id-value="{{ $status->id }}">Show

@endforeach

Scripts:

var text = $('.status-body-text'),
     btn = $('.btn-overflow'),
       h = text[0].scrollHeight;

if(h > 45) {
    btn.addClass('less');
    btn.css('display', 'block');
}

btn.click(function(e)
{
  e.stopPropagation();

  if (btn.hasClass('less')) {
      btn.removeClass('less');
      btn.addClass('more');
      btn.text('Hide');

      text.animate({'height': h});
  } else {
      btn.addClass('less');
      btn.removeClass('more');
      btn.text('Show');
      text.animate({'height': '45px'});
  }
});

Styling:

.btn-overflow {
display: none;
border-radius: 3px;
text-align: center;
width: 42px;
margin: 0 auto;

}
.status-body-text {
height:45px;
display:block;
overflow:hidden;
word-break: break-word;
word-wrap: break-word;
}

Working fiddle: https://jsfiddle.net/jmzqsc1r/1/

Now as you can see, the intended functionality works. The exceeding text is hidden, the show button only shows up when .status-body-text exceeds 45px, the animation is nice, etc.

The problem is that this solution is only intended for a single one of these  on the page, whereas on my page I may have hundreds of these. As you can expect, only the first .status-body-text is hidden initially (if it exceeds 45px), and a show/hide button affects all .status-body-text fields.

My attempt at fixing this was to try to implement data attributes identifiers, but I couldn't seem to find a good solution.

The identifiers are still in the markup, such as btn-overflow-{{ $status->id }}, which will have the same ending number as its corresponding status-body-text-{{ $status->id }}.

Any help would be appreciated.

Edit:

Shiladitya's answer was helpful, but if you reduce the text size of the second text box, it still shows the Show button. Alternatively, if you reduce the size of the first text box, the show button doesn't appear on the second box. Like so: jsfiddle.net/jmzqsc1r/4

Body:
Here you go with the solution https://jsfiddle.net/jmzqsc1r/3/

var text = $('.status-body-text'),
     btn = $('.btn-overflow'),
       h = text[0].scrollHeight;

if(h > 45) {
 btn.addClass('less');
 btn.css('display', 'block');
}

btn.click(function(e)
{
  e.stopPropagation();

  if ($(this).hasClass('less')) {
      $(this).removeClass('less');
      $(this).addClass('more');
      $(this).text('Hide');

      $('#cont' + $(this).attr('val')).animate({'height': h});
  } else {
      $(this).addClass('less');
      $(this).removeClass('more');
      $(this).text('Show');
       $('#cont' + $(this).attr('val')).animate({'height': '45px'});
  }
});

.btn-overflow {
display: none;
border-radius: 3px;
text-align: center;
margin: 0 auto;
}
.status-body-text {
height:45px;
display:block;
overflow:hidden;
word-break: break-word;
word-wrap: break-word;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="status-body-text" id="cont1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.sad sdadsadsadsadsa
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.sad sdadsadsadsadsa
</div>
<a class="btn-overflow" href="#" val="1">Show</a>

<div class="status-body-text" id="cont2">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.sad sdadsadsadsadsa
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.sad sdadsadsadsadsa
</div>
<a class="btn-overflow" href="#" val="2">Show</a>

I just modified part of the code & it works as you are expecting it.


问:
How to show "read more" link after 3 buttons
In this code, I want to display show more link, after 3 buttons:
I know, how to display show more button after x words, but how to display show more link after buttons?

This is my code to display show more link after x words, if it helps:

jQuery(function(){

    var minimized_elements = $('span.showmore');

    minimized_elements.each(function(){
        var t = $(this).text();
        if(t.length < 410) return;

        $(this).html(
            t.slice(0,410)+'... Show More'+
            ''+ t.slice(410,t.length)+' Less'
        );

    });

    $('a.more', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).hide().prev().hide();
        $(this).next().show();
    });

    $('a.less', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).parent().hide().prev().show().prev().show();
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="playtrailer">Trailer 1</button>
<button class="playtrailer">Trailer 2</button>
<button class="playtrailer">Trailer 3 HD</button>
<button class="playtrailer">Trailer 4 SD</button>
<button class="playtrailer">Trailer 5</button>
<button class="playtrailer">Trailer 6</button>
<button class="playtrailer">Video</button></code>```

答:
Very Easy to do like below:-

$(document).ready(function(){
  $( "button.playtrailer" ).eq(2).after('Show More');//add a unique id to link
  $( "button.playtrailer:gt(2)" ).addClass('hide');
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $('button.playtrailer').removeClass('hide');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide{
  display:none;
}</code>```

<button class="playtrailer">Trailer 1</button>
<button class="playtrailer">Trailer 2</button>
<button class="playtrailer">Trailer 3 HD</button>
<button class="playtrailer">Trailer 4 SD</button>
<button class="playtrailer">Trailer 5</button>
<button class="playtrailer">Trailer 6</button>
<button class="playtrailer">Video</button>```

Body:
In this code, I want to display show more link, after 3 buttons:
I know, how to display show more button after x words, but how to display show more link after buttons?

This is my code to display show more link after x words, if it helps:

jQuery(function(){

    var minimized_elements = $('span.showmore');

    minimized_elements.each(function(){
        var t = $(this).text();
        if(t.length < 410) return;

        $(this).html(
            t.slice(0,410)+'... Show More'+
            ''+ t.slice(410,t.length)+' Less'
        );

    });

    $('a.more', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).hide().prev().hide();
        $(this).next().show();
    });

    $('a.less', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).parent().hide().prev().show().prev().show();
    });

});

<button class="playtrailer">Trailer 1</button>
<button class="playtrailer">Trailer 2</button>
<button class="playtrailer">Trailer 3 HD</button>
<button class="playtrailer">Trailer 4 SD</button>
<button class="playtrailer">Trailer 5</button>
<button class="playtrailer">Trailer 6</button>
<button class="playtrailer">Video</button>

Body:
Very Easy to do like below:-

$(document).ready(function(){
  $( "button.playtrailer" ).eq(2).after('<a href="#" id="particular">Show More</a>');//add a unique id to link
  $( "button.playtrailer:gt(2)" ).addClass('hide');
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $('button.playtrailer').removeClass('hide');
});

.hide{
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="playtrailer">Trailer 1</button>
<button class="playtrailer">Trailer 2</button>
<button class="playtrailer">Trailer 3 HD</button>
<button class="playtrailer">Trailer 4 SD</button>
<button class="playtrailer">Trailer 5</button>
<button class="playtrailer">Trailer 6</button>
<button class="playtrailer">Video</button>


问:
Add reference to .dll asp.net
I have a simple question about adding references to a .NET project. I'm adding reCAPTCHA to a website and i have downloaded the dll.

After setting the reference to the dll i build and run the project and gets this error:

```<code>[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
   System.Reflection.Module._GetTypesInternal(StackCrawlMark& stackMark) +0
   System.Reflection.Assembly.GetTypes() +96
   StarSuite.Core.Settings.GetSingletonInstancesOfBaseType(Type baseType, String staticMethodName, Type returnType) +149

[ApplicationException: Unable to load types from 'Recaptcha, Version=1.0.5.0, Culture=neutral, PublicKeyToken=9afc4d65b28c38c2'. LoaderExceptions: [FileNotFoundException: Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
]
</code>```

What am i missing, why do i get this error?

答: Sorry if the question is silly...Is it your web project MVC? It seems that If you're using web form based project you shouldn't use that component since it relies on mvc assemblies (maybe there is a web form version?).</p>

Title: Add reference to .dll asp.net

Body:
I have a simple question about adding references to a .NET project. I'm adding reCAPTCHA to a website and i have downloaded the dll.

After setting the reference to the dll i build and run the project and gets this error:

[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
   System.Reflection.Module._GetTypesInternal(StackCrawlMark& stackMark) +0
   System.Reflection.Assembly.GetTypes() +96
   StarSuite.Core.Settings.GetSingletonInstancesOfBaseType(Type baseType, String staticMethodName, Type returnType) +149

[ApplicationException: Unable to load types from 'Recaptcha, Version=1.0.5.0, Culture=neutral, PublicKeyToken=9afc4d65b28c38c2'. LoaderExceptions: [FileNotFoundException: Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
]

What am i missing, why do i get this error?