问:
How can I format this VBA RegExp?
Currently taking the names from the names of some .xlsx files the having the following formats:

IT-Name LastName -VP Name LastName - Report - Month Year

IT-Name LastName - Report - Month Year

Name LastName-Name LastName - Month Year

Name LastName - Report - Month Year

and so on...
I can easily separate the names from the - report - month year and -vp parts and put them into a LastName, Name format.

The problem I'm currently having is that some of the names will have dashes in them. For example something along the lines Bob Smith-Jones.

I am new to using VBA and RegEx and this is the pattern I'm using to separate the names once they're in a Name LastName[ ]?[-][ ]?Name LastName format.

```<code>'                      Name         LastName       -        Name            LastName
objRegEx2.Pattern = "([a-zA-Z]*)[ ]([a-zA-Z]*)[ ]?[-]?[ ]?(([a-zA-Z]*)[ ]([a-zA-Z]*))?"
newFile = objRegEx2.Replace(newFile, "$2, $1, $5, $4")
'To remove ", , " when there is only one name
newFile = Replace(newFile, ", , ", "")
</code>```

Is there any way to get a name with the Bob Smith-Jones format into a Smith-Jones, Bob format? Currently they end up in a Smith, BobJones format

答:
You're not far off - you can use:

```<code>([a-zA-Z]+)[ ]([a-zA-Z\-]+)( \- )([a-zA-Z]+)[ ]([a-zA-Z\-]+)
</code>```

Note you need to escape the - in the 'LastName' part with a \ because as you can see - is a special regex character.

To get the ,s between the names I updated the replace clause to "$2, $1 $3 $5, $4".

If you want to match names like Billy-Bob Smith as well as Bob Smith-Jones you can put the additional \- in the first-name parts of the pattern like:

```<code>([a-zA-Z\-]+)[ ]([a-zA-Z\-]+)( \- )([a-zA-Z\-]+)[ ]([a-zA-Z\-]+)
</code>```

Test code (in Excel):

```<code>Option Explicit

Sub Test()

    Dim objRegex As Object
    Dim strPattern As String
    Dim strInput As String
    Dim strOutput As String

    strPattern = "([a-zA-Z\-]+)[ ]([a-zA-Z\-]+)( \- )([a-zA-Z\-]+)[ ]([a-zA-Z\-]+)"
    Set objRegex = CreateObject("VBScript.RegExp")
    objRegex.Pattern = strPattern

    strInput = "Billy-Bob Smith - Terry Smith-Jones - July 2017"
    strOutput = objRegex.Replace(strInput, "$2, $1 $3 $5, $4")

    Debug.Print strOutput

End Sub
</code>```

Gives:

```<code>Smith, Billy-Bob  -  Smith-Jones, Terry - July 2017
</code>```

Title: How can I format this VBA RegExp?

Body:
Currently taking the names from the names of some .xlsx files the having the following formats:

IT-Name LastName -VP Name LastName - Report - Month Year

IT-Name LastName - Report - Month Year

Name LastName-Name LastName - Month Year

Name LastName - Report - Month Year

and so on...
I can easily separate the names from the - report - month year and -vp parts and put them into a LastName, Name format.

The problem I'm currently having is that some of the names will have dashes in them. For example something along the lines Bob Smith-Jones.

I am new to using VBA and RegEx and this is the pattern I'm using to separate the names once they're in a Name LastName[ ]?[-][ ]?Name LastName format.

'                      Name         LastName       -        Name            LastName
objRegEx2.Pattern = "([a-zA-Z]*)[ ]([a-zA-Z]*)[ ]?[-]?[ ]?(([a-zA-Z]*)[ ]([a-zA-Z]*))?"
newFile = objRegEx2.Replace(newFile, "$2, $1, $5, $4")
'To remove ", , " when there is only one name
newFile = Replace(newFile, ", , ", "")

Is there any way to get a name with the Bob Smith-Jones format into a Smith-Jones, Bob format? Currently they end up in a Smith, BobJones format

Body:
You're not far off - you can use:

([a-zA-Z]+)[ ]([a-zA-Z\-]+)( \- )([a-zA-Z]+)[ ]([a-zA-Z\-]+)

Note you need to escape the - in the 'LastName' part with a \ because as you can see - is a special regex character.

To get the ,s between the names I updated the replace clause to "$2, $1 $3 $5, $4".

If you want to match names like Billy-Bob Smith as well as Bob Smith-Jones you can put the additional \- in the first-name parts of the pattern like:

([a-zA-Z\-]+)[ ]([a-zA-Z\-]+)( \- )([a-zA-Z\-]+)[ ]([a-zA-Z\-]+)

Test code (in Excel):

Option Explicit

Sub Test()

    Dim objRegex As Object
    Dim strPattern As String
    Dim strInput As String
    Dim strOutput As String

    strPattern = "([a-zA-Z\-]+)[ ]([a-zA-Z\-]+)( \- )([a-zA-Z\-]+)[ ]([a-zA-Z\-]+)"
    Set objRegex = CreateObject("VBScript.RegExp")
    objRegex.Pattern = strPattern

    strInput = "Billy-Bob Smith - Terry Smith-Jones - July 2017"
    strOutput = objRegex.Replace(strInput, "$2, $1 $3 $5, $4")

    Debug.Print strOutput

End Sub

Gives:

Smith, Billy-Bob  -  Smith-Jones, Terry - July 2017


来源: stackexchange

问:
Django form field errors in templates
Django templates allow access to field errors via field.errors.as_ul.  In Python, however, field has no attribute errors.  How does this work?

My particular problem is that I tried serializing the forms (and the errors) and on the deserialization everything works in python, but errors don't show up if I ask explicitly for them via field.errors.as_ul.  They do show up via field.errors, though: basically, the list of strings shows.

Can someone explain this?

答: There are actually two separate classes for fields - the field elements you declare in your form, and a BoundField class which is automatically created by the form and which contains any bound data and errors.

ContentLicense: CC BY-SA 2.5

Title: Django form field errors in templates


问:
How to loop through DIV id element to check style None or Block
I want to loop through DIV id element in order to check the style if its none/block?

Code to check against

// The below code can perform that but just once.

if($('#loadingProgressContainer').css('display') == 'none')
{
 console.log("Display = NONE !!!");
}
else
{
 console.log("Display = BLOCK !!");
}

//I tried with the below code but not working

while ($('#loadingProgressContainer').css('display') != 'none')
{
   console.log("Display = BLOCK !!");
}

console.log("Display = NONE !!!");```
<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>
<div id="tbNewStyleWrapper" style="position: relative;">
  <div id="loadingProgressContainer" style="display: block;">
  <div id="loadingProgressElement">
  <p><h1>Test Please...</h1></p>
   <img src="http://www.dev.tasch.co.za/airportshuttle2/components/com_taxibooking/assets/images/ajax-loader-bar.gif">
  </div>
  </div>
    </div></code>```

答:
If you need to repeatedly check for the element visibility you could use setInterval(). This is NOT the best way to do this, but is a quick solution. The second argument of set interval is how often you want the function to run in milliseconds. The code below will run every 3 seconds. </p>

```<code>setInterval(function(){
   if($('#loadingProgressContainer').css('display') == 'none')
   {
      console.log("Display = NONE !!!");
   }
   else
  {
     console.log("Display = BLOCK !!");
  }
     }, 3000);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to loop through DIV id element in order to check the style if its none/block?

Code to check against

// The below code can perform that but just once.

if($('#loadingProgressContainer').css('display') == 'none')
{
 console.log("Display = NONE !!!");
}
else
{
 console.log("Display = BLOCK !!");
}

//I tried with the below code but not working

while ($('#loadingProgressContainer').css('display') != 'none')
{
   console.log("Display = BLOCK !!");
}

console.log("Display = NONE !!!");

Test Please...

Body:
If you need to repeatedly check for the element visibility you could use setInterval(). This is NOT the best way to do this, but is a quick solution. The second argument of set interval is how often you want the function to run in milliseconds. The code below will run every 3 seconds.

setInterval(function(){
   if($('#loadingProgressContainer').css('display') == 'none')
   {
      console.log("Display = NONE !!!");
   }
   else
  {
     console.log("Display = BLOCK !!");
  }
     }, 3000);


问:
How to load hook for particular controller
I am new in codeigniter. I want to load hooks for admin panel controller.  </p>

```<code>$hook['post_controller_constructor'][] = array(
    'class'    => 'AdminData',
    'function' => 'myfunction',
    'filename' => 'loginhelp.php',
    'filepath' => 'hooks',
    'params'   => array()
);
</code>```

答:
```<code>    Application/config/hooks.php

    $hook['post_controller'] = array(
            'class'    => 'LogoutBlockedUser',
            'function' => 'logout',
            'filename' => 'LogoutBlockedUser.php',
            'filepath' => 'hooks',
            'params'   => ""
    );

    Enable hooks in config.php
    $config['enable_hooks'] = TRUE;

    Application/hooks/LogoutBlockedUser.php

    class LogoutBlockedUser {

    public function __construct()
    {

    }

    public function logout()
    {
        $CI =& get_instance();
        if(!(empty($CI->session->userdata('user_id'))))
        {
            $CI->load->model('Your_model', 'web');
            $result = $CI->common->select_query;
            if(!empty($result))
            {
                $CI->session->unset_userdata('user_id');
                session_destroy();
                redirect(base_url() . 'yourcontroller/function');
            }
        }

    }

}
</code>```

Body:
I am new in codeigniter. I want to load hooks for admin panel controller.

$hook['post_controller_constructor'][] = array(
    'class'    => 'AdminData',
    'function' => 'myfunction',
    'filename' => 'loginhelp.php',
    'filepath' => 'hooks',
    'params'   => array()
);


问:
How to remove all non-uppercase characters in a string?
Yeah I'm basically just trying to explode a phrase like Social Inc. or David Jason to SI and DJ. I've tried using explode but couldn't figure out how to explode everything BUT the capital letters, do I need to use preg_match()?

答:
You can use this regex (?![A-Z]). with preg_replace() to replace every char except the one in uppercase.

```<code>preg_replace("/(?![A-Z])./", "", $yourvariable)
</code>```

The regex  will look for anythings NOT an uppercase letter ( ?! negative lookahead ).

I've created a regex101 if you wish to test it with other cases.

EDIT As an update of this thread, You could also use the ^ char inside the square braquets to reverse  the effect.

```<code>preg_replace("/([^A-Z])./", "", $yourvariable)
</code>```

This will match all char that are not uppercase and replace them with nothing.

Body:
You can use this regex (?![A-Z]). with preg_replace() to replace every char except the one in uppercase.

preg_replace("/(?![A-Z])./", "", $yourvariable)

The regex  will look for anythings NOT an uppercase letter ( ?! negative lookahead ).

I've created a regex101 if you wish to test it with other cases.

EDIT As an update of this thread, You could also use the ^ char inside the square braquets to reverse  the effect.

preg_replace("/([^A-Z])./", "", $yourvariable)

This will match all char that are not uppercase and replace them with nothing.

ContentLicense: CC BY-SA 4.0


问:
How should the model feedback to the view in android MVP?
I am using MVP to decouple my view and model in my android application. I need to know how the model should feedback the result of the business logic to the view.

If for example a button is pressed to login, the activity would be like this, using butterknife @OnClick annotation:

```<code>@OnClick(R.id.login_button)
public void login() {
    String email = mEmailEditText.getText().toString();
    String password = mPasswordEditText.getText().toString();
    LoginCredentials loginCredentials = new LoginCredentials(email, password);
    mPresenter.loginWithEmail(loginCredentials);
}
</code>```

The presenter would then validate and make a request to the repository:

```<code>public void loginWithEmail(LoginCredentials loginCredentials) {
    boolean isEmailValid = AuthValidator.validateEmail(loginCredentials.getUsername());
    boolean isPasswordValid = AuthValidator.validatePassword(loginCredentials.getPassword());

    if(isEmailValid && isPasswordValid) repository.loginEmailUser(loginCredentials);

    if (!isEmailValid) view.handleInvalidEmail();

    if (!isPasswordValid) view.handleInvalidPassword();
}
</code>```

The repository would then execute the business logic:

```<code>@Override
public void loginEmailUser(LoginCredentials loginCredentials) {
    Call<Token> call = userServiceApi.loginInToken(loginCredentials);
    call.enqueue(new Callback<Token>() {
        @Override
        public void onResponse(@NonNull Call<Token> call, @NonNull Response<Token> response) {
            if (response.isSuccessful()) {
                // handle successful login
            } else {
                // Handle unsuccessful login
            }
        }

        @Override
        public void onFailure(@NonNull Call<Token> call, @NonNull Throwable t) {
            // Handle failed request
        }
    });
</code>```

Where the comments say // handle unsuccessful something, how does the model feedback to the view the outcomes of the business logic so that the view can handle these outcomes?

Thank you.

答:
You can use a interface as callback, for example :

```<code>public interface RepositoryCallback {

   void onLoginEmailUserSuccess(/*paramaters if you need*/);
   void onLoginEmailUserError(/*paramaters if you need*/);
   void onRequestFailed(/*paramaters if you need*/)

}
</code>```

In the repository defined the listener

```<code>public class MyRepository {

    private RepositoryCallback mListener;

    @Override
    public void loginEmailUser(LoginCredentials loginCredentials) {
        Call<Token> call = userServiceApi.loginInToken(loginCredentials);
        call.enqueue(new Callback<Token>() {
            @Override
            public void onResponse(@NonNull Call<Token> call, @NonNull Response<Token> response) {
                if (response.isSuccessful()) {
                    // handle successful login
                    if (mListener != null) {
                        mListener.onLoginEmailUserSuccess()
                    }
                } else {
                    // Handle unsuccessful login
                   if (mListener != null) {
                       mListener.onLoginEmailUserError()
                   }
                }
            }

            @Override
            public void onFailure(@NonNull Call<Token> call, @NonNull Throwable t) {
                // Handle failed request
                if (mListener != null) {
                    mListener.onRequestFailed()
                }
            }
        });

    public void setRepositoryCallback(RepositoryCallback listener) {
        mListener = listener;
    }

}
</code>```

Then set the presenter as listener :

```<code>public class MyPresenter implements RepositoryCallback {

    public void loginWithEmail(LoginCredentials loginCredentials) {
        repository.setRepositoryCallback(this) // here or in the presenter constructor
        boolean isEmailValid = AuthValidator.validateEmail(loginCredentials.getUsername());
        boolean isPasswordValid = AuthValidator.validatePassword(loginCredentials.getPassword());

        if(isEmailValid && isPasswordValid) repository.loginEmailUser(loginCredentials);

        if (!isEmailValid) view.handleInvalidEmail();

        if (!isPasswordValid) view.handleInvalidPassword();
    }

    @Override
    public void onLoginEmailUserSuccess(//paramaters if you need){
        // your code
    }

    @Override
    public void onLoginEmailUserError(//paramaters if you need){
        // your code
    }

    @Override
    public void onRequestFailed(//paramaters if you need){
        // your code
    }

}
</code>```

Hope this helps.

Sorry for my english.

Body:
I am using MVP to decouple my view and model in my android application. I need to know how the model should feedback the result of the business logic to the view.

If for example a button is pressed to login, the activity would be like this, using butterknife @OnClick annotation:

@OnClick(R.id.login_button)
public void login() {
    String email = mEmailEditText.getText().toString();
    String password = mPasswordEditText.getText().toString();
    LoginCredentials loginCredentials = new LoginCredentials(email, password);
    mPresenter.loginWithEmail(loginCredentials);
}

The presenter would then validate and make a request to the repository:

public void loginWithEmail(LoginCredentials loginCredentials) {
    boolean isEmailValid = AuthValidator.validateEmail(loginCredentials.getUsername());
    boolean isPasswordValid = AuthValidator.validatePassword(loginCredentials.getPassword());

    if(isEmailValid && isPasswordValid) repository.loginEmailUser(loginCredentials);

    if (!isEmailValid) view.handleInvalidEmail();

    if (!isPasswordValid) view.handleInvalidPassword();
}

The repository would then execute the business logic:

@Override
public void loginEmailUser(LoginCredentials loginCredentials) {
    Call<Token> call = userServiceApi.loginInToken(loginCredentials);
    call.enqueue(new Callback<Token>() {
        @Override
        public void onResponse(@NonNull Call<Token> call, @NonNull Response<Token> response) {
            if (response.isSuccessful()) {
                // handle successful login
            } else {
                // Handle unsuccessful login
            }
        }

        @Override
        public void onFailure(@NonNull Call<Token> call, @NonNull Throwable t) {
            // Handle failed request
        }
    });

Where the comments say // handle unsuccessful something, how does the model feedback to the view the outcomes of the business logic so that the view can handle these outcomes?

Thank you.

Body:
You can use a interface as callback, for example :

public interface RepositoryCallback {

   void onLoginEmailUserSuccess(/*paramaters if you need*/);
   void onLoginEmailUserError(/*paramaters if you need*/);
   void onRequestFailed(/*paramaters if you need*/)

}

In the repository defined the listener

public class MyRepository {

    private RepositoryCallback mListener;

    @Override
    public void loginEmailUser(LoginCredentials loginCredentials) {
        Call<Token> call = userServiceApi.loginInToken(loginCredentials);
        call.enqueue(new Callback<Token>() {
            @Override
            public void onResponse(@NonNull Call<Token> call, @NonNull Response<Token> response) {
                if (response.isSuccessful()) {
                    // handle successful login
                    if (mListener != null) {
                        mListener.onLoginEmailUserSuccess()
                    }
                } else {
                    // Handle unsuccessful login
                   if (mListener != null) {
                       mListener.onLoginEmailUserError()
                   }
                }
            }

            @Override
            public void onFailure(@NonNull Call<Token> call, @NonNull Throwable t) {
                // Handle failed request
                if (mListener != null) {
                    mListener.onRequestFailed()
                }
            }
        });

    public void setRepositoryCallback(RepositoryCallback listener) {
        mListener = listener;
    }

}

Then set the presenter as listener :

public class MyPresenter implements RepositoryCallback {

    public void loginWithEmail(LoginCredentials loginCredentials) {
        repository.setRepositoryCallback(this) // here or in the presenter constructor
        boolean isEmailValid = AuthValidator.validateEmail(loginCredentials.getUsername());
        boolean isPasswordValid = AuthValidator.validatePassword(loginCredentials.getPassword());

        if(isEmailValid && isPasswordValid) repository.loginEmailUser(loginCredentials);

        if (!isEmailValid) view.handleInvalidEmail();

        if (!isPasswordValid) view.handleInvalidPassword();
    }

    @Override
    public void onLoginEmailUserSuccess(//paramaters if you need){
        // your code
    }

    @Override
    public void onLoginEmailUserError(//paramaters if you need){
        // your code
    }

    @Override
    public void onRequestFailed(//paramaters if you need){
        // your code
    }

}

Hope this helps.

Sorry for my english.


问:
Binding SelectionChanged to ViewModel using Caliburn.Micro
We've using Caliburn.Micro on a new Silverlight project and everythings working great. The inbuilt conventions bind buttons click events to the viewModel, but I'm not sure what the best way to handle the selectionChanged event on datagrids and comboboxes is.

At the moment, I'm binding to the selected item and calling custom logic, but I feel like this is a bit of a code smell and that I should seperate the setting of the property and the selectedChange event. But if I seperate these, how do I bind the selection changed event to my viewModel, by commands? or an EventTrigger? Or is the code below acceptable? Its a small change but I do this logic everywhere.

```<code>private Foo _selectedFoo;
public Foo SelectedFoo
{
    get
    {
        return _Foo;
    }
    set
    {
        if (_Foo != null && _Foo.Equals(value)) return;
        _Foo = value;
        NotifyOfPropertyChange("SelectedFoo");
        NotifyOfPropertyChange("CanRemove");
        LoadRelatedBars();
    }
}
</code>```

答:
Here is a sample for MVVM and Caliburn.Micro using. Some actions like SelectionChanged should get an explicit a event arguments, so you should set it in caliburn event action part. Freqently first argument is passing $this (The actual ui element to which the action is attached.) and you gets in handler a datacontext for the row but to get to the Grid you should pass $source, as the first argument ($source - is the actual FrameworkElement that triggered the ActionMessage to be sent). According to the manual Caliburn manual.

XAML

```<code>cal:Message.Attach="[Event SelectionChanged]=[Action DataGrid_JobTypesSelectionChanged($source,$eventArgs)];"
</code>```

Code:

```<code>public void DataGrid_JobTypesSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var grid = sender as DataGrid;
        JobTypesSelectedCollection = grid.SelectedItems.Cast<JobComplexModel>().ToList();
    }
</code>```

Body:
We've using Caliburn.Micro on a new Silverlight project and everythings working great. The inbuilt conventions bind buttons click events to the viewModel, but I'm not sure what the best way to handle the selectionChanged event on datagrids and comboboxes is.

At the moment, I'm binding to the selected item and calling custom logic, but I feel like this is a bit of a code smell and that I should seperate the setting of the property and the selectedChange event. But if I seperate these, how do I bind the selection changed event to my viewModel, by commands? or an EventTrigger? Or is the code below acceptable? Its a small change but I do this logic everywhere.

private Foo _selectedFoo;
public Foo SelectedFoo
{
    get
    {
        return _Foo;
    }
    set
    {
        if (_Foo != null && _Foo.Equals(value)) return;
        _Foo = value;
        NotifyOfPropertyChange("SelectedFoo");
        NotifyOfPropertyChange("CanRemove");
        LoadRelatedBars();
    }
}

Body:
Here is a sample for MVVM and Caliburn.Micro using. Some actions like SelectionChanged should get an explicit a event arguments, so you should set it in caliburn event action part. Freqently first argument is passing $this (The actual ui element to which the action is attached.) and you gets in handler a datacontext for the row but to get to the Grid you should pass $source, as the first argument ($source - is the actual FrameworkElement that triggered the ActionMessage to be sent). According to the manual Caliburn manual.

XAML

cal:Message.Attach="[Event SelectionChanged]=[Action DataGrid_JobTypesSelectionChanged($source,$eventArgs)];"

Code:

public void DataGrid_JobTypesSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var grid = sender as DataGrid;
        JobTypesSelectedCollection = grid.SelectedItems.Cast<JobComplexModel>().ToList();
    }


问:
Microsoft Access Query
I have one settings table that is storing different setting keys for a app built using Microsoft Access
One of the settings key drives how many records should be seen in a dropdown list
The query behind the list is similar to the one below:

```<code>Select Top 3 id, name FROM tblRegular
</code>```

Now, I want to achieve something like this:

```<code>Select Top (Select keyValue FROM tblSettings WHERE key="rowNumber") id, name FROM tblRegular
</code>```

But, using it like this does not work as it fires errors
Could someone tell me if it can be done?

EDIT: The table structure looks similar to the one below:
tblRegular:

```<code>id  | name
1     'A'
2     'B'
3     'C'
</code>```

tblSettings:

```<code>id  | key          | keyValue
1     'rowNumber'    2
</code>```

Thank you!

答:
Ok, so, just found out that using the Select statement as it was in the question would have triggered the errors mentioned. So, the approach that worked is to alter the .RowSource of the dropdown on form load and the query placed in the rowsource should look like:

```<code>Select Top (" & rowNr & ") id, name FROM tblRegular
</code>```

where rowNr is fetched using another SQL query or even a DAO/ADO function to retrieve the value from the database

Title: Microsoft Access Query

Body:
I have one settings table that is storing different setting keys for a app built using Microsoft Access
One of the settings key drives how many records should be seen in a dropdown list
The query behind the list is similar to the one below:

Select Top 3 id, name FROM tblRegular

Now, I want to achieve something like this:

Select Top (Select keyValue FROM tblSettings WHERE key="rowNumber") id, name FROM tblRegular

But, using it like this does not work as it fires errors
Could someone tell me if it can be done?

EDIT: The table structure looks similar to the one below:
tblRegular:

id  | name
1     'A'
2     'B'
3     'C'

tblSettings:

id  | key          | keyValue
1     'rowNumber'    2

Thank you!

Body:
Ok, so, just found out that using the Select statement as it was in the question would have triggered the errors mentioned. So, the approach that worked is to alter the .RowSource of the dropdown on form load and the query placed in the rowsource should look like:

Select Top (" & rowNr & ") id, name FROM tblRegular

where rowNr is fetched using another SQL query or even a DAO/ADO function to retrieve the value from the database


问:
Ignore inline model when saving
I've been looking on the documentation and stackoverflow/forums for a way to ignore the inline children of a model when I save it in django admin. I've been searching for a few days and I can't seem to find an answer.

I have a normal tabularinline object:

```<code>class UserOrdersAdmin(admin.TabularInline):
    model = Order
    classes = ['collapse']
</code>```

And a normal User admin registration:

```<code>class UserAdmin(BaseUserAdmin):
    inlines = (UserOrdersAdmin, UserSettingsAdmin)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)
</code>```

What I simply want is when I press save within the User "change view", it will ignore the inline "UserOrderAdmin" which is inline to UserAdmin.

答:
Try this:</p>

```<code>class UserOrdersAdmin(admin.TabularInline):
    model = Order
    classes = ['collapse']
    extra = 0
</code>```

Title: Ignore inline model when saving

Body:
I've been looking on the documentation and stackoverflow/forums for a way to ignore the inline children of a model when I save it in django admin. I've been searching for a few days and I can't seem to find an answer.

I have a normal tabularinline object:

class UserOrdersAdmin(admin.TabularInline):
    model = Order
    classes = ['collapse']

And a normal User admin registration:

class UserAdmin(BaseUserAdmin):
    inlines = (UserOrdersAdmin, UserSettingsAdmin)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

What I simply want is when I press save within the User "change view", it will ignore the inline "UserOrderAdmin" which is inline to UserAdmin.

Body:
Try this:

class UserOrdersAdmin(admin.TabularInline):
    model = Order
    classes = ['collapse']
    extra = 0


问:
jQuery $(this).nextUntil('h3').toggle(); - hidden ul inside an ul
I'm struggling for two days now on how to toggle specific content for my first project (started coding about a week ago, so I'm a newbie). I have searched other topics and read articles/done tutorials, and they helped me in the right direction, but I'm still not there yet. Who knows how to tackle this?

Goal:
Only the h3s should be visible when the page loads. When I click on h3, I want everything until the next h3 to toggle (thus, the ul and the 'sub' ul).

Current situation: List Items 1 and 2 toggle, but the Sublist items are not (they stay hidden).

```<code><div>
<h3>Heading</h3>
  <ul>
    <li>List item 1</li>
      <ul>
       <li>Sublist item 1</li>
       <li>Sublist item 2</li>
      </ul>
    <li>List item 2</li>
      <ul>
        <li></li>
      </ul>
  </ul>
<h3>Next heading</h3>
...
</div>
</code>```

This is the jQuery code:

```<code> $(document).ready(function() {
   $('h3').click(function() {
     $(this).nextUntil('h3').toggle();
   });
 });
</code>```

And the CSS that hides the ul when the page loads:

```<code>ul {
  display: none;
  visibility: inherit;
}
</code>```

I think the problem is in my CSS (because List Item 2 does load), but after two days I'm still not able to fix it. Who can help me?

答:
You should only hide the sibling UL of h3, so change the selector for CSS rules as

```<code>h3+ul {
  display: none;
  visibility: inherit;
}
</code>```

$(document).ready(function() {
  $('h3').click(function() {
    $(this).nextUntil('h3').toggle();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h3+ul {
  display: none;
  visibility: inherit;
}</code>```

Heading

List item 1

Sublist item 1

Sublist item 2

List item 2

Next heading

List item 4

Sublist item 4

Sublist item 4

```

As pointed by @lonut, You should add nested UL as child of LI

Body:
I'm struggling for two days now on how to toggle specific content for my first project (started coding about a week ago, so I'm a newbie). I have searched other topics and read articles/done tutorials, and they helped me in the right direction, but I'm still not there yet. Who knows how to tackle this?

Goal:
Only the h3s should be visible when the page loads. When I click on h3, I want everything until the next h3 to toggle (thus, the ul and the 'sub' ul).

Current situation: List Items 1 and 2 toggle, but the Sublist items are not (they stay hidden).

Heading

List item 1

Sublist item 1

Sublist item 2

List item 2

Next heading

...

This is the jQuery code:

 $(document).ready(function() {
   $('h3').click(function() {
     $(this).nextUntil('h3').toggle();
   });
 });

And the CSS that hides the ul when the page loads:

ul {
  display: none;
  visibility: inherit;
}

I think the problem is in my CSS (because List Item 2 does load), but after two days I'm still not able to fix it. Who can help me?

Body:
You should only hide the sibling UL of h3, so change the selector for CSS rules as

h3+ul {
  display: none;
  visibility: inherit;
}

$(document).ready(function() {
  $('h3').click(function() {
    $(this).nextUntil('h3').toggle();
  });
});

h3+ul {
  display: none;
  visibility: inherit;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3>Heading</h3>
  <ul>
    <li>List item 1</li>
    <ul>
      <li>Sublist item 1</li>
      <li>Sublist item 2</li>
    </ul>
    <li>List item 2</li>
    <ul>
      <li></li>
    </ul>
  </ul>
  <h3>Next heading</h3>
  <ul>
    <li>List item 4</li>
    <ul>
      <li>Sublist item 4</li>
      <li>Sublist item 4</li>
    </ul>

  </ul>
</div>

As pointed by @lonut, You should add nested UL as child of LI


问:
I can not redirect with .htaccess file
I tried to redirect any thing the user write after domainname/ to the index.php file but it is not working unless i write domainname/index.php/sdsdsdsd => this works but i wanna it without typing index.php.

This is .htaccess file:

```<code>RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /index.php
</code>```

答:
I found the solution when i changed

```<code><Directory />
    AllowOverride None
    Require all denied
</Directory>
</code>```

To:

```<code><Directory />
    AllowOverride All
    Require all denied
</Directory>
</code>```

Title: I can not redirect with .htaccess file

Body:
I tried to redirect any thing the user write after domainname/ to the index.php file but it is not working unless i write domainname/index.php/sdsdsdsd => this works but i wanna it without typing index.php.

This is .htaccess file:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /index.php

Body:
I found the solution when i changed

<Directory />
    AllowOverride None
    Require all denied
</Directory>

To:

<Directory />
    AllowOverride All
    Require all denied
</Directory>


问:
How to create instance of an object?
I am using Json.Net library to convert objects to json and back to objects.

I have an interface:

```<code>public interface IGoods
{
    List<IPen> Pens { get; set; }
    List<IPencil> Pencils{ get; set; }
    void Deserialize(String json);

}
</code>```

implementation:

```<code>new public void Deserialize(String json)
    {
        JsonConvert.DeserializeObject<Goods>(json);
    }
</code>```

The obvious error I got is: Could not create an instance of type Project.IPen. Type is an interface or abstract class and cannot be instantated.

How do I overcome this error?

Thanks!

答:
IPen is an interface, not a class, which means it cannot be instantiated.  Basically what you need is a class which implements the IPen interface (let's call it Pen).  You should then be able to replace IPen in the Json string with Pen, and Json.Net will be able to instantiate the object.

Just to be clear, your Pen class should look something like this:

```<code>public class Pen: IPen
{
//Interface implementation here.
}
</code>```

Title: How to create instance of an object?

Body:
I am using Json.Net library to convert objects to json and back to objects.

I have an interface:

public interface IGoods
{
    List<IPen> Pens { get; set; }
    List<IPencil> Pencils{ get; set; }
    void Deserialize(String json);

}

implementation:

new public void Deserialize(String json)
    {
        JsonConvert.DeserializeObject<Goods>(json);
    }

The obvious error I got is: Could not create an instance of type Project.IPen. Type is an interface or abstract class and cannot be instantated.

How do I overcome this error?

Thanks!

Body:
IPen is an interface, not a class, which means it cannot be instantiated.  Basically what you need is a class which implements the IPen interface (let's call it Pen).  You should then be able to replace IPen in the Json string with Pen, and Json.Net will be able to instantiate the object.

Just to be clear, your Pen class should look something like this:

public class Pen: IPen
{
//Interface implementation here.
}


问:
Here maps sdk V3.3 not working on android 7
I'm using HereMaps SDK for a project, I can initialize the map engine without any problems on old Android devices running older version than Android 7

But when I try to run my apk on an Android 7 device I get missing libraries

HereMaps SDK version is 3.3, it's using an AAR file.

I've analyzed the generated APK if it's missing any libraries but everything seems to be in place.

Here is the error exception thrown from the SDK initialization

```<code>java.lang.Throwable
    at com.nokia.maps.av.a(EngineError.java:27)
    at com.nokia.maps.MapsEngine.b(MapsEngine.java:370)
    at com.nokia.maps.MapsEngine.a(MapsEngine.java:346)
    at com.here.android.mpa.common.MapEngine.init(MapEngine.java:129)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5491)
    at android.app.ActivityThread.-wrap2(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1583)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:241)
    at android.app.ActivityThread.main(ActivityThread.java:6217)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Cannot initialize MapEngine: MISSING_LIBRARIES
</code>```

答:
I added below code in Build Gradle and it works fine for me in android 7 (Nougat)

```<code>splits {
  abi {
         enable true
         reset()
         include 'armeabi-v7a'
         universalApk false
      }
 }
</code>```

Body:
I'm using HereMaps SDK for a project, I can initialize the map engine without any problems on old Android devices running older version than Android 7

But when I try to run my apk on an Android 7 device I get missing libraries

HereMaps SDK version is 3.3, it's using an AAR file.

I've analyzed the generated APK if it's missing any libraries but everything seems to be in place.

Here is the error exception thrown from the SDK initialization

java.lang.Throwable
    at com.nokia.maps.av.a(EngineError.java:27)
    at com.nokia.maps.MapsEngine.b(MapsEngine.java:370)
    at com.nokia.maps.MapsEngine.a(MapsEngine.java:346)
    at com.here.android.mpa.common.MapEngine.init(MapEngine.java:129)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5491)
    at android.app.ActivityThread.-wrap2(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1583)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:241)
    at android.app.ActivityThread.main(ActivityThread.java:6217)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Cannot initialize MapEngine: MISSING_LIBRARIES

Body:
I added below code in Build Gradle and it works fine for me in android 7 (Nougat)

splits {
  abi {
         enable true
         reset()
         include 'armeabi-v7a'
         universalApk false
      }
 }


问:
Visual Studio 2015 SSRS - Report Preview Shows Invisible Values
I am developing SSRS reports in Visual Studio 2015. This happened before in the SQL Report Builder.

When I try and preview the report is doesnt show any of the value. However exporting the report does show the values.

This is really annoying as I have to export the report to see my results.

Has anyone come across this or have a possible solution?

答:
One thought that comes to mind is the data cache issue.  Have you tried:

1) Clicking the "Refresh" button on the report after it is ran because I believe that refreshes the data cache

2) Via File Explorer navigate to where the .rdl file is and find the .data file for the report and delete it then run the report.

3) As per the comments below: In VS2015 just clean the project, it deletes the .data files.


问:
Idea PyCharm database tool returns same result for MySql
Using PyCharm database tool for a mysql database over SSH tunnel.

I simply select * from table_x however database tool returns the same result (even after insertions/updates to the table). I double checked all the cache options, all off.

I tried different queries such as select ... from table_x where id > ... on the same table but result doesn't change.

I also tried select SQL_NO_CACHE * from table_x but no luck.

Other tools work ok that's why rather it looks like a bug or what is it at all?

答:
The problem caused by auto-commit option (in my case it was off).

It has to be on otherwise even if you are doing read-only operations you will get the same results.

I guess if auto commit is off PyCharm opens a transaction and never closes it that's why operations works on the same time frame with transaction opening moment.

It has to be a bug. Auto commit could be dangerous, now I am forced to use it which is not convenient and reasonable. Hope it gets fixed soon.


问:
JavaScript - Get only negative numbers form array
I have task: Write the function getNegativeNumbers (array) which as an argument take array. The function has to return a new array filled only negative numbers.

I have done this solution, but I ask about different methods.

```<code>var myArray = [4, -5, 0, 2, -67, 8, 10, -34 ];

function getNegativeNumbers(array) {

    var negatives = [];

    for (var i = 0; i < array.length; i++) {
        if (array[i] < 0) {
            negatives.push(array[i]);
        }
    }
    return negatives;

}
console.log(getNegativeNumbers(myArray));
</code>```

答:
Use Array#filter to create a new array of negative numbers:

var myArray = [4, -5, 0, 2, -67, 8, 10, -34 ];

var result = myArray.filter(function(number) {
  return number < 0;
});

console.log(result);```

Body:
I have task: Write the function getNegativeNumbers (array) which as an argument take array. The function has to return a new array filled only negative numbers.

I have done this solution, but I ask about different methods.

var myArray = [4, -5, 0, 2, -67, 8, 10, -34 ];

function getNegativeNumbers(array) {

    var negatives = [];

    for (var i = 0; i < array.length; i++) {
        if (array[i] < 0) {
            negatives.push(array[i]);
        }
    }
    return negatives;

}
console.log(getNegativeNumbers(myArray));


问:
MySQL: What is the most performant way of storing a whole year (365 elements) in MySQL?
Within a project, I have to store the daily availability of different meeting rooms. So let's suppose around 1.000.000 meeting rooms, where each meeting room is in a city, and a city could have hundreds of meeting rooms.

I would also like to be able to make SELECT Queries entering the city and the availability that I need, so I would like to get a list of the available meeting rooms for a day, or set of continues days, in a concrete city.

I have one table called "MeetingRoom", when I store the city and the name of the meeting room, but my design question is how to design the availability part:

Is it better in terms of performance to have a binary array that stores the 365 days of the year with a '1' or '0' according to the availability of the meeting room?

Is it better in terms of performance to have another table called "Availability" that stores a DATE and a BIT with the availability, and then JOIN both tables for each meeting room that exists in a city?

Could it better another option I don't have in mind?

I wonder what querying time would be optimal having around 1.000.000 meeting rooms, and searching for the meeting rooms in a city and available for concrete days. Is it crazy about thinking in database responses below 100 ms?

Some colleagues told me that I should also consider to migrate to MongoDB or NoSQL approach. I don't know if a change of DB could fit better with my issues, or if it don't. Any comment about this?

Thank you very much for the help!!

答:
I don't know if this will help, but if it doesn't, please write me to delete the answer.

Instead of these options you may want to consider that in the "Availability" table to store only the id(surrogate) of the room and the date on which it is reserved. So when you select the data and join both tables you will get only the reserved rooms. I personally think that there is no point of storing all of the room-date relations with status.

Moreover, to improve the performance you can create non-clustered index on the City column for instance.


问:
Sorting column for HTML Report from PowerShell
How do I sort the "Online" column and Uptime column? I would like to show True at the top with the longest uptime at the top, followed by FALSE. </p>

```<code>    <#

    .Synopsis
        Query Uptime Details of servers.

    .Description
        This script helps you to get the uptime details of the servers. It also generates a HTML report
        when -HTMLReport switch is used. The report contains the uptime details and a summary of how many
        computers reachable and how many are not

    .Parameter ComputerName
        Computer name(s) for which you want to get the uptime details.

    .Parameter HTMLReport
        Generates a HTML report in c:\ drive with name uptimereport.html by default. You can override this by
        specifying -HTMLFile parameter

    .Parameter HTMLFile
        Name of the file path where you want to store the report

    .Example
        Get-UptimeOfServers.ps1 -ComputerName Comp1, Comp2

        Gets the Uptime of Comp1 and Comp2
    .Example
        Get-UptimeOfServers.ps1 -ComputerName Comp1, Comp2 -HTMLReport

        Get the uptime of Comp1 and Comp2 and saves the report in HTML format

    .Example
        Get-Content c:\servers.txt | Get-UptimeOfServers.ps1 -HTMLReport

        Get the uptime of computers listed in servers.txt and saves the report in HTML format

    .Notes
        NAME:      Get-UptimeOfServers.ps1
        AUTHOR:    Sitaram Pamarthi
        WEBSITE:   http://techibee.com

#>

[cmdletbinding()]

param(
    [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [string[]]$ComputerName = $env:computername,
    [switch]$HTMLReport,
    [string]$HTMLFile = "c:\Temp\Uptimereport.html"
)

begin{
if($HTMLReport) {
    $Report = "

            <html>
                <head>
                    <title> Server Uptime Report </title>
                </head>
                <body>

                    <H1 Align=`"Center`"> <B>Server Uptime Report </B></H1>
                    <br>
                    <H3 Align=`"Center`"> Report Generated at $(Get-Date)</H3>
                    <table BORDER=`"1`" CELLPADDING=`"5`" Align=`"Center`">
                    <tr>
                        <td font-family: 'Calibri' BGColor=#98C6F3 Align=center><b>Server Name</b></td>
                        <td font-family: 'Calibri' BGColor=#98C6F3 Align=center><b>Online</b></td>
                        <td font-family: 'Calibri' BGColor=#98C6F3 Align=center><b>Uptime</b></td>
                    </tr>"

    }
}
process {
    $Count=0
    $SuccessComps = 0
    $UnreachableComps = 0
    $FailedComps = 0
    $FinalOutput = @()
    foreach($Computer in $ComputerName) {
        $Count++
        $Computer = $Computer.Toupper()
        $OutputObj  = New-Object -TypeName PSobject
        $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer
        $Status = 0
        if(Test-Connection -Computer $Computer -count 1 -ea 0) {
            $OutputObj | Add-Member -MemberType NoteProperty -Name IsOnline -Value "TRUE"
            try {
                $Boottime = (Get-WmiObject win32_operatingSystem -computer $Computer -ErrorAction stop).lastbootuptime
                $Boottime = [System.Management.ManagementDateTimeconverter]::ToDateTime($BootTIme)
                $Now = Get-Date
                $span = New-TimeSpan $BootTime $Now
                $Uptime = "{0} day(s), {1} hour(s), {2} min(s), {3} second(s)" -f $span.days, $span.hours, $span.minutes, $span.seconds
                $OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value $Uptime
                $Status=1
                $SuccessComps++
            } catch {
                $OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "FAILED TO GET"
                $FailedComps++
            }

        } else {
            $OutputObj | Add-Member -MemberType NoteProperty -Name IsOnline -Value "FALSE"
            $OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value ""

            $UnreachableComps++
        }

        $FinalOutput +=$OutputObj
        $OutputObj = $OutputObj

        if($HTMLReport) {
            if($Status) {
                $BGColor="GreenYellow"
            } else {
                $BGColor="OrangeRed"
            }
            $IsOnline
            $Report += " <TR>
                        <TD BGColor=$BGColor>$($OutputObj.ComputerName)</TD>
                        <TD BGColor=$BGColor>$($OutputObj.IsOnline)</TD>
                        <TD BGColor=$BGColor>$($OutputObj.Uptime)</TD>
                        </TR>"

        } else {
            $OutputObj

        }

    }

}
end{
    if($HTMLReport) {
        $Report +=
        $Report | Out-File $HTMLFile -Force
    }
}
</code>```

答:
I think Sort-Object will help you out.
$FinalOutput | Sort-Object IsOnline,uptime -descending </p>

<p>Version 2  you can put span field into </p>

```<code>$FinalOutput | sort-Object IsOnline,span -descending | Select-Object ComputerName,IsOnline,Uptime
</code>```

Body:
How do I sort the "Online" column and Uptime column? I would like to show True at the top with the longest uptime at the top, followed by FALSE.

    <#

    .Synopsis
        Query Uptime Details of servers.

    .Description
        This script helps you to get the uptime details of the servers. It also generates a HTML report
        when -HTMLReport switch is used. The report contains the uptime details and a summary of how many
        computers reachable and how many are not

    .Parameter ComputerName
        Computer name(s) for which you want to get the uptime details.

    .Parameter HTMLReport
        Generates a HTML report in c:\ drive with name uptimereport.html by default. You can override this by
        specifying -HTMLFile parameter

    .Parameter HTMLFile
        Name of the file path where you want to store the report

    .Example
        Get-UptimeOfServers.ps1 -ComputerName Comp1, Comp2

        Gets the Uptime of Comp1 and Comp2
    .Example
        Get-UptimeOfServers.ps1 -ComputerName Comp1, Comp2 -HTMLReport

        Get the uptime of Comp1 and Comp2 and saves the report in HTML format

    .Example
        Get-Content c:\servers.txt | Get-UptimeOfServers.ps1 -HTMLReport

        Get the uptime of computers listed in servers.txt and saves the report in HTML format

    .Notes
        NAME:      Get-UptimeOfServers.ps1
        AUTHOR:    Sitaram Pamarthi
        WEBSITE:   http://techibee.com

#>

[cmdletbinding()]

param(
    [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [string[]]$ComputerName = $env:computername,
    [switch]$HTMLReport,
    [string]$HTMLFile = "c:\Temp\Uptimereport.html"
)

begin{
if($HTMLReport) {
    $Report = "

                    <title> Server Uptime Report </title>

                    <H1 Align=`"Center`"> Server Uptime Report

                    <H3 Align=`"Center`"> Report Generated at $(Get-Date)

                    <table BORDER=`"1`" CELLPADDING=`"5`" Align=`"Center`">

                        Server Name
                        Online
                        Uptime

"

    }
}
process {
    $Count=0
    $SuccessComps = 0
    $UnreachableComps = 0
    $FailedComps = 0
    $FinalOutput = @()
    foreach($Computer in $ComputerName) {
        $Count++
        $Computer = $Computer.Toupper()
        $OutputObj  = New-Object -TypeName PSobject
        $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer
        $Status = 0
        if(Test-Connection -Computer $Computer -count 1 -ea 0) {
            $OutputObj | Add-Member -MemberType NoteProperty -Name IsOnline -Value "TRUE"
            try {
                $Boottime = (Get-WmiObject win32_operatingSystem -computer $Computer -ErrorAction stop).lastbootuptime
                $Boottime = [System.Management.ManagementDateTimeconverter]::ToDateTime($BootTIme)
                $Now = Get-Date
                $span = New-TimeSpan $BootTime $Now
                $Uptime = "{0} day(s), {1} hour(s), {2} min(s), {3} second(s)" -f $span.days, $span.hours, $span.minutes, $span.seconds
                $OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value $Uptime
                $Status=1
                $SuccessComps++
            } catch {
                $OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "FAILED TO GET"
                $FailedComps++
            }

        } else {
            $OutputObj | Add-Member -MemberType NoteProperty -Name IsOnline -Value "FALSE"
            $OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value ""

            $UnreachableComps++
        }

        $FinalOutput +=$OutputObj
        $OutputObj = $OutputObj

        if($HTMLReport) {
            if($Status) {
                $BGColor="GreenYellow"
            } else {
                $BGColor="OrangeRed"
            }
            $IsOnline
            $Report += "

                        $($OutputObj.ComputerName)
                        $($OutputObj.IsOnline)
                        $($OutputObj.Uptime)

"

        } else {
            $OutputObj

        }

    }

}
end{
    if($HTMLReport) {
        $Report +=
        $Report | Out-File $HTMLFile -Force
    }
}

Body:
I think Sort-Object will help you out.
$FinalOutput | Sort-Object IsOnline,uptime -descending

Version 2  you can put span field into

$FinalOutput | sort-Object IsOnline,span -descending | Select-Object ComputerName,IsOnline,Uptime


问:
Selecting a series from dual in Oracle using connect by: column alias not recognized in prior clause
I am trying to select a sequence from dual. The following is a simplified example of what I'm trying to do.

Executing the following query is successful:

```<code>select
  1 as curr_val,
  2 as next_val
from
  dual
connect by
  level <=3
;
</code>```

However, when I try to create the sequence by doing the following I get the error shown below.

```<code>select
  1 as curr_val,
  2 as next_val
from
  dual
connect by
  level <=3
  and curr_val = prior next_val
;
</code>```

Error:

```<code>ORA-00904: "NEXT_VAL": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:
Error at Line: 8 Column: 24
</code>```

Is there a way to modify the above to generate a sequence of numbers (i.e. get the above query to return 1,2,3 for the values of curr_val)?

答:
How about this?

```<code>select rownum curr_val, rownum + 1 next_val
from dual
connect by level <=10
order by 1;
</code>```

The ORDER BY clause might not be required if the ordering is not important (unlikely but it's your call) or if the RDBMS' implied ordering is always going to be guaranteed (also unlikely).

Addendum: John is correct regarding the redundancy of what previously was in the text of the SQL statement above.

Body:
I am trying to select a sequence from dual. The following is a simplified example of what I'm trying to do.

Executing the following query is successful:

select
  1 as curr_val,
  2 as next_val
from
  dual
connect by
  level <=3
;

However, when I try to create the sequence by doing the following I get the error shown below.

select
  1 as curr_val,
  2 as next_val
from
  dual
connect by
  level <=3
  and curr_val = prior next_val
;

Error:

ORA-00904: "NEXT_VAL": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:
Error at Line: 8 Column: 24

Is there a way to modify the above to generate a sequence of numbers (i.e. get the above query to return 1,2,3 for the values of curr_val)?

Body:
How about this?

select rownum curr_val, rownum + 1 next_val
from dual
connect by level <=10
order by 1;

The ORDER BY clause might not be required if the ordering is not important (unlikely but it's your call) or if the RDBMS' implied ordering is always going to be guaranteed (also unlikely).

Addendum: John is correct regarding the redundancy of what previously was in the text of the SQL statement above.


问:
Open Excel File using OpenFileDialog in C# Windows Form
I am able to choose an Excel file, but after I clicked on Open, the excel file doesn't appear. What should I do? I'm still new with OpenFileDialog, it will be good if anyone can tell what I should add to make the excel file appear after clicking on Open.

Modified from http://www.c-sharpcorner.com/uploadfile/mahesh/openfiledialog-in-c-sharp/

This is my code:

```<code>private void BrowseButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = @"C:\";
        openFileDialog1.Title = "Browse Text Files";

        openFileDialog1.CheckFileExists = true;
        openFileDialog1.CheckPathExists = true;

        openFileDialog1.DefaultExt = "txt";
        openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        openFileDialog1.ReadOnlyChecked = true;
        openFileDialog1.ShowReadOnly = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string file = openFileDialog1.FileName;
            try
            {
                string text = File.ReadAllText(file);
                int size = text.Length;
            }
            catch (IOException)
            {
            }

        }
    }

public bool ThumbnailCallback()
   {
     return false;
   }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
    {

    }
</code>```

After I clicked Open, only the file name appear, but not the excel file - https://i.stack.imgur.com/GXToy.jpg

答:
If you only want to open the Excel file using the default application that is associated to *.xlsx files (which usually is MS Excel when it is installed), then you can simply use the Process.Start(string) method. In you case it may look something like this:

```<code>    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        Process.Start(openFileDialog1.FileName);
    }
</code>```

Body:
I am able to choose an Excel file, but after I clicked on Open, the excel file doesn't appear. What should I do? I'm still new with OpenFileDialog, it will be good if anyone can tell what I should add to make the excel file appear after clicking on Open.

Modified from http://www.c-sharpcorner.com/uploadfile/mahesh/openfiledialog-in-c-sharp/

This is my code:

private void BrowseButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = @"C:\";
        openFileDialog1.Title = "Browse Text Files";

        openFileDialog1.CheckFileExists = true;
        openFileDialog1.CheckPathExists = true;

        openFileDialog1.DefaultExt = "txt";
        openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        openFileDialog1.ReadOnlyChecked = true;
        openFileDialog1.ShowReadOnly = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string file = openFileDialog1.FileName;
            try
            {
                string text = File.ReadAllText(file);
                int size = text.Length;
            }
            catch (IOException)
            {
            }

        }
    }

public bool ThumbnailCallback()
   {
     return false;
   }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
    {

    }

After I clicked Open, only the file name appear, but not the excel file - https://i.stack.imgur.com/GXToy.jpg

Body:
If you only want to open the Excel file using the default application that is associated to *.xlsx files (which usually is MS Excel when it is installed), then you can simply use the Process.Start(string) method. In you case it may look something like this:

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        Process.Start(openFileDialog1.FileName);
    }


问:
C# foreach with string - ignore last character
I have a methode who add numbers together parsed from a string.

If user type : "52+7+1", it will result in (60)
"52++2+3", "52+c+2", "+52+2", "52+2++", ... won't work.

My code works almost perfectly, expect... it ignores the last character. It works when, in the code I add "+0" to the string but of course it brokes the condition who prevent the user to type "+" as a last character.

```<code>    public int addFromString(string str)
    {
        bool valid_str = true;
        bool current_char_numeric = false;

        string unparsedNumber = "";
        int parsedNumber = 0;
        List<int> parsedNumbers = new List<int>();

        if (string.IsNullOrEmpty(chaine))
            chaine_valide = false;
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber))
               valid_str = false;

            if (!int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
                valid_str = false;
        }

        foreach (char c in str)
        {
            current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);

            if (current_char_numeric)
                unparsedNumber += c;
            else if(c == '+')
            {
                int.TryParse(unparsedNumber, out parsedNumber);
                parsedNumbers.Add(parsedNumber);

                if (str.IndexOf(c) < str.Length && str.ElementAt(str.IndexOf(c) + 1) == '+')
                    valid_str = false;

                //Just in case :
                unparsedNumber = "";
                current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);
            }
            else valid_str = false;
        }

        int result = 0;

        if(valid_str) { foreach(int n in parsedNumbers) { result += n; } }

        return result;
}
</code>```

So if I type : "52+2" I get 52

If I type : "52+2+6" I get 54

答:
You only add a number to the numbers collection when you encounter a +.
What about the last number? There's no '+' after that.

You should add unparsedNumber to parsedNumbers for the last number too.

Body:
I have a methode who add numbers together parsed from a string.

If user type : "52+7+1", it will result in (60)
"52++2+3", "52+c+2", "+52+2", "52+2++", ... won't work.

My code works almost perfectly, expect... it ignores the last character. It works when, in the code I add "+0" to the string but of course it brokes the condition who prevent the user to type "+" as a last character.

    public int addFromString(string str)
    {
        bool valid_str = true;
        bool current_char_numeric = false;

        string unparsedNumber = "";
        int parsedNumber = 0;
        List<int> parsedNumbers = new List<int>();

        if (string.IsNullOrEmpty(chaine))
            chaine_valide = false;
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber))
               valid_str = false;

            if (!int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
                valid_str = false;
        }

        foreach (char c in str)
        {
            current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);

            if (current_char_numeric)
                unparsedNumber += c;
            else if(c == '+')
            {
                int.TryParse(unparsedNumber, out parsedNumber);
                parsedNumbers.Add(parsedNumber);

                if (str.IndexOf(c) < str.Length && str.ElementAt(str.IndexOf(c) + 1) == '+')
                    valid_str = false;

                //Just in case :
                unparsedNumber = "";
                current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);
            }
            else valid_str = false;
        }

        int result = 0;

        if(valid_str) { foreach(int n in parsedNumbers) { result += n; } }

        return result;
}

So if I type : "52+2" I get 52

If I type : "52+2+6" I get 54


问:
How to listen to Process Up or down events in Java?
I have a process running using Systemctl, configured it with Restart=always
so that even if process crashes then it will restart by itself without manual intervention. When that process restarts I want to take some action in my java code. I don't want poll the process. is there anyway to achieve this?

Thanks in advance.

答:
systemd has a D-Bus API that you can use to receive event notifications when a unit changes state, including changes to its ActiveState property that tells you whether it's currently running.  See this answer on Unix & Linux StackExchange for more information.

To use this API from a Java program, you'll need a D-Bus library for Java.  It looks like there's a DBus-Java library, though it hasn't been updated in a long time.  Alternatively, you might be able to have your Java program invoke the command-line dbus-send and/or dbus-monitor programs and read their output.


问:
multiple return values Vulkan C++ function header
I'm reading the tutorial on the Vulkan API.  There is a function which seems to me to be declaring 3 return types.  I'm not sure if this is a C++ feature or something unique to Vulkan.

```<code>static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
  VkDebugReportFlagsEXT flags,
  VkDebugReportObjectTypeEXT objType,
  uint64_t obj,
  size_t location,
  int32_t code,
  const char* layerPrefix,
  const char* msg,
  void* userData) {
    std::cerr << "validation layer: " << msg << std::endl;

    return VK_FALSE;
}
</code>```

I saw this stackoverflow answer, but it doesn't really explain what is going on here.

答:
some implementations of c/c++ compilers accept certain attributes for different functions and structs, i.e. optimization level for the function, or marking it as a specific purpose. They usually do not change the functionality but might add or remove special code or use special calling convention or whatever. So, common practice is to hide attributes int macros, defined in some header files.

In your case both VKAPI_ATTR and VKAPI_CALL look like such macros specific to the Vulkan. In other implementations they are defined to nothing, but in your case they might have some meaning. Check header files for their definition.

The bottom line is that there is only a single return type VkBool32, the rest are just attributes.

Body:
I'm reading the tutorial on the Vulkan API.  There is a function which seems to me to be declaring 3 return types.  I'm not sure if this is a C++ feature or something unique to Vulkan.

static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
  VkDebugReportFlagsEXT flags,
  VkDebugReportObjectTypeEXT objType,
  uint64_t obj,
  size_t location,
  int32_t code,
  const char* layerPrefix,
  const char* msg,
  void* userData) {
    std::cerr << "validation layer: " << msg << std::endl;

    return VK_FALSE;
}

I saw this stackoverflow answer, but it doesn't really explain what is going on here.


问:
Multi-threading in MATLAB
I have read MATLAB's info on multi-threading and how it is in-built in certain functions.  However, my requirement is different.
Say, I have 3 functions: fun1(data1), fun2(data2), fun3(data3).... Can I implement multi-threading between these functions?  I actually have 300+ functions using a lot of data.  Multi-threading may help me cut down a lot of the time.  Please suggest a command or something which I can further research on.  Thanks!</p>

答: Try looking at the Parallel Computing Toolbox. (I'm unfortunately not too familiar with it, but that seems to be the right place.) Look at gather and parallel for-loops.

Title: Multi-threading in MATLAB


答:
Try following

var myArray = [4, -5, 0, 2, -67, 8, 10, -34];

function getNegativeNumbers(array) {
  return array.filter(function(value) {
    return value < 0;
  });
}
console.log(getNegativeNumbers(myArray));```
</div>
</div>
</p>

<p><strong>ES6</strong> </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myArray = [4, -5, 0, 2, -67, 8, 10, -34];

function getNegativeNumbers(array) {
  return array.filter(value => value < 0);
}
console.log(getNegativeNumbers(myArray));</code>```

For reference - filter

Title: JavaScript - Get only negative numbers form array

Body:
Try following

var myArray = [4, -5, 0, 2, -67, 8, 10, -34];

function getNegativeNumbers(array) {
  return array.filter(function(value) {
    return value < 0;
  });
}
console.log(getNegativeNumbers(myArray));

ES6

var myArray = [4, -5, 0, 2, -67, 8, 10, -34];

function getNegativeNumbers(array) {
  return array.filter(value => value < 0);
}
console.log(getNegativeNumbers(myArray));

For reference - filter


问:
How to import and use "support" library in AIDE app?
I've been trying to figure this out for a while now, but I have no idea how to achieve this. I'm trying to be able to use fragments in the app, but when I try to use the import android.support* library, I get an error.

A step by step explanation would be very beneficial.

答:
If you open the folder 'app' in your project, you have an option called 'Add to Project...'. Here you can choose what library to import. You propably want to use "com.android.support:support-v4:+".

BTW - in your java file, you should write import android.support.v4.app.*


问:
Why Html.Checkbox("Visible") returns "true, false" in ASP.NET MVC 2?
I'm using Html.Checkbox("Visible") for displaying a check box to user. In post back, FormCollection["Visible"] value is "true, false". Why?

in view:

```<code><td>
    <%: Html.CheckBox("Visible") %>
</td>
</code>```

in controller:

```<code> adslService.Visible = bool.Parse(collection["Visible"]);
</code>```

答:
I already have a static function that I use everywhere to handle boolean type text and return true or false as a boolean so I just take care of it there</p>

```<code>            if (sBool.StartsWith("true,")) bReturn = true;//cater for mvc checkboxes

            else if (sBool == "true") bReturn = true;

            else if (sBool == "t") bReturn = true;//t-f

            else if (sBool == "1") bReturn = true;//1-0

            else if (sBool == "yes") bReturn = true;//yes-no

            else if (sBool == "y") bReturn = true;//y-n

            else if (sBool == "on") bReturn = true;//on-off
</code>```

Body:
I'm using Html.Checkbox("Visible") for displaying a check box to user. In post back, FormCollection["Visible"] value is "true, false". Why?

in view:

    <%: Html.CheckBox("Visible") %>

in controller:

 adslService.Visible = bool.Parse(collection["Visible"]);

Body:
I already have a static function that I use everywhere to handle boolean type text and return true or false as a boolean so I just take care of it there

            if (sBool.StartsWith("true,")) bReturn = true;//cater for mvc checkboxes

            else if (sBool == "true") bReturn = true;

            else if (sBool == "t") bReturn = true;//t-f

            else if (sBool == "1") bReturn = true;//1-0

            else if (sBool == "yes") bReturn = true;//yes-no

            else if (sBool == "y") bReturn = true;//y-n

            else if (sBool == "on") bReturn = true;//on-off


问:
In Apache POI, Is there a way to access XWPF elements by id their id?
I have word document (it is docx and xml based), I want to find a table and populate it programmatically. I am using Apache POI, XWPF API.

Is there a way to access XWPF elements by their id?

How can I create uniqueness between XWPF elements then alter using java?

Thanks

答:
What I have implemented is a find replace feature(from here);

In my template docx file I am using "id like texts", __heading1__, __subjectname__, Then replacing with them using code below. For tables @axel-richters solution may be suitable.

```<code>private void findReplace(String a, String b, CustomXWPFDocument document){
    for (XWPFParagraph p : document.getParagraphs()) {
        List<XWPFRun> runs = p.getRuns();
        if (runs != null) {
            for (XWPFRun r : runs) {
                String text = r.getText(0);
                if (text != null && text.contains(a)) {
                    text = text.replace(a, b);
                    r.setText(text, 0);
                }
            }
        }
    }
}
</code>```

Body:
What I have implemented is a find replace feature(from here);

In my template docx file I am using "id like texts", __heading1__, __subjectname__, Then replacing with them using code below. For tables @axel-richters solution may be suitable.

private void findReplace(String a, String b, CustomXWPFDocument document){
    for (XWPFParagraph p : document.getParagraphs()) {
        List<XWPFRun> runs = p.getRuns();
        if (runs != null) {
            for (XWPFRun r : runs) {
                String text = r.getText(0);
                if (text != null && text.contains(a)) {
                    text = text.replace(a, b);
                    r.setText(text, 0);
                }
            }
        }
    }
}


问:
How can I fill / populate DropDown with my IEnumerable<Model> value ASP.NET MVC
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

```<code>@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

                }
            }
        }
    }
}
</code>```

Controller action:

```<code>public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}
</code>```

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

答:
```<code>public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();

   ViewBag.Languages = activeLanguages.Select(item => new SelectListItem{
       Text = item.Name,
       Value = item.Id
    });

   return View(activeL);
}

@Html.DropDownListFor(m => m.LanguageId, ViewBag.Languages, new { @class = "form-control" })
</code>```

Body:
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}

                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })

                    }

                }
            }
        }
    }
}

Controller action:

public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")


问:
C++, g++, conditional compilation based on host name?
I have come across the following problem:

Our testing environment is not able to fully simulate a certain hardware part of the production environment, and therefore some code needs excluding when testing the application.

I therefore need something in the way of

```<code> #IFNDEF testing_env
 //code to exclude
 #ENDIF
</code>```

This works just fine if i include a #DEFINE testing_env, but like this i need to manually comment/uncomment this define every time i switch environments.

I'm looking for a way to do this based on the host name or a similar feature. I have tried to look for conditional compilation based on environment variables, but apparently this is not possible.

答:
Usually you create a specific build profile for the testing env (dedicated make rules) and another build profile (other make rules) for the other environments.

Test environment can then be specified with -DTEST_ENVIRONMENT on the compilation line (usually in the Makefile), eg. of use of -D option:

g++ -DTEST_ENVIRONMENT -o test main.c

then

```<code>#IFNDEF TEST_ENVIRONMENT
//code to exclude
#ENDIF
</code>```

will work fine.

Body:
I have come across the following problem:

Our testing environment is not able to fully simulate a certain hardware part of the production environment, and therefore some code needs excluding when testing the application.

I therefore need something in the way of

 #IFNDEF testing_env
 //code to exclude
 #ENDIF

This works just fine if i include a #DEFINE testing_env, but like this i need to manually comment/uncomment this define every time i switch environments.

I'm looking for a way to do this based on the host name or a similar feature. I have tried to look for conditional compilation based on environment variables, but apparently this is not possible.

Body:
Usually you create a specific build profile for the testing env (dedicated make rules) and another build profile (other make rules) for the other environments.

Test environment can then be specified with -DTEST_ENVIRONMENT on the compilation line (usually in the Makefile), eg. of use of -D option:

g++ -DTEST_ENVIRONMENT -o test main.c

then

#IFNDEF TEST_ENVIRONMENT
//code to exclude
#ENDIF

will work fine.


问:
Error after importing project to Android Studio
I have received an old code, coded in 2014 and I was requested to update some functionalities.

I am having problems running the code, for it was built on Eclipse and now I imported it to Android Studio.

First of all, the code calls 3 libraries that are included in the project, one of them is in cpp. This is why I think it was needed to add the bundle-ndk.

I added: android.useDeprecatedNdk=true to gradle-wrapper.properties

These are the gradle files I currently have:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

First Library Gradle

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 16
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}
</code>```

Second Library

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 5
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile project(':FirstLibrary')
    compile 'com.android.support:support-v4:18.0.0'
    compile files('libs/libGoogleAnalyticsV2.jar')
}
</code>```

Third Library

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 7
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
}
</code>```

Module Gradle of Project

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 8
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.application.id"
        minSdkVersion 8
        targetSdkVersion 17
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
        }
    }
}

dependencies {
    compile project(':secondLbrary')
    compile project(':thirdLibrary')
}
</code>```

Latest Error Received:

Error:Execution failed for task ':library:compileDebugNdk'.

Error: Your project contains C++ files but it is not using a supported native build system.
Consider using CMake or ndk-build integration with the stable Android Gradle plugin:
https://developer.android.com/studio/projects/add-native-code.html
or use the experimental plugin:
http://tools.android.com/tech-docs/new-build-system/gradle-experimental.

What can I do to investigate this?

答:
For compiling cpp code in Android Studio:

you need to download CMAKE, LLDB and NDK on Android SDK Manager.

you need to make CMakeList.txt and need to put script for compiling cpp files.

you need to put following lines in build.gradle:

```<code>externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}
</code>```

Body:
I have received an old code, coded in 2014 and I was requested to update some functionalities.

I am having problems running the code, for it was built on Eclipse and now I imported it to Android Studio.

First of all, the code calls 3 libraries that are included in the project, one of them is in cpp. This is why I think it was needed to add the bundle-ndk.

I added: android.useDeprecatedNdk=true to gradle-wrapper.properties

These are the gradle files I currently have:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

First Library Gradle

apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 16
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

Second Library

apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 5
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile project(':FirstLibrary')
    compile 'com.android.support:support-v4:18.0.0'
    compile files('libs/libGoogleAnalyticsV2.jar')
}

Third Library

apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 7
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
}

Module Gradle of Project

apply plugin: 'com.android.application'

android {
    compileSdkVersion 8
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.application.id"
        minSdkVersion 8
        targetSdkVersion 17
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
        }
    }
}

dependencies {
    compile project(':secondLbrary')
    compile project(':thirdLibrary')
}

Latest Error Received:

Error:Execution failed for task ':library:compileDebugNdk'.

Error: Your project contains C++ files but it is not using a supported native build system.
Consider using CMake or ndk-build integration with the stable Android Gradle plugin:
https://developer.android.com/studio/projects/add-native-code.html
or use the experimental plugin:
http://tools.android.com/tech-docs/new-build-system/gradle-experimental.

What can I do to investigate this?

Body:
For compiling cpp code in Android Studio:

you need to download CMAKE, LLDB and NDK on Android SDK Manager.

you need to make CMakeList.txt and need to put script for compiling cpp files.

you need to put following lines in build.gradle:

externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}


问:
How to count no of rows in table from web application using selenium python webdriver
How to count the rows in the table from web application by using selenium python web driver. Here we can retrieve all data in the table from web application but couldn't count the rows and columns, please give me idea of how to do this.</p>

答:
For python users the simple way of counting a tag is as follows.</p>

```<code>!#use find_elements_by_xpath

test_elem = self.driver.find_elements_by_xpath("//div[@id='host-history']/table[1]/tbody[1]/tr")

!#then check the len of the returnes list

print (len(test_elem))
</code>```

Body:
For python users the simple way of counting a tag is as follows.

!#use find_elements_by_xpath

test_elem = self.driver.find_elements_by_xpath("//div[@id='host-history']/table[1]/tbody[1]/tr")

!#then check the len of the returnes list

print (len(test_elem))


问:
Laravel error handling, get_class vs instanceof
In the following code in app/Exceptions/Handler.php, the first one doesn't work but the second one does.

dd(get_class($exception)); outputs "Illuminate\Database\Eloquent\ModelNotFoundException".

The first one is similar to the doc. How can I make it work using instanceof?

```<code>    public function render($request, Exception $exception)
    {
        //dd(get_class($exception));
        // this does not work.
        if ($exception instanceof Illuminate\Database\Eloquent\ModelNotFoundException
) {
            return response()->json(['error'=>['message'=>'Resouce not found']], 404);
        }
        // This one works.
        if(get_class($exception) == "Illuminate\Database\Eloquent\ModelNotFoundException") {
            return response()->json(['error'=>['message'=>'Resouce not found']], 404);
        }

        return parent::render($request, $exception);
    }
</code>```

答:
To use instanceof you must use the full class name, and if your class has a namespace then you should use the fully qualified class name of the class.

And there is an other way to use instanceof using a short name (alias) for a given class thanks to use statement, in your case you can use it like so :

```<code>use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; // on top of course :)

if ($exception instanceof ModelNotFoundException) {
        return response()->json(['error'=>['message'=>'Resouce not found']], 404);
}
</code>```

Body:
In the following code in app/Exceptions/Handler.php, the first one doesn't work but the second one does.

dd(get_class($exception)); outputs "Illuminate\Database\Eloquent\ModelNotFoundException".

The first one is similar to the doc. How can I make it work using instanceof?

    public function render($request, Exception $exception)
    {
        //dd(get_class($exception));
        // this does not work.
        if ($exception instanceof Illuminate\Database\Eloquent\ModelNotFoundException
) {
            return response()->json(['error'=>['message'=>'Resouce not found']], 404);
        }
        // This one works.
        if(get_class($exception) == "Illuminate\Database\Eloquent\ModelNotFoundException") {
            return response()->json(['error'=>['message'=>'Resouce not found']], 404);
        }

        return parent::render($request, $exception);
    }

Body:
To use instanceof you must use the full class name, and if your class has a namespace then you should use the fully qualified class name of the class.

And there is an other way to use instanceof using a short name (alias) for a given class thanks to use statement, in your case you can use it like so :

use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; // on top of course :)

if ($exception instanceof ModelNotFoundException) {
        return response()->json(['error'=>['message'=>'Resouce not found']], 404);
}


问:
How can I escape a \n from an html-attribute to a js-string?
I'm trying to pass new-lines from a html-attribute to a javascriptstring, in order to apply it to a textarea:

```<code><input id="check input" type="checkbox" data-mode2="Varför är det så mycket administration! \n\n">Mer tid att lägga på att träffa barn, istället för administration</input>

string = $('#check').data('hello'+mode);
$('textarea').val(string);
</code>```

This outputs the \n as characters rather than a new line.

答:
You need to:

Define the data format you are using

Parse that data format

You could say the data format is "Plain text except that new lines are expressed as \n".

In which case you could use a simple regular expression replacement.

```<code>var parsed_string = string.replace(/\\n/g, "\n");
</code>```

You might be better off using an existing language, like JSON, which would give you more options in the future and come with prebuilt parsers.

var mode = "mode2";
var string = $('#check').data(mode);
var parsed_string = JSON.parse(string);
$('textarea').val(parsed_string);```
<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>
<label><input id="check" type="checkbox" data-mode2=""Varför är det så mycket administration! \n\n"">Mer tid att lägga på att träffa barn, istället för administration</label>
<textarea></textarea></code>```

Note that I had to wrap the data in " characters to make it a valid JSON string.

Body:
I'm trying to pass new-lines from a html-attribute to a javascriptstring, in order to apply it to a textarea:

<input id="check input" type="checkbox" data-mode2="Varför är det så mycket administration! \n\n">Mer tid att lägga på att träffa barn, istället för administration</input>

string = $('#check').data('hello'+mode);
$('textarea').val(string);

This outputs the \n as characters rather than a new line.

Body:
You need to:

Define the data format you are using

Parse that data format

You could say the data format is "Plain text except that new lines are expressed as \n".

In which case you could use a simple regular expression replacement.

var parsed_string = string.replace(/\\n/g, "\n");

You might be better off using an existing language, like JSON, which would give you more options in the future and come with prebuilt parsers.

var mode = "mode2";
var string = $('#check').data(mode);
var parsed_string = JSON.parse(string);
$('textarea').val(parsed_string);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input id="check" type="checkbox" data-mode2="&quot;Varför är det så mycket administration! \n\n&quot;">Mer tid att lägga på att träffa barn, istället för administration</label>
<textarea></textarea>

Note that I had to wrap the data in " characters to make it a valid JSON string.