问:
How to run ASP.NET project connecting Visual Studio with github
I have a github repository with an ASP.NET project.

I've connected my Visual Studio 2019 with Github (And cloned the repository).

When I try to run the webpage appears this error:

Configuration error Description: Error during the processing of a configuration file required to service this request. Review the following specific error details and modify the configuration file accordingly.

Analyzer error message: The provider type CodeDom "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version = 1.0.7.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e364e364e364e364e364e

Source Code Error:

```<code>Línea 23:         <compilers>
Línea 24:             <compiler language="c#;cs;csharp" extension=".cs"
Línea 25:                 type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Línea 26:                 warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>```
```

答:
You to need to Install Microsoft.CodeDom.Providers.DotNetCompilerPlatform Nuget Package

Right Click your Project

```<code> Manage Nuget Packages > Browse > Microsoft.CodeDom.Providers.DotNetCompilerPlatform > Install
</code>```

Body:
I have a github repository with an ASP.NET project.

I've connected my Visual Studio 2019 with Github (And cloned the repository).

When I try to run the webpage appears this error:

Configuration error Description: Error during the processing of a configuration file required to service this request. Review the following specific error details and modify the configuration file accordingly.

Analyzer error message: The provider type CodeDom "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version = 1.0.7.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e364e364e364e364e364e

Source Code Error:

Línea 23:         <compilers>
Línea 24:             <compiler language="c#;cs;csharp" extension=".cs"
Línea 25:                 type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Línea 26:                 warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>```

Body:
You to need to Install Microsoft.CodeDom.Providers.DotNetCompilerPlatform Nuget Package

Right Click your Project

 Manage Nuget Packages > Browse > Microsoft.CodeDom.Providers.DotNetCompilerPlatform > Install


来源: stackexchange

问:
How to fix the error - Operand type clash: date is incompatible with int
```<code>INSERT INTO Buy
SELECT Title
    ,Type1
    ,Tedat
    ,DATEADD(DAY, - 2, DATEADD(YEAR, - 1, Tarikh))
    ,Descrip
FROM Buy
WHERE (
    Tarikh BETWEEN 2019-03-21
    AND 2020-03-19
)
</code>```

答:
You need to wrap the date in quotes, like '2019-03-21' instead of 2019 - 03 - 21

```<code>INSERT INTO Buy
SELECT Title
    ,Type1
    ,Tedat
    ,DATEADD(DAY, -2, DATEADD(YEAR, -1, Tarikh))
    ,Descrip
FROM Buy
WHERE Tarikh BETWEEN '2019-03-21' AND '2020-03-19'
</code>```

Besides, You ought to specify the column to avoid an unexpected error (insert into incorrect column or Just want to insert a number of columns instead of all)

```<code>INSERT INTO Buy(column1, column2,.. )
SELECT  Title, Tedat, ..
FROM    Buy
</code>```

Read the following post to have a better understanding

Insert into certain columns

ContentLicense: CC BY-SA 4.0

Body:
You need to wrap the date in quotes, like '2019-03-21' instead of 2019 - 03 - 21

INSERT INTO Buy
SELECT Title
    ,Type1
    ,Tedat
    ,DATEADD(DAY, -2, DATEADD(YEAR, -1, Tarikh))
    ,Descrip
FROM Buy
WHERE Tarikh BETWEEN '2019-03-21' AND '2020-03-19'

Besides, You ought to specify the column to avoid an unexpected error (insert into incorrect column or Just want to insert a number of columns instead of all)

INSERT INTO Buy(column1, column2,.. )
SELECT  Title, Tedat, ..
FROM    Buy

Read the following post to have a better understanding

Insert into certain columns


问:
Surprising expansion of variadic GNU C preprocessor macros in the presence of the ## operator
If we define a macro

```<code>#define M(x, ...) { x, __VA_ARGS__ }
</code>```

and then use it passing itself as an argument

```<code>M(M(1, 2), M(3, 4), M(5, 6))
</code>```

then it expands to the expected form:

```<code>{ { 1, 2 }, { 3, 4 }, { 5, 6 } }
</code>```

However, when we use the ## operator (to prevent dangling comma from appearing in the output in the case of the single argument invocations, as documented in the GCC manual), i.e.

```<code>#define M0(x, ...) { x, ## __VA_ARGS__ }
</code>```

then the expansion of arguments in

```<code>M0(M0(1,2), M0(3,4), M0(5,6))
</code>```

seems to stop after the first argument, i.e. we get:

```<code>{ { 1,2 }, M0(3,4), M0(5,6) }
</code>```

Is this behavior a bug, or does it stem from some principle?

(I have also checked it with clang, and it behaves in the same way as GCC)

答:
Way down at the end of this answer there is a possible solution.

Is this behavior a bug, or does it stem from some principle?

It stems from two principles whose interaction is pretty subtle. So I agree that it is surprising, but it's not a bug.

The two principles are the following:

Inside the replacement of macro invocation, that macro is not expanded. (See the GCC Manual Section 3.10.5, Self-Referential Macros or the C Standard, §6.10.3.4 paragraph 2.) This  precludes recursive macro expansion, which in most cases would produce infinite recursion if allowed. Although it is likely that no-one anticipated such uses, it turns out that there would be ways of using recursive macro expansion which would not result in infinite recursion (see the Boost Preprocessor Library documentation for a thorough discussion of this issue), but the standard isn't going to get changed now.

If ## is applied to a macro argument, it suppresses macro expansion of that argument. (See the GCC Manual section 3.5, Concatenation or the C Standard, §6.10.3.3 paragraph 2.) The suppression of expansion is part of the C Standard, but GCC/Clang's extension to allow use of ## to conditionally suppress the comma preceding __VA_ARGS__ is non-standard. (See the GCC Manual Section 3.6, Variadic Macros.) Apparently, the extension still respects the standard's rule about not expanding concatenated macro arguments.

Now, the curious thing about the second point, with respect to optional comma suppression, is that you hardly ever notice it in practice. You can use ## to conditionally suppress commas and arguments will still get expanded as normal:

```<code>#define SHOW_ARGS(arg1, ...) Arguments are (arg1, ##__VA_ARGS__)
#define DOUBLE(a) (2 * a)
SHOW_ARGS(DOUBLE(2))
SHOW_ARGS(DOUBLE(2), DOUBLE(3))
</code>```

This expands to:

```<code>Arguments are ((2 * 2))
Arguments are ((2 * 2), (2 * 3))
</code>```

Both DOUBLE(2) and DOUBLE(3) are expanded normally, despite the fact that one of them is an argument to the concatenation operator.

But there's a subtlety to macro expansion. Expansion happens twice:

First, macro arguments are expanded. (This expansion is in the context of the text which invokes the macro.) These expanded arguments are substituted for the parameters in the macro replacement body (but only where the parameter is not an argument to # or ##).

Then the # and ## operators are applied to the replacement token list.

Finally, the resulting replacement tokens are inserted into the input stream, so that they are expanded again. This time, the expansion is in the context of the macro so recursive invocation is suppressed.

With that in mind, we see that in SHOW_ARGS(DOUBLE(2), DOUBLE(3)), DOUBLE(2) is expanded in step 1, before being inserted into the replacement token list, and DOUBLE(3) is expanded in step 3, as part of the replacement token list.

This doesn't make a difference with DOUBLE inside SHOW_ARGS, since they're different macros. But the difference would become apparent if they were the same macro.

To see the difference, consider the following macro:

```<code>#define INVOKE(A, ...) A(__VA_ARGS__)
</code>```

That macro creates a macro invocation (or a function invocation, but here we're only interested in the case where it's a macro). That is, in turns INVOKE(X, Y) into X(Y). (That's a simplification of a useful feature, where the named macro is actually invoked several times, possibly with slightly different arguments.)

That works fine with SHOW_ARGS:

```<code>INVOKE(SHOW_ARGS, one arg)

⇒ Arguments are (one arg)
</code>```

But if we try to INVOKE the macro INVOKE itself, we find that the ban on recursive invocation takes effect:

```<code>INVOKE(INVOKE, SHOW_ARGS, one arg)

⇒ INVOKE(SHOW_ARGS, one arg)
</code>```

"Of course", we could expand INVOKE as an argument to INVOKE:

```<code>INVOKE(SHOW_ARGS, INVOKE(SHOW_ARGS, one arg))

⇒ Arguments are (Arguments are (one arg))
</code>```

That works fine because there is no ## inside INVOKE, so expansion of the argument is not suppressed. But if the expansion of the argument had been suppressed, then the argument would be inserted into the macro body unexpanded, and then it would become a recursive expansion.

So that's what is going on in your example:

```<code>#define M0(x, ...) { x, ## __VA_ARGS__ }
M0(M0(1,2), M0(3,4), M0(5,6))

⇒ { { 1,2 }, M0(3,4), M0(5,6) }
</code>```

Here, the first argument to the outer M0, M0(1,2), is not used with ##, so it is expanded as part of the invocation. The other two arguments are part of __VA_ARGS__, which is used with ##. Consequently, they are not expanded prior to being substituted into the macro's replacement list. But as part of the macro's replacement list, their expansion is suppressed by the no-recursive-macros rule.

You can easily work around that by defining two versions of the M0 macro, with the same contents but different names (as suggested in a comment to the OP):

```<code>#define M0(x, ...) { x, ## __VA_ARGS__ }
M0(M1(1,2), M1(3,4), M1(5,6))

⇒ { { 1,2 }, { 3,4 }, { 5,6 } }
</code>```

But that's not very pleasant.

Solution: Use __VA_OPT__

C++2a will include a new feature designed specifically to assist with suppressing commas in variadic invocations: the __VA_OPT__ function-like macro. Inside a variadic macro expansion, __VA_OPT__(x) expands to its argument provided that there is at least one token in the variadic arguments. But if __VA_ARGS__ expands to an empty token list, so does __VA_OPT__(x). Thus, __VA_OPT__(,) can be used for conditional suppression of a comma just like the GCC ## extension, but unlike ##, it does not trigger suppression of macro expansion.

As an extension to the C standard, recent versions of GCC and Clang implement __VA_OPT__ for C as well as C++. (See the GCC Manual Section 3.6, Variadic Macros.) So if you're willing to rely on relatively recent compiler versions, there is a very clean solution:

```<code>#define M0(x, ...) { x __VA_OPT__(,) __VA_ARGS__ }
M0(M0(1,2), M0(3,4), M0(5,6))

⇒ { { 1 , 2 } , { 3 , 4 }, { 5 , 6 } }
</code>```

Notes:

You can see these examples on Godbolt

This question was originally closed as a duplicate of Variadic macros: expansion of pasted tokens but I don't think that answer is really adequate to this particular situation.

Body:
If we define a macro

#define M(x, ...) { x, __VA_ARGS__ }

and then use it passing itself as an argument

M(M(1, 2), M(3, 4), M(5, 6))

then it expands to the expected form:

{ { 1, 2 }, { 3, 4 }, { 5, 6 } }

However, when we use the ## operator (to prevent dangling comma from appearing in the output in the case of the single argument invocations, as documented in the GCC manual), i.e.

#define M0(x, ...) { x, ## __VA_ARGS__ }

then the expansion of arguments in

M0(M0(1,2), M0(3,4), M0(5,6))

seems to stop after the first argument, i.e. we get:

{ { 1,2 }, M0(3,4), M0(5,6) }

Is this behavior a bug, or does it stem from some principle?

(I have also checked it with clang, and it behaves in the same way as GCC)

Body:
Way down at the end of this answer there is a possible solution.

Is this behavior a bug, or does it stem from some principle?

It stems from two principles whose interaction is pretty subtle. So I agree that it is surprising, but it's not a bug.

The two principles are the following:

Inside the replacement of macro invocation, that macro is not expanded. (See the GCC Manual Section 3.10.5, Self-Referential Macros or the C Standard, §6.10.3.4 paragraph 2.) This  precludes recursive macro expansion, which in most cases would produce infinite recursion if allowed. Although it is likely that no-one anticipated such uses, it turns out that there would be ways of using recursive macro expansion which would not result in infinite recursion (see the Boost Preprocessor Library documentation for a thorough discussion of this issue), but the standard isn't going to get changed now.

If ## is applied to a macro argument, it suppresses macro expansion of that argument. (See the GCC Manual section 3.5, Concatenation or the C Standard, §6.10.3.3 paragraph 2.) The suppression of expansion is part of the C Standard, but GCC/Clang's extension to allow use of ## to conditionally suppress the comma preceding __VA_ARGS__ is non-standard. (See the GCC Manual Section 3.6, Variadic Macros.) Apparently, the extension still respects the standard's rule about not expanding concatenated macro arguments.

Now, the curious thing about the second point, with respect to optional comma suppression, is that you hardly ever notice it in practice. You can use ## to conditionally suppress commas and arguments will still get expanded as normal:

#define SHOW_ARGS(arg1, ...) Arguments are (arg1, ##__VA_ARGS__)
#define DOUBLE(a) (2 * a)
SHOW_ARGS(DOUBLE(2))
SHOW_ARGS(DOUBLE(2), DOUBLE(3))

This expands to:

Arguments are ((2 * 2))
Arguments are ((2 * 2), (2 * 3))

Both DOUBLE(2) and DOUBLE(3) are expanded normally, despite the fact that one of them is an argument to the concatenation operator.

But there's a subtlety to macro expansion. Expansion happens twice:

First, macro arguments are expanded. (This expansion is in the context of the text which invokes the macro.) These expanded arguments are substituted for the parameters in the macro replacement body (but only where the parameter is not an argument to # or ##).

Then the # and ## operators are applied to the replacement token list.

Finally, the resulting replacement tokens are inserted into the input stream, so that they are expanded again. This time, the expansion is in the context of the macro so recursive invocation is suppressed.

With that in mind, we see that in SHOW_ARGS(DOUBLE(2), DOUBLE(3)), DOUBLE(2) is expanded in step 1, before being inserted into the replacement token list, and DOUBLE(3) is expanded in step 3, as part of the replacement token list.

This doesn't make a difference with DOUBLE inside SHOW_ARGS, since they're different macros. But the difference would become apparent if they were the same macro.

To see the difference, consider the following macro:

#define INVOKE(A, ...) A(__VA_ARGS__)

That macro creates a macro invocation (or a function invocation, but here we're only interested in the case where it's a macro). That is, in turns INVOKE(X, Y) into X(Y). (That's a simplification of a useful feature, where the named macro is actually invoked several times, possibly with slightly different arguments.)

That works fine with SHOW_ARGS:

INVOKE(SHOW_ARGS, one arg)

⇒ Arguments are (one arg)

But if we try to INVOKE the macro INVOKE itself, we find that the ban on recursive invocation takes effect:

INVOKE(INVOKE, SHOW_ARGS, one arg)

⇒ INVOKE(SHOW_ARGS, one arg)

"Of course", we could expand INVOKE as an argument to INVOKE:

INVOKE(SHOW_ARGS, INVOKE(SHOW_ARGS, one arg))

⇒ Arguments are (Arguments are (one arg))

That works fine because there is no ## inside INVOKE, so expansion of the argument is not suppressed. But if the expansion of the argument had been suppressed, then the argument would be inserted into the macro body unexpanded, and then it would become a recursive expansion.

So that's what is going on in your example:

#define M0(x, ...) { x, ## __VA_ARGS__ }
M0(M0(1,2), M0(3,4), M0(5,6))

⇒ { { 1,2 }, M0(3,4), M0(5,6) }

Here, the first argument to the outer M0, M0(1,2), is not used with ##, so it is expanded as part of the invocation. The other two arguments are part of __VA_ARGS__, which is used with ##. Consequently, they are not expanded prior to being substituted into the macro's replacement list. But as part of the macro's replacement list, their expansion is suppressed by the no-recursive-macros rule.

You can easily work around that by defining two versions of the M0 macro, with the same contents but different names (as suggested in a comment to the OP):

#define M0(x, ...) { x, ## __VA_ARGS__ }
M0(M1(1,2), M1(3,4), M1(5,6))

⇒ { { 1,2 }, { 3,4 }, { 5,6 } }

But that's not very pleasant.

Solution: Use __VA_OPT__

C++2a will include a new feature designed specifically to assist with suppressing commas in variadic invocations: the __VA_OPT__ function-like macro. Inside a variadic macro expansion, __VA_OPT__(x) expands to its argument provided that there is at least one token in the variadic arguments. But if __VA_ARGS__ expands to an empty token list, so does __VA_OPT__(x). Thus, __VA_OPT__(,) can be used for conditional suppression of a comma just like the GCC ## extension, but unlike ##, it does not trigger suppression of macro expansion.

As an extension to the C standard, recent versions of GCC and Clang implement __VA_OPT__ for C as well as C++. (See the GCC Manual Section 3.6, Variadic Macros.) So if you're willing to rely on relatively recent compiler versions, there is a very clean solution:

#define M0(x, ...) { x __VA_OPT__(,) __VA_ARGS__ }
M0(M0(1,2), M0(3,4), M0(5,6))

⇒ { { 1 , 2 } , { 3 , 4 }, { 5 , 6 } }

Notes:

You can see these examples on Godbolt

This question was originally closed as a duplicate of Variadic macros: expansion of pasted tokens but I don't think that answer is really adequate to this particular situation.


问:
How to conditionally render a dialog and drawer in material UI for different screen resolutions?
I want to show a dialog in a desktop view and a drawer with the same content in the mobile view.

I am using Material UI as a component library and I am using the Drawer and Dialog component of it.

Please share if you have done something like this, or if you have taken a different approach to handle this.

答:
just need to add resize event on your component like so :

```<code>componentDidMount() {
  document.addEventListener('resize' , this.handleResize)
}

handleResize = (event) => {
   if(window.innerWidth < 400) {
     // handle your component changes
   }
}

// dont forget to remove your event listener on component unmount

componentWillUnMount() {
  document.removeEventListener('resize',this.handleResize)
}

</code>```

and if you using hooks :

```<code>useEffect(() => {
   document.addEventListener('resize' , handleResize);

   return () => {
     document.removeEventListener('resize',handleResize);
  }
})

const handleResize = (event) => {
   if(window.innerWidth < 400) {
     // handle your component changes
   }
}

</code>```

Body:
just need to add resize event on your component like so :

componentDidMount() {
  document.addEventListener('resize' , this.handleResize)
}

handleResize = (event) => {
   if(window.innerWidth < 400) {
     // handle your component changes
   }
}

// dont forget to remove your event listener on component unmount

componentWillUnMount() {
  document.removeEventListener('resize',this.handleResize)
}

and if you using hooks :

useEffect(() => {
   document.addEventListener('resize' , handleResize);

   return () => {
     document.removeEventListener('resize',handleResize);
  }
})

const handleResize = (event) => {
   if(window.innerWidth < 400) {
     // handle your component changes
   }
}


问:
Laravel routing for deleting one record
I'm new to Laravel (but not developing) and am following along in the free Laravel 6 from Scratch course at Laracasts. I can't afford to subscribe to Laracasts so I can't ask questions there.

I've been following along as the instructor build an app that listed a bunch of articles, displayed a single article, created and saved a new article, and edited an existing article and saved it back to the database. Now I'm trying to delete an individual record but I can't quite get it right.

On the page where I display a single record, I give the user the option of editing the record or of deleting the record via two separate links. The Edit process works fine: it displays the record, allows me to change it (assuming I pass the validations), and then saves it to the database correctly.

The delete process fails. Since I am already displaying the record to the user and have presumably satisfied themselves that it IS the record they want to delete, I want to simply go to the destroy() method of my controller. But I'm obviously doing it wrong. I think the code in the controller is correct so it may be the routes that are messed up. The course doesn't show you how to do a delete and of the videos and stack overflow articles I've seen use different techniques, none of which I fully understand. I'm hoping someone can tell me what I'm doing wrong. There can't be more than 1 or 2 lines that are wrong....

Here's the message I get when I click on the Delete button when I am displaying Article #6:

```<code>Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
http://localhost:8000/articles/6/delete
</code>```

Here's my routing:

```<code>Route::get('/articles', 'ArticlesController@index');
Route::post('/articles', 'ArticlesController@store');
Route::get('/articles/create', 'ArticlesController@create');
Route::get('/articles/{article}', 'ArticlesController@show');
Route::get('/articles/{article}/edit', 'ArticlesController@edit');
Route::put('/articles/{article}', 'ArticlesController@update');
Route::post('/articles/{article}/delete', 'ArticlesController@destroy');
</code>```

Here's the page that displays the article and let's the user click Edit or Delete links:

```<code>@extends ('layout');

@section ('content');

<div id="wrapper">
<div id="page" class="container">
    <div id="content">
        <div class="title">
            <h2>{{ $article->title }}</h2>
            <span class="byline">{{ $article->author}}</span></div>
        <p><img src="{{ $article->photopath}}" alt="" class="image image-full" /> </p>
        <p>{{ $article->body }}
        <p><a class="article-link" href="/articles/{{ $article->id }}/edit">Edit This Article</a>
        <a class="article-link" href="/articles/{{ $article->id }}/delete">Delete This Article</a></p>
    </div>
</div>
</div>
@endsection
</code>```

Lastly, here's my ArticlesController:

```<code><?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
public function index()
{
    $articles = Article::latest()->paginate(2);
    return view ('articles.index', ['articles' => $articles]);
}

public function show(Article $article)
{
    return view('articles.show', ['article' => $article]);
}

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

public function store()
{
    //Stores a NEW article
    Article::create($this->validateArticle());
    return redirect('/articles');
}

public function edit(Article $article)
{
    return view('articles.edit', ['article' => $article]);
}

public function update(Article $article)
{
    //Updates an EXISTING article
    $article->update($this->validateArticle());
    return redirect('/articles/'.$article->id);
}

public function validateArticle()
{
    return request()->validate([
        'title' => ['required', 'min:5', 'max:20'],
        'author' => ['required', 'min:5', 'max:30'],
        'photopath' => ['required', 'min:10', 'max:100'],
        'excerpt' => ['required', 'min:10', 'max:50'],
        'body' => ['required', 'min:50', 'max:500']
    ]);
}

public function delete(Article $article)
{
    return view('articles.delete', ['article' => $article]);
}

public function destroy(Article $article)
{
    $article = Article::find($article->id);
    $article->delete();
    return redirect('/articles');
}
}
</code>```

答:
```<code>// Blade file
@extends('layouts.backend.app')

@section('title','Article')

@push('css')
<link href="{{ asset('backend/plugins/jquery-datatable/skin/bootstrap/css/dataTables.bootstrap.css') }}" rel="stylesheet">
@endpush
@section('content')
<div class="container-fluid">
    <div class="block-header">
        <h2>
        <a class="btn btn-info" href="{{ route('admin.tag.create') }}">
            <i class="material-icons">add</i>
        {{ __('ADD ARTICLE') }}
        </a>
        </h2>
    </div>

    <!-- Exportable Table -->
    <div class="row clearfix">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="card">
                <div class="header">
                    <h2>
                        <a href="{{ route('admin.tag.index') }}">
                            {{ __('ALL ARTICLE') }}
                            <span class="btn btn-warning sm">{{ $articles->count() }}</span>
                        </a>
                    </h2>
                </div>
                <div class="body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped table-hover dataTable js-exportable">
                            <thead>
                                <tr>
                                <th>{{__('Sl')}}</th>
                                <th>{{__('Name')}}</th>
                                <th>{{__('Slug')}}</th>
                                <th>i{{__('Post Count')}}</th>
                                <th>{{__('Create At')}}</th>
                                <th>{{__('Action')}}</th>
                            </tr>
                            </thead>
                            <tfoot>
                                <tr>
                                    <th>{{__('Sl')}}</th>
                                    <th>{{__('Name')}}</th>
                                    <th>{{__('Slug')}}</th>
                                    <th>{{__('Post Count')}}</th>
                                    <th>{{__('Create At')}}</th>
                                    <th>{{__('Action')}}</th>
                                </tr>
                            </tfoot>
                            <tbody>
                               @if(Auth::check() && Auth::user()->role->id == 1)
                                   @foreach($articles as $key=>$article)
                                       <tr>
                                           <td>{{ $key + 1 }}</td>
                                           <td>{{ $article->name }}</td>
                                           <td>{{ $article->slug }}</td>
                                           <td>{{ $article->posts->count() }}</td>
                                           <td>{{ $article->created_at->diffForHumans() }}</td>
                                           <td >
                                               <a href="{{ route('admin.$article.edit',$article->id) }}" class="btn btn-info waves-effect">
                                                   <i class="material-icons">edit</i>
                                               </a>
                                               <button class="btn btn-danger waves-effect" type="button" onclick="deletearticle({{ $article->id }})">
                                                   <i class="material-icons">delete</i>
                                               </button>
                                               <form id="delete-form-{{ $article->id }}" action="{{ route('admin.article.destroy',$article->id) }}" method="POST" style="display: none;">
                                                   @csrf
                                                   @method('DELETE')
                                               </form>
                                           </td>
                                       </tr>
                                   @endforeach
                                @else
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- #END# Exportable Table -->
</div>
@endsection

@push('js')
<script src="{{asset ('backend/plugins/jquery-datatable/jquery.dataTables.js') }}"></script>
<script src="{{asset ('backend/plugins/jquery-datatable/skin/bootstrap/js/dataTables.bootstrap.js') }}"></script>
<script src="{{asset ('backend/plugins/jquery-datatable/extensions/export/dataTables.buttons.min.js') }}"></script>
<script src="{{asset ('backend/plugins/jquery-datatable/extensions/export/buttons.flash.min.js') }}"></script>
<script src="{{asset ('backend/plugins/jquery-datatable/extensions/export/jszip.min.js') }}"></script>
<script src="{{asset ('backend/plugins/jquery-datatable/extensions/export/pdfmake.min.js') }}"></script>
<script src="{{asset ('backend/plugins/jquery-datatable/extensions/export/vfs_fonts.js') }}"></script>
<script src="{{asset ('backend/plugins/jquery-datatable/extensions/export/buttons.html5.min.js') }}"></script>
<script src="{{asset ('backend/plugins/jquery-datatable/extensions/export/buttons.print.min.js') }}"></script>
<script src="{{ asset('backend/js/pages/tables/jquery-datatable.js') }}"></script>
<script src="https://unpkg.com/sweetalert2@7.19.1/dist/sweetalert2.all.js"></script>

<script type="text/javascript">
    function deletearticle(id) {
        swal({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'No, cancel!',
            confirmButtonClass: 'btn btn-success',
            cancelButtonClass: 'btn btn-danger',
            buttonsStyling: false,
            reverseButtons: true
        }).then((result) => {
            if (result.value) {
                event.preventDefault();
                document.getElementById('delete-form-'+id).submit();
            } else if (
                // Read more about handling dismissals
                result.dismiss === swal.DismissReason.cancel
            ) {
                swal(
                    'Cancelled',
                    'Your data is safe :)',
                    'error'
                )
            }
        })
    }
</script>
@endpush

//  web.php
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
    Route::get('dashboard','DashboardController@index')->name('dashboard');
    Route::resource('article','ArticleController');

});
// Controller file
<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use App\Article;
class TagController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $articles = Article::latest()->get();
        return view('admin.article.index',compact('articles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.article.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'name' => 'required|unique:articles'
        ]);
        $article = new Article();
        $article->name = $request->name;
        $article->slug = str_slug($request->name);
        $article->save();
        Toastr::success('Article Successfully Saved :)','Success');
        return redirect()->route('admin.article.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $tag = Article::find($id);
        return view('admin.article.edit',compact('article'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'name' => 'required'
        ]);

        $article = Article::find($id);
        $article->name = $request->name;
        $article->slug = str_slug($request->name);
        $article->save();
        Toastr::success('Article Successfully Updated','Success');
        return redirect()->route('admin.article.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Article::find($id)->delete();
        Toastr::success('Article Successfully Deleted',"Success");
        return redirect()->back();
    }
}
</code>```

Title: Laravel routing for deleting one record

Body:
I'm new to Laravel (but not developing) and am following along in the free Laravel 6 from Scratch course at Laracasts. I can't afford to subscribe to Laracasts so I can't ask questions there.

I've been following along as the instructor build an app that listed a bunch of articles, displayed a single article, created and saved a new article, and edited an existing article and saved it back to the database. Now I'm trying to delete an individual record but I can't quite get it right.

On the page where I display a single record, I give the user the option of editing the record or of deleting the record via two separate links. The Edit process works fine: it displays the record, allows me to change it (assuming I pass the validations), and then saves it to the database correctly.

The delete process fails. Since I am already displaying the record to the user and have presumably satisfied themselves that it IS the record they want to delete, I want to simply go to the destroy() method of my controller. But I'm obviously doing it wrong. I think the code in the controller is correct so it may be the routes that are messed up. The course doesn't show you how to do a delete and of the videos and stack overflow articles I've seen use different techniques, none of which I fully understand. I'm hoping someone can tell me what I'm doing wrong. There can't be more than 1 or 2 lines that are wrong....

Here's the message I get when I click on the Delete button when I am displaying Article #6:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
http://localhost:8000/articles/6/delete

Here's my routing:

Route::get('/articles', 'ArticlesController@index');
Route::post('/articles', 'ArticlesController@store');
Route::get('/articles/create', 'ArticlesController@create');
Route::get('/articles/{article}', 'ArticlesController@show');
Route::get('/articles/{article}/edit', 'ArticlesController@edit');
Route::put('/articles/{article}', 'ArticlesController@update');
Route::post('/articles/{article}/delete', 'ArticlesController@destroy');

Here's the page that displays the article and let's the user click Edit or Delete links:

@extends ('layout');

@section ('content');

{{ $article->title }}

            {{ $article->author}}

photopath}}" alt="" class="image image-full" />

{{ $article->body }}

id }}/edit">Edit This Article
        id }}/delete">Delete This Article

@endsection

Lastly, here's my ArticlesController:

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
public function index()
{
    $articles = Article::latest()->paginate(2);
    return view ('articles.index', ['articles' => $articles]);
}

public function show(Article $article)
{
    return view('articles.show', ['article' => $article]);
}

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

public function store()
{
    //Stores a NEW article
    Article::create($this->validateArticle());
    return redirect('/articles');
}

public function edit(Article $article)
{
    return view('articles.edit', ['article' => $article]);
}

public function update(Article $article)
{
    //Updates an EXISTING article
    $article->update($this->validateArticle());
    return redirect('/articles/'.$article->id);
}

public function validateArticle()
{
    return request()->validate([
        'title' => ['required', 'min:5', 'max:20'],
        'author' => ['required', 'min:5', 'max:30'],
        'photopath' => ['required', 'min:10', 'max:100'],
        'excerpt' => ['required', 'min:10', 'max:50'],
        'body' => ['required', 'min:50', 'max:500']
    ]);
}

public function delete(Article $article)
{
    return view('articles.delete', ['article' => $article]);
}

public function destroy(Article $article)
{
    $article = Article::find($article->id);
    $article->delete();
    return redirect('/articles');
}
}


问:
SQL query, am I wrong somewhere?
I am trying to pull distinct City names and only one zipcode for any given City.

```<code>zip city    state
00603   AGUADILLA   PR
00604   AGUADILLA   PR
00605   AGUADILLA   PR
</code>```

Query:

```<code>SELECT DISTINCT (city),(zip)
  FROM zips
 WHERE state = 'PR'
</code>```

I tried group by clause as well, let me know where am I wrong here.

答:
```<code>SELECT city, max(zip) from zips where state='PR' group by city, state
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL query, am I wrong somewhere?

Body:
I am trying to pull distinct City names and only one zipcode for any given City.

zip city    state
00603   AGUADILLA   PR
00604   AGUADILLA   PR
00605   AGUADILLA   PR

Query:

SELECT DISTINCT (city),(zip)
  FROM zips
 WHERE state = 'PR'

I tried group by clause as well, let me know where am I wrong here.


问:
Unable to Successfully Split HTML-Like Strings with Python RE Using Lookarounds
```<code>'''
Trying to split string 'text' below so that all segments are found and split.
There are three flavors of segments:
    A:    <tag attr1="one" attr2>some text</tag>
    B:    <tag attr1="one" attr2 text="some text"/>
    C:    some tagless text
I can't use an HTML parser, because C segments are in plain English.

I would like to be able to accept '/' as part of the text.
So, '/' is just a char unless it precedes '>' or comes before 'tag'.
In a perfect world, I would also like to accept '<' and '>', too.
So '<' is just a char unless it precedes 't' or '/'.

Currently I use patt[1] to split text with A and C segments, but now I want to be
able to split strings with B segments, too. Also, patt[1] does not allow '/' to be
passed in as a regular char without breaking the routine. Although it seems
to work, I don't like that the regexp limits matching according to '/'.

The goal is to properly split the text string into the expected output strings. Can someone
tell me what I'm doing wrong?  Running the regexp on https://pythex.org/ looks okay, but it
still doesn't run properly under CPython 3.6 - 3.9.
'''
import pprint, re, sys, unittest

class TestClass(unittest.TestCase):

    sub = False # True #
    patt = {}
    patt[1] = r'(<t(?:ag)?\s*[^>]*>[^>]*</t(?:ag)?>)' # orig, works for A and C but not B

    patt[2] = r'(<t(?:ag)?.*?(?:/t(?:ag)?>|/>))' # misses one
    #           1  2    2    3    4    4     31
    patt[3] = r'(<t(?:ag)?[^/]*/t?>)' # misses one
    #           1  2    2          1
    patt[4] = r'(<t(?:ag)?.*?(?<=/)(?:t(?:ag)?)?>)' # with lookarounds. still misses one.
    patt[5] = r'(<t(?:ag)?(?!/>)(?!/t).*?(?<=/)(?:t(?:ag)?)?>)' # with lookarounds. tried adding negs
    patt[6] = r'(<t(?:ag)?.*?(?!/>)(?!/t)(?<=/)(?:t(?:ag)?)?>)'

    text = "start: <t s=10 B=1>Size 10 bold</t><t siz=6>Size 6\nNew Line </t>" \
           "<t u w=bold>Underlined and Bolded\n</t><t it>Italics</t><t>default</t>" \
           '<t fam="Courier New" siz=18>Courier 18</t>' \
           "<t bitmap=question/><t bitmap=info/> and <t fg=red>red/and/yellow</t>" \
           "<t fg=red>lesser < or greater > or both <></t><t>bye</t>"

    if sub:
        text = re.sub(r"/>", "></t>", text)
    expected_output = ['start: ', '<t s=10 B=1>Size 10 bold</t>', '<t siz=6>Size 6\nNew Line </t>',
         '<t u w=bold>Underlined and Bolded\n</t>', '<t it>Italics</t>', '<t>default</t>',
         '<t fam="Courier New" siz=18>Courier 18</t>',
         '<t bitmap=question/>', '<t bitmap=info/>', ' and ', '<t fg=red>red/and/yellow</t>',
         "<t fg=red>lesser < or greater > or both <></t>", '<t>bye</t>', ]
    if sub:
        expected_output = expected_output[:7] + ['<t bitmap=question></t>', '<t bitmap=info></t>'] + expected_output[9:]
    exp_len = len(expected_output)

    def test_patt1(self, i=1):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt2(self, i=2):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt3(self, i=3):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt4(self, i=4):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt5(self, i=5):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt6(self, i=6):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

if __name__ == '__main__':
    unittest.main()
</code>```

答: Looks like I figured out my own problem... By passing flags=re.DOTALL to the re.split() command, I get the expected output. So, patt[4] it is...


问:
Google Ads interrupt the app. Slow down fps
I use AdView mAdView and the last updated libraries.

I placed the AdView into my layout (as shown in the examples):

```<code><com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</code>```

Then I identify it and try to load a new ad in the onCreate() method:

```<code>AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
</code>```

But my layout has some animated objects. This animation is freezing (skipping some frames) while new ad is become visible.

We can't catch the same problem with the disabled Internet (it disables ads and not affect lags).

I'm trying to show the problem with my own record (GIF can't show that completely):

https://www.youtube.com/watch?v=adH2Mn79O7w

How can I remove ads' lags and make the user experience better?

答:
As a workaround which I also have in my apps is setting a layertype:

```<code>mAdView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
</code>```

or

```<code> mAdView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
</code>```

Body:
I use AdView mAdView and the last updated libraries.

I placed the AdView into my layout (as shown in the examples):

<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>

Then I identify it and try to load a new ad in the onCreate() method:

AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);

But my layout has some animated objects. This animation is freezing (skipping some frames) while new ad is become visible.

We can't catch the same problem with the disabled Internet (it disables ads and not affect lags).

I'm trying to show the problem with my own record (GIF can't show that completely):

https://www.youtube.com/watch?v=adH2Mn79O7w

How can I remove ads' lags and make the user experience better?

Body:
As a workaround which I also have in my apps is setting a layertype:

mAdView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

or

 mAdView.setLayerType(View.LAYER_TYPE_HARDWARE, null);


问:
if statement, boolean value
This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:

```<code>        // the new IsDecimal method
    public bool IsDecimal(TextBox textBox, string name)
    {
        //make sure the string only contains numbers and numeric formatting
        string s = textBox.Text;
        int decimalCount = 0;
        bool validDecimal = true;
        foreach (char c in s)
        {
            if (!(
                c == '0' || c == '1' || c == '2' ||   // numeric chars
                c == '3' || c == '4' || c == '5' ||
                c == '6' || c == '7' || c == '8' ||
                c == '9' || c == '.' ||
                c == '$' || c == '%' || c == ',' ||  // formatting chars
                c == ' '
                ))
            {
                validDecimal = false;
                break;
            }
            if (c == '.')
            {
                decimalCount++;
            }
        } // end loop

        if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
        else
        {
            MessageBox.Show(name + " must be a decimal number.",
                "Entry Error");
            textBox.Focus();
            return false;
        }
    }
</code>```

My question is about this if statement and boolean value:

```<code>            if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
</code>```

I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.

答:
Operator Precedence.  This:

```<code>if (validDecimal && decimalCount <= 1)
</code>```

is interpreted as:

```<code>if (validDecimal &&  (decimalCount <= 1))
</code>```

not

```<code>if ((validDecimal && decimalCount) <= 1)
</code>```

In other words, the <= happens before the &&.

Title: if statement, boolean value

Body:
This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:

        // the new IsDecimal method
    public bool IsDecimal(TextBox textBox, string name)
    {
        //make sure the string only contains numbers and numeric formatting
        string s = textBox.Text;
        int decimalCount = 0;
        bool validDecimal = true;
        foreach (char c in s)
        {
            if (!(
                c == '0' || c == '1' || c == '2' ||   // numeric chars
                c == '3' || c == '4' || c == '5' ||
                c == '6' || c == '7' || c == '8' ||
                c == '9' || c == '.' ||
                c == '$' || c == '%' || c == ',' ||  // formatting chars
                c == ' '
                ))
            {
                validDecimal = false;
                break;
            }
            if (c == '.')
            {
                decimalCount++;
            }
        } // end loop

        if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
        else
        {
            MessageBox.Show(name + " must be a decimal number.",
                "Entry Error");
            textBox.Focus();
            return false;
        }
    }

My question is about this if statement and boolean value:

            if (validDecimal && decimalCount <= 1)
        {
            return true;
        }

I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.

Body:
Operator Precedence.  This:

if (validDecimal && decimalCount <= 1)

is interpreted as:

if (validDecimal &&  (decimalCount <= 1))

not

if ((validDecimal && decimalCount) <= 1)

In other words, the <= happens before the &&.


问:
Plotting a function in R where the input is of length 3
I am trying to plot a function I have defined in terms of a parameter x and plot the function over three values of x.  I get an error about the lengths being different.

The length of the function is 1 while x is 3.

```<code>l <- seq(0, 7)
p <- c(5, 2, 9, 4, 4, 1, 1, 0)
loglikGeo <- function(beta){sum(p*log(dgeom(l, beta)))}
beta <- seq(0.01, 0.40, 0.01)
plot(beta, loglikGeo)
</code>```

What is going on?

答:
loglikGeo is defined as a function in your code so you cannot give it as as argument to plot. You need a vector in your y-argument in plot().
To apply a function to each element of a vector and return a vector of function values you can use sapply(vector,function). Replace the last line in your code with:

```<code>loglikGeo_values <- sapply(beta,loglikGeo)
plot(beta, loklikGeo_values)
</code>```

Body:
I am trying to plot a function I have defined in terms of a parameter x and plot the function over three values of x.  I get an error about the lengths being different.

The length of the function is 1 while x is 3.

l <- seq(0, 7)
p <- c(5, 2, 9, 4, 4, 1, 1, 0)
loglikGeo <- function(beta){sum(p*log(dgeom(l, beta)))}
beta <- seq(0.01, 0.40, 0.01)
plot(beta, loglikGeo)

What is going on?

Body:
loglikGeo is defined as a function in your code so you cannot give it as as argument to plot. You need a vector in your y-argument in plot().
To apply a function to each element of a vector and return a vector of function values you can use sapply(vector,function). Replace the last line in your code with:

loglikGeo_values <- sapply(beta,loglikGeo)
plot(beta, loklikGeo_values)


问:
nextjs config merging module export
I want to have both of these module exports, can someone tell me how to merge:

const path = require("path");
const withSass = require('@zeit/next-sass');
const withCSS = require('@zeit/next-css');

module.exports = {
target: "serverless",
webpack(config) {
config.resolve.modules.push(path.resolve("./"));
return config;
}
};

module.exports = withCSS(withSass());```

Tried multiple ways described on stackoverflow and my own ideas unfortunately didn't work. The first module is for absolute paths and the second for bootstrap. If you have general suggestions how to get the result even easier I would appreciate it.

答:
Try this way:</p>

```<code>const withPlugins = require('next-compose-plugins');
const withCss = require('@zeit/next-css');
const withSass = require('@zeit/next-sass');
const withImages = require('next-images');

const nextConfig = {
    ... // webpack configs if you have
    return config;
  },
};

module.exports = withPlugins(
  [
    [withImages],
    [withCss],
    [
      withSass, // if you have other options go this way
      {
        cssModules: true,
        cssLoaderOptions: {
          localIdentName: '[path]___[local]___[hash:base64:5]',
        },
      },
    ],
  ],
  nextConfig,
);
</code>```

Title: nextjs config merging module export

Body:
I want to have both of these module exports, can someone tell me how to merge:

const path = require("path");
const withSass = require('@zeit/next-sass');
const withCSS = require('@zeit/next-css');

module.exports = {
target: "serverless",
webpack(config) {
config.resolve.modules.push(path.resolve("./"));
return config;
}
};

module.exports = withCSS(withSass());

Tried multiple ways described on stackoverflow and my own ideas unfortunately didn't work. The first module is for absolute paths and the second for bootstrap. If you have general suggestions how to get the result even easier I would appreciate it.

Body:
Try this way:

const withPlugins = require('next-compose-plugins');
const withCss = require('@zeit/next-css');
const withSass = require('@zeit/next-sass');
const withImages = require('next-images');

const nextConfig = {
    ... // webpack configs if you have
    return config;
  },
};

module.exports = withPlugins(
  [
    [withImages],
    [withCss],
    [
      withSass, // if you have other options go this way
      {
        cssModules: true,
        cssLoaderOptions: {
          localIdentName: '[path]___[local]___[hash:base64:5]',
        },
      },
    ],
  ],
  nextConfig,
);


问:
Adjust output based on the count of a substring within a string in a 2d char array
I'm reading a bunch of lines from a file and trying to print each line that contains a certain set of keywords. Right now my code just looks for the first occurrence of a keyword within a line, if it finds one, it will print that keyword and that line with its line number. But I'm trying to make it so that if the line contains more than one occurrence of the keyword, then in the printed output, there should be a star character next to the line number. I've tried many different approaches and nothing seems to work. Here's my code:

```<code>for(i = 0; i < wordCount_keyword; i++) {
    for(j = 0; j <= lineCount; j++) {
        if(strstr(inputLines[j], keywords[i]) != NULL) {
            printf("%-*s %s (%d)\n", max_length + 1, keywords_upper[i], inputLines[j], j+1);
        }
    }
}
</code>```

Here's my current output:

```<code>CAT       the fish a dog cat dog rabbit (1)
CAT       the fish and cat  (2)
DOG       the fish a dog cat dog rabbit (1)
ELEPHANT  a rabbit or elephant (3)
FISH      the fish a dog cat dog rabbit (1)
FISH      the fish and cat  (2)
RABBIT    the fish a dog cat dog rabbit (1)
RABBIT    a rabbit or elephant (3)
</code>```

Here's the ideally correct output I'm aiming for:

```<code>CAT       the fish a dog cat dog rabbit (1)
CAT       the fish and cat  (2)
DOG       the fish a dog cat dog rabbit (1*)
ELEPHANT  a rabbit or elephant (3)
FISH      the fish a dog cat dog rabbit (1)
FISH      the fish and cat  (2)
RABBIT    the fish a dog cat dog rabbit (1)
RABBIT    a rabbit or elephant (3)
</code>```

Notice the difference being the star next to the 1 in paranthesis at the end of the 3rd line.
What's the right way to do this?

答:
As there are no build-in functions in c to count the number of occurrences of a word in a string you need to write one. Let's say the definition of the function is "getWordOccurances(char * str, char * toSearch)". Then the following code will solve your problem.

```<code>for(i = 0; i < wordCount_keyword; i++) {
   for(j = 0; j <= lineCount; j++) {
       int count = getWordOccurances(inputLines[j], keywords[i]);
       if(count > 0) {
           printf("%-*s %s (%d", max_length + 1, keywords_upper[i], inputLines[j], j+1);
           if(count > 1) printf("*)\n");
           else printf(")\n");
       }
   }
}
</code>```

And the getWordOccurances(char * str, char * toSearch) function may look like following:

```<code>int countOccurrences(char * str, char * toSearch){
    int i, j, found, count;
    int stringLen, searchLen;

    stringLen = strlen(str);      // length of string
    searchLen = strlen(toSearch); // length of word to be searched

    count = 0;

    for(i=0; i <= stringLen-searchLen; i++) {
        /* Match word with string */
        found = 1;
        for(j=0; j<searchLen; j++) {
            if(str[i + j] != toSearch[j]) {
                found = 0;
                break;
            }
        }

        if(found == 1) count++;
    }

    return count;
}
</code>```

Let me know if you don't understand any part of the program. Happy coding!

Body:
I'm reading a bunch of lines from a file and trying to print each line that contains a certain set of keywords. Right now my code just looks for the first occurrence of a keyword within a line, if it finds one, it will print that keyword and that line with its line number. But I'm trying to make it so that if the line contains more than one occurrence of the keyword, then in the printed output, there should be a star character next to the line number. I've tried many different approaches and nothing seems to work. Here's my code:

for(i = 0; i < wordCount_keyword; i++) {
    for(j = 0; j <= lineCount; j++) {
        if(strstr(inputLines[j], keywords[i]) != NULL) {
            printf("%-*s %s (%d)\n", max_length + 1, keywords_upper[i], inputLines[j], j+1);
        }
    }
}

Here's my current output:

CAT       the fish a dog cat dog rabbit (1)
CAT       the fish and cat  (2)
DOG       the fish a dog cat dog rabbit (1)
ELEPHANT  a rabbit or elephant (3)
FISH      the fish a dog cat dog rabbit (1)
FISH      the fish and cat  (2)
RABBIT    the fish a dog cat dog rabbit (1)
RABBIT    a rabbit or elephant (3)

Here's the ideally correct output I'm aiming for:

CAT       the fish a dog cat dog rabbit (1)
CAT       the fish and cat  (2)
DOG       the fish a dog cat dog rabbit (1*)
ELEPHANT  a rabbit or elephant (3)
FISH      the fish a dog cat dog rabbit (1)
FISH      the fish and cat  (2)
RABBIT    the fish a dog cat dog rabbit (1)
RABBIT    a rabbit or elephant (3)

Notice the difference being the star next to the 1 in paranthesis at the end of the 3rd line.
What's the right way to do this?

Body:
As there are no build-in functions in c to count the number of occurrences of a word in a string you need to write one. Let's say the definition of the function is "getWordOccurances(char * str, char * toSearch)". Then the following code will solve your problem.

for(i = 0; i < wordCount_keyword; i++) {
   for(j = 0; j <= lineCount; j++) {
       int count = getWordOccurances(inputLines[j], keywords[i]);
       if(count > 0) {
           printf("%-*s %s (%d", max_length + 1, keywords_upper[i], inputLines[j], j+1);
           if(count > 1) printf("*)\n");
           else printf(")\n");
       }
   }
}

And the getWordOccurances(char * str, char * toSearch) function may look like following:

int countOccurrences(char * str, char * toSearch){
    int i, j, found, count;
    int stringLen, searchLen;

    stringLen = strlen(str);      // length of string
    searchLen = strlen(toSearch); // length of word to be searched

    count = 0;

    for(i=0; i <= stringLen-searchLen; i++) {
        /* Match word with string */
        found = 1;
        for(j=0; j<searchLen; j++) {
            if(str[i + j] != toSearch[j]) {
                found = 0;
                break;
            }
        }

        if(found == 1) count++;
    }

    return count;
}

Let me know if you don't understand any part of the program. Happy coding!


问:
Validate e-mail address when pressing a button
I'm trying to make a basic login screen. However, I'm struggling with the e-mail validation.

Every time I press a button, I want to make sure that the user inputs the correct e-mail format, or give them a small alert under the e-mail TextInput if they write something other than a valid e-mail (this alert will be hidden by default.). However, when I try, it always gives me this error (regardless of the user input):

```<code>undefined is not an object (evaluating 'this.state.username')
</code>```

This is my code so far

```<code>class HomeScreen extends Component {
 state = { username: null, password: null }
 show = false;

 _validar = (text) => {
  let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;

  if(reg.test(text) === false) {
    return false;
  } else {
    return true;
  }
 }

 _onSubmit() {
  if(this._validar(this.state.username) == true) {
    const { username, password } = this.state;
  } else {
    this.show = true;
  }
 }

 render() {
  return (
   <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
   enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
    <View style={styles.logo}>
     <Image source = {logo} style={styles.img}/>
     <Text style={styles.textLogoPrimary}>Neuron App</Text>
     <Text style={styles.textLogoSecondary}>Test</Text>
    </View>

    <View style={styles.formElement}>
     <Text style={styles.formText}>Correo Electrónico</Text>
     <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
     style={styles.formInput} />
     {this.state.show ? (
       <Text style={styles.textAlert}>Correo Electrónico no valido.</Text>
     ) : null}
    </View>

    <View style={styles.formElement}>
     <Text style={styles.formText}>Contraseña</Text>
     <TextInput style={styles.formInput} onChangeText={value => this.setState({ password: value })} secureTextEntry={true}/>
    </View>

    <View style={styles.buttonView}>
     <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
      <Text style={styles.buttonText}>Iniciar</Text>
     </TouchableOpacity>
    </View>
  </KeyboardAwareScrollView>
 );
}}
</code>```

答:
This error is raised because you are accessing the this.state.username before it is assigned. I would recommend you to change the initial state value of username into a string, as it ends up being a string, instead of null.

```<code>state = { username: '', password: '' };
</code>```

null can be avoided in string case, by just assigning it '' an empty string. If you are to evaluate it logically, it would give you same result as null as it is 'falsy'.

Body:
I'm trying to make a basic login screen. However, I'm struggling with the e-mail validation.

Every time I press a button, I want to make sure that the user inputs the correct e-mail format, or give them a small alert under the e-mail TextInput if they write something other than a valid e-mail (this alert will be hidden by default.). However, when I try, it always gives me this error (regardless of the user input):

undefined is not an object (evaluating 'this.state.username')

This is my code so far

class HomeScreen extends Component {
 state = { username: null, password: null }
 show = false;

 _validar = (text) => {
  let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;

  if(reg.test(text) === false) {
    return false;
  } else {
    return true;
  }
 }

 _onSubmit() {
  if(this._validar(this.state.username) == true) {
    const { username, password } = this.state;
  } else {
    this.show = true;
  }
 }

 render() {
  return (
   <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
   enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
    <View style={styles.logo}>
     <Image source = {logo} style={styles.img}/>
     <Text style={styles.textLogoPrimary}>Neuron App</Text>
     <Text style={styles.textLogoSecondary}>Test</Text>
    </View>

    <View style={styles.formElement}>
     <Text style={styles.formText}>Correo Electrónico</Text>
     <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
     style={styles.formInput} />
     {this.state.show ? (
       <Text style={styles.textAlert}>Correo Electrónico no valido.</Text>
     ) : null}
    </View>

    <View style={styles.formElement}>
     <Text style={styles.formText}>Contraseña</Text>
     <TextInput style={styles.formInput} onChangeText={value => this.setState({ password: value })} secureTextEntry={true}/>
    </View>

    <View style={styles.buttonView}>
     <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
      <Text style={styles.buttonText}>Iniciar</Text>
     </TouchableOpacity>
    </View>
  </KeyboardAwareScrollView>
 );
}}

Body:
This error is raised because you are accessing the this.state.username before it is assigned. I would recommend you to change the initial state value of username into a string, as it ends up being a string, instead of null.

state = { username: '', password: '' };

null can be avoided in string case, by just assigning it '' an empty string. If you are to evaluate it logically, it would give you same result as null as it is 'falsy'.


问:
setAlarmClock() fires too late in doze mode
I have soooo much trouble getting my radio alarm clock working as intended and I have read a lot of threads here about that topic, but unfortunatley none did help me.

```<code>AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent penInt = PendingIntent.getBroadcast(this, intentId, intent, 0);
</code>```

This method of distinction between the API levels I found here on stackoverflow and put it inside my calcNextAlarm() function (plus some log messages for debugging) to set the alarm correctly no matter what API is being used on the device:

```<code>// problems in doze mode api 23+
if (Build.VERSION.SDK_INT >= 23) {
    if (testMode) Log.d("Ben", "setAlarmClock() - API 23+");
    am.setAlarmClock(new AlarmManager.AlarmClockInfo(alarmTimeInMillis, penInt), penInt);
}

else if (Build.VERSION.SDK_INT >= 19) {
// Wakes up the device in Idle Mode
    if (testMode) Log.d("Ben", "setExact() - API >= 19 && API < 23");
    am.setExact(AlarmManager.RTC_WAKEUP, alarmTimeInMillis, penInt);
}
// Old APIs
else {
    if (testMode) Log.d("Ben", "set() - API < 19");
    am.set(AlarmManager.RTC_WAKEUP, alarmTimeInMillis, penInt);
}
</code>```

According to the Log.d messages I can see that, on my Android 7.1 Device the first method setAlarmClock() is being executed to set the alarm in the Receiver.

I am getting really desperate after 3 weeks of unsuccessful tests and coding - my alarm today got off 4 minutes too late again - this should never happen, according to the doze mode training page:

Alarms set with setAlarmClock() continue to fire normally — the system exits Doze shortly before those alarms fire.

On my 7.1 phone the alarm will even be 20 seconds to 1:40 mins late when I set the alarm to "now +5 or 6" minutes. Could anyone advise me how to really ALWAYS get the alarm off perfectly in time?

答:
The documentation states that:

If you need to set alarms that fire while in Doze, use
  setAndAllowWhileIdle() or setExactAndAllowWhileIdle().

Alarms set with setAlarmClock() continue to fire normally — the system
  exits Doze shortly before those alarms fire.

In "Adapt your app to Doze" section it also says that:

Note: Neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle()
  can fire alarms more than once per 9 minutes, per app.

The documentation for setExactAndAllowWhileIdle says that:

Unlike other alarms, the system is free to reschedule this type of
  alarm to happen out of order with any other alarms, even those from
  the same app. This will clearly happen when the device is idle (since
  this alarm can go off while idle, when any other alarms from the app
  will be held until later), but may also happen even when not idle.
  Note that the OS will allow itself more flexibility for scheduling
  these alarms than regular exact alarms, since the application has
  opted into this behavior. When the device is idle it may take even
  more liberties with scheduling in order to optimize for battery life.

So setExactAndAllowWhileIdle is not guaranteeing the exact execution, and setAlarmClock is more exact (according to documentation).

Body:
I have soooo much trouble getting my radio alarm clock working as intended and I have read a lot of threads here about that topic, but unfortunatley none did help me.

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent penInt = PendingIntent.getBroadcast(this, intentId, intent, 0);

This method of distinction between the API levels I found here on stackoverflow and put it inside my calcNextAlarm() function (plus some log messages for debugging) to set the alarm correctly no matter what API is being used on the device:

// problems in doze mode api 23+
if (Build.VERSION.SDK_INT >= 23) {
    if (testMode) Log.d("Ben", "setAlarmClock() - API 23+");
    am.setAlarmClock(new AlarmManager.AlarmClockInfo(alarmTimeInMillis, penInt), penInt);
}

else if (Build.VERSION.SDK_INT >= 19) {
// Wakes up the device in Idle Mode
    if (testMode) Log.d("Ben", "setExact() - API >= 19 && API < 23");
    am.setExact(AlarmManager.RTC_WAKEUP, alarmTimeInMillis, penInt);
}
// Old APIs
else {
    if (testMode) Log.d("Ben", "set() - API < 19");
    am.set(AlarmManager.RTC_WAKEUP, alarmTimeInMillis, penInt);
}

According to the Log.d messages I can see that, on my Android 7.1 Device the first method setAlarmClock() is being executed to set the alarm in the Receiver.

I am getting really desperate after 3 weeks of unsuccessful tests and coding - my alarm today got off 4 minutes too late again - this should never happen, according to the doze mode training page:

Alarms set with setAlarmClock() continue to fire normally — the system exits Doze shortly before those alarms fire.

On my 7.1 phone the alarm will even be 20 seconds to 1:40 mins late when I set the alarm to "now +5 or 6" minutes. Could anyone advise me how to really ALWAYS get the alarm off perfectly in time?


问:
How to change the height of a
?
I have a big paragraph of text that is divided into subparagraphs with
's:

```<code><p>
  Blah blah blah.
  <br/>
  Blah blah blah. Blah blah blah. Blah blah blah.
  <br/>
  Blah blah blah.
</p>
</code>```

I want to widen the gap between these subparagraphs, like there is two
's or something like that. I know that the right way to do this is to use

, but right now I cannot change this layout, so I am looking for CSS-only solution.

I've tried setting
's line-height and height with display: block, I also Googled and Stack Overflow-ed briefly, but did not find any solution. Is this even possible without changing the layout?

答:
Another way is to use an HR. But, and here's the cunning part, make it invisible.

Thus:

```<code><hr style="height:30pt; visibility:hidden;" />
</code>```

To make a cleaner BR break simulated using the HR: Btw works in all browsers!!

```<code>{ height:2px; visibility:hidden; margin-bottom:-1px; }
</code>```

Title: How to change the height of a <br>?

Body:
I have a big paragraph of text that is divided into subparagraphs with
's:

  Blah blah blah.

  Blah blah blah. Blah blah blah. Blah blah blah.

  Blah blah blah.

I want to widen the gap between these subparagraphs, like there is two
's or something like that. I know that the right way to do this is to use

, but right now I cannot change this layout, so I am looking for CSS-only solution.

I've tried setting
's line-height and height with display: block, I also Googled and Stack Overflow-ed briefly, but did not find any solution. Is this even possible without changing the layout?

Body:
Another way is to use an HR. But, and here's the cunning part, make it invisible.

Thus:

<hr style="height:30pt; visibility:hidden;" />

To make a cleaner BR break simulated using the HR: Btw works in all browsers!!

{ height:2px; visibility:hidden; margin-bottom:-1px; }


问:
Query with switch function requests parameter value
Background: Excel worksheet as front end to an Access database.  Excel contains VBA code and uses ADODB to move values into and out of the tables in Access.

One column is a composite value which describes a complex priority relationship.  One digit for priority level (1-6), one letter for more granular level (A-C), and a type of project (Safety, Security, Enviro, etc.)  The values look like "2B - Maint.", "2A - ProcCntl"

I need to sort the results of a select * query in different ways.  Sometimes with the typical Alpha sort which would list 1A values before 1B before 4C.  Other times I need to sort all the Safety as a group, Maint. as another, etc. A simple alpha sort on the project type doesn't work because the manager wants a specific order.

I am using the Switch function to assign the order.  I have found a couple of ways to make this work in Access but they all ask for a parameter value when I run the query. Entering a blank value gets the desired result.  Moving the query into the VBA of Excel returns an error complaining of an empty parameter.

Here is one of the "working" queries:

SELECT *, Mid([Priority],6,2) AS ProjClass,
  Switch(ProjClass="Sa",1,ProjClass="En",2,ProjClass="Se",3,ProjClass="6S",4,ProjClass="Qu",5,ProjClass="Pr",6,ProjClass="Ma",7,ProjClass="Bu",8)
  AS [FirstSort]

FROM tblProjects

ORDER BY [FirstSort] ASC, [Priority] ASC;

When I run this through the VBA I get

Run-time error "No value given for one or more required parameters."

When I run it in Access a "Enter Parameter Value" dialog opens asking for FirstSort. I click through and see the result is correctly sorted.

The root question: Why is Access seeing FirstSort as a parameter and not a field name?

I think I need to understand that before I can fix the VBA issue.

答:
More research has revealed yet another Access quirk:  The problem is that MS Access does not allow AS clauses in the ORDER BY clause.

So a little experimentation lead me to change the ORDER BY clause to ORDER BY 3 ASC, [Priority] ASC;

I chose the three because it is the third field expression in the query.  It works but it would be great if someone could clarify the specific rule that makes it work.

Hat tip: Why does this query require a parameter?  and onedaywhen's answer.


问:
How to track dark mode with Komito Analytics?
Does Komito Analytics support tracking of users' preferred color scheme (especially dark mode)?</p>

答:
Preferred color scheme tracking is enabled by default in Komito Analytics' initial configuration. To disable it, set the configuration property trackColorScheme to 0.

Check for more information at https://komito.net/posts/track-color-scheme/


问:
How to checked multiple checkbox over loop
In One Array I am getting array like :

```<code>    ['1','2','3','4','5','6']
</code>```

And In another array i Am getting array like :

```<code>    ['1','6']
</code>```

In template i am doing like :

```<code>    <div class="col-md-10">
      {% if edit_data.features %}
    {% for feature in edit_data.feature %}
    {% for features in edit_data.features %}
    {% if feature.id == features.feature_id %}
        checked='checked'
    {%endif%}
    {%endfor%}
    <input type="checkbox" name="features" value={{feature.id}} {{checked}}> {{feature.name}}
    {%endfor%}
    {%endif%}
    </div>
</code>```

After This i am getting Like:

How Can i select the checkbox over the loop i am not able to create variable inside if condition. i am newbe please let me now how can i make checkbox to be selected

```<code>  [1]: https://i.stack.imgur.com/LzVV4.png
</code>```

After Your Solution i am getting Like This:

https://i.stack.imgur.com/7nZJj.png

答:
```<code>    <div class="col-md-10">
      {% if edit_data.features %}
        {% for feature in edit_data.feature %}
            {% with ns=namespace(found=false) %}
            {% for features in edit_data.features %}
                {% if feature.id == features.feature_id %}
                    {% with ns.found=true %}
                {% endif %}
            {%endfor%}
        {% if ns.found == true %}
        <input type="checkbox" name="features" value={{feature.id}}  checked> {{feature.name}}</option>
        {% else %}
           <input type="checkbox" name="features" value={{feature.id}} > {{feature.name}}</option>
        {% endif %}
        {%endfor%}
      {%endif%}
    </div>
</code>```

Body:
In One Array I am getting array like :

    ['1','2','3','4','5','6']

And In another array i Am getting array like :

    ['1','6']

In template i am doing like :

      {% if edit_data.features %}
    {% for feature in edit_data.feature %}
    {% for features in edit_data.features %}
    {% if feature.id == features.feature_id %}
        checked='checked'
    {%endif%}
    {%endfor%}
    <input type="checkbox" name="features" value={{feature.id}} {{checked}}> {{feature.name}}
    {%endfor%}
    {%endif%}

After This i am getting Like:

How Can i select the checkbox over the loop i am not able to create variable inside if condition. i am newbe please let me now how can i make checkbox to be selected

  [1]: https://i.stack.imgur.com/LzVV4.png

After Your Solution i am getting Like This:

https://i.stack.imgur.com/7nZJj.png


答:
You can write

```<code>if (validDecimal == true && decimalCount <= 1)
</code>```

but it is equivalent to the shorthand way

```<code>if (validDecimal && decimalCount <= 1)
</code>```

When the type is a bool no need to again use

== true

as it is assumed

Title: if statement, boolean value

Body:
You can write

if (validDecimal == true && decimalCount <= 1)

but it is equivalent to the shorthand way

if (validDecimal && decimalCount <= 1)

When the type is a bool no need to again use

== true

as it is assumed


问:
who is the best theme load time speed in WordPress site?
friend i have junior developer and i have create site but site home page is load time is 15 second. how can use i use best theme in my site plz ask best theme...</p>

答:
Here are the 11 ways to speed up WordPress:

Choose a better web hosting provider

Use a lightweight WordPress theme/framework

Reduce image sizes

Minify JS and CSS files

Use advanced caching mechanisms with a caching plugin

Use a CDN

Enable GZIP compression

Cleanup WordPress database

Deactivate or uninstall plugins

Keep external scripts to a minimum

Disable pingbacks and trackbacks


问:
Value Error: Format does not match while converting string to datime.date?
I am converting the following string 2020-02-14 20:56:00 to datetime.date format. But am getting the following error:

```<code>ValueError: time data '2020-02-14 20:56:00' does not match format '%Y/%m/%d %H:%M:%S'

</code>```

Here is the code I am using:

from datetime import datetime
date_and_time = '2020-02-14 20:56:00'
date_and_time = datetime.strptime(date_and_time, '%Y/%m/%d %H:%M:%S')

```

What am I doing wrong here?

答:
The ValueError specifies the use of incorrect format string.

To resolve this error you have to replace / with -.
 Here is correct code:

```<code>from datetime import datetime
date_and_time = '2020-02-14 20:56:00'
date_and_time = datetime.strptime(date_and_time, '%Y-%m-%d %H:%M:%S')
</code>```

Hope it helps you:)

Body:
I am converting the following string 2020-02-14 20:56:00 to datetime.date format. But am getting the following error:

ValueError: time data '2020-02-14 20:56:00' does not match format '%Y/%m/%d %H:%M:%S'

Here is the code I am using:

from datetime import datetime
date_and_time = '2020-02-14 20:56:00'
date_and_time = datetime.strptime(date_and_time, '%Y/%m/%d %H:%M:%S')

What am I doing wrong here?

Body:
The ValueError specifies the use of incorrect format string.

To resolve this error you have to replace / with -.
 Here is correct code:

from datetime import datetime
date_and_time = '2020-02-14 20:56:00'
date_and_time = datetime.strptime(date_and_time, '%Y-%m-%d %H:%M:%S')

Hope it helps you:)


问:
deletion of one past end element in map and segmentation fault
When I tried to delete end() element from the map using erase I got no issues in compilation but on later printing the map.begin() key/mapped_value I got segmentation fault:

```<code> //RELEVANT HEADERS

 //main function starts

 map<int, string> m;
 m[0] = "hello";
 m[1] = "Mello";

 m.erase(m.end());

 cout<<(m.begin())->second;
</code>```

OUTPUT: Segmentation fault

My question is: on trying to delete the end() element nothing would've happened to the structure of map m as end refers to one past the real end element, so what really triggered that segmentation fault as the memory structure still holds same as before deletion.

答:
As you can see in e.g. cppreference's documentation on std::map::erase, the iterator passed to it must be a valid iterator into the container that erase is called on and it has to be dereferencable.

The end() iterator is not dereferencable. Therefore passing it to erase violates erase's precondition, which means that your program has undefined behavior.

Undefined behavior means that there is no guarantee on what the program will do (or whether it will compile at all) and therefore it is entirely possible that it seems to work until somewhere later in your program and/or that you get a segmentation fault. These are possible manifestations of undefined behavior.

Practically speaking, the erase call probably dereferences some pointer contained in the iterator that doesn't point to any element and that triggers the segmentation fault. But that is an implementation detail dependent on your standard library implementation and it doesn't really matter anyway, as the rules are given by the language and described above.

Body:
When I tried to delete end() element from the map using erase I got no issues in compilation but on later printing the map.begin() key/mapped_value I got segmentation fault:

 //RELEVANT HEADERS

 //main function starts

 map<int, string> m;
 m[0] = "hello";
 m[1] = "Mello";

 m.erase(m.end());

 cout<<(m.begin())->second;

OUTPUT: Segmentation fault

My question is: on trying to delete the end() element nothing would've happened to the structure of map m as end refers to one past the real end element, so what really triggered that segmentation fault as the memory structure still holds same as before deletion.


问:
How to add a force to an object in Unity not relative to the objects rotation but relative to the game coordinates?
I am creating a 2d game and would like to have an object move up. I don't want it to move up relative to the object, but up relative to the game coordinates. I am currently using Rigidbody.AddForce(). Does anyone know of a way to do this?</p>

答:
Do You want it to AddForce Relative to Local space or world space?, If you want it to move in local space use AddRelativeForce(..), if you want to move based on world use AddForce(..)

Check Out Doc


问:
Wrong conversion of date difference to numeric In Python
I have a dataset:

```<code>     A                               B
2019-06-19 09:18:00         2019-06-22 09:14:37
2019-06-27 22:35:00         2019-06-27 22:04:20
2019-06-26 19:50:00         2019-06-26 21:18:45
</code>```

where it represent the datetime for both column.

I wanted to construct a columns C that shows the difference in date time as hours in decimal and apply the following transformation.

```<code>raw_data['C']= raw_data['B'] - raw_data['A']
raw_data['C']= round(raw_data['C']/np.timedelta64(1,'h'),2)
</code>```

and I managed to get the correct value calculation:

```<code>  C               A                         B
71.94    2019-06-22 09:14:37      2019-06-19 09:18:00
-0.51    2019-06-27 22:04:20      2019-06-27 22:35:00
1.48     2019-06-26 21:18:45      2019-06-26 19:50:00
</code>```

However, when I tried to create a categorical variable D, where it will be 'Pass' if column C is smaller than 3, I have the wrong conversion for the third row. I.e. it should be 'Pass' value.

```<code>raw_data['D']= "Fail"
raw_data.loc[raw_data['C']<3, 'D']= 'Pass'

  D        C
71.94    Fail
-0.51    Pass
1.48     Fail
</code>```

May I know what could be the possible reasons for the failed conversion? Thank you!

答:
Tested and for me working correct.

Alternative solution with Series.dt.total_seconds, divide by Series.div and Series.round, last for new column is used numpy.where:

```<code>raw_data['C']= raw_data['B'] - raw_data['A']
raw_data['C']=  raw_data['C'].dt.total_seconds().div(3600).round(2)

raw_data['D']= np.where(raw_data['C']<3,'Pass',"Fail")
print (raw_data)
                    A                   B      C     D
0 2019-06-19 09:18:00 2019-06-22 09:14:37  71.94  Fail
1 2019-06-27 22:35:00 2019-06-27 22:04:20  -0.51  Pass
2 2019-06-26 19:50:00 2019-06-26 21:18:45   1.48  Pass
</code>```

Body:
I have a dataset:

     A                               B
2019-06-19 09:18:00         2019-06-22 09:14:37
2019-06-27 22:35:00         2019-06-27 22:04:20
2019-06-26 19:50:00         2019-06-26 21:18:45

where it represent the datetime for both column.

I wanted to construct a columns C that shows the difference in date time as hours in decimal and apply the following transformation.

raw_data['C']= raw_data['B'] - raw_data['A']
raw_data['C']= round(raw_data['C']/np.timedelta64(1,'h'),2)

and I managed to get the correct value calculation:

  C               A                         B
71.94    2019-06-22 09:14:37      2019-06-19 09:18:00
-0.51    2019-06-27 22:04:20      2019-06-27 22:35:00
1.48     2019-06-26 21:18:45      2019-06-26 19:50:00

However, when I tried to create a categorical variable D, where it will be 'Pass' if column C is smaller than 3, I have the wrong conversion for the third row. I.e. it should be 'Pass' value.

raw_data['D']= "Fail"
raw_data.loc[raw_data['C']<3, 'D']= 'Pass'

  D        C
71.94    Fail
-0.51    Pass
1.48     Fail

May I know what could be the possible reasons for the failed conversion? Thank you!

Body:
Tested and for me working correct.

Alternative solution with Series.dt.total_seconds, divide by Series.div and Series.round, last for new column is used numpy.where:

raw_data['C']= raw_data['B'] - raw_data['A']
raw_data['C']=  raw_data['C'].dt.total_seconds().div(3600).round(2)

raw_data['D']= np.where(raw_data['C']<3,'Pass',"Fail")
print (raw_data)
                    A                   B      C     D
0 2019-06-19 09:18:00 2019-06-22 09:14:37  71.94  Fail
1 2019-06-27 22:35:00 2019-06-27 22:04:20  -0.51  Pass
2 2019-06-26 19:50:00 2019-06-26 21:18:45   1.48  Pass


问:
How to Implement Video Ads like YouTube and Netflix that shows before playing the actual video
**I am trying to make a video streaming site programmed in

PHP or ASP.NET

I am trying to recreate the senerio that YouTube show.
ie. When someone clicks the video it shows a video ad in my video player.
**

Problem: I want to show then the video promotion ad without actually adding the video to all 20k+ videos and let there be 4 video promo named 1/2/3/4.mp4 respectively so it should be random that the video is played.

答:
The easiest way to accomplish this is to use WebM byte stream format which makes it easy for you to have the browser download the video in chunks (these are called WebM clusters). As the browser downloads one chunk it sends back a token to the server requesting the next chunk (based on timestamps in the video stream). The server can then make the determination to stop sending the video stream of the main feature and instead send a video stream for the advertisement. It will normally update the browser with new tokens upon each request to ensure that tokens can't be reused to obtain new chunks without the server first making the determination if an advertisement should be played mid-stream or not. This same mechanism is what most video streaming sites use to control when ads can be played during the video stream.

WebM is a digital multimedia container file format promoted by the open-source WebM Project. It comprises a subset of the Matroska multimedia container format.

So to walk through a practical example of this technique let's assume we have a video file that's 10 minutes long. What we aim to do is chop up the video into smaller chunks (let's say about 30 seconds each), but only in a logical way. The video file remains intact physically. When the page is first loaded the server will supply a non-reusable token (like a nonce) that can be used to retrieve the first chunk of the video (the first 30 seconds). So the browser fires off an AJAX request along with the token and the server will respond with a 30 second chunk of the video and a renewed token. This process will recur over and over again until we reach the end of the video. If at any time the server decides we need to show an ad then instead of sending along the next 30 seconds of video we send along instead the ad. To the end-user it appears as though the video and ad are all playing in the same video.

The way the server is keeping track of how much of the video the user has watched is based on the tokens the user sends back in the next request. This is how you can arbitrarily place ads in the video based on video length.


问:
Unable to find field "username" that is not disabled (Capybara::ElementNotFound)
I'm trying to test a simple login form using cucumber / rspec / capybara. But I'm having trouble detecting elements on the page and doing any sort of test.

Unable to find field "username" that is not disabled (Capybara::ElementNotFound)

Feature File

Feature: Login

    Scenario: correct login credentials
        Given I am on the admin_login page
        When I fill in "username" with "thomas"```
</div>
</div>
</p>

<p><strong>ENV</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-html lang-html prettyprint-override"><code>require 'capybara'
require 'rspec'
require 'capybara/cucumber'
require 'rack'
require_relative '../../config'

ENV['RACK_ENV'] = 'test'

Capybara.ignore_hidden_elements = false
Capybara.app = Sinatra::Application

class Sinatra::ApplicationWorld
    include RSpec::Expectations
    include RSpec::Matchers
    include Capybara::DSL
end

World do
    Sinatra::ApplicationWorld.new
end</code>```

WEB STEP

When /^(?:|I )fill in "([^\"]*)" with "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, value, selector|
  with_scope(selector) do
    fill_in(field,visible: false, :with => value)
  end
end```
</div>
</div>
</p>

<p><strong>HTML</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-html lang-html prettyprint-override"><code><div class="container">
            <div class="row">
                <div class="col-md-4 col-md-offset-4">
                    <div class="login-panel panel panel-default">
                        <div class="panel-heading">
                            <h3 class="panel-title">Please Sign In To Pied Piper</h3>
                        </div>
                        <div class="panel-body">
                            <form role="form" action="/admin/login" method="post" label="form">
                                <fieldset label ="form" >
                                    <div class="form-group">

                                        <input label="username" class="form-control" placeholder="username" name="username" id="username" type="text" value="<%= params[:username] %>" autofocus>
                                    </div>
                                    <div class="form-group">
                                        <input class="form-control" placeholder="Password" name="password" type="password" value="<%= params[:password]%>">
                                    </div>
                                    <div class="checkbox">
                                        <label>
                                            <input name="remember" type="checkbox" value="Remember Me">Remember Me
                                        </label>
                                    </div>
                                    <button type="submit">Login</button>
                                    <button>Return to Main Site</button>
                                </fieldset>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div></code>```

答:
I got the same problem with my rails appliction and the way I solved it was by giving an id to that field</p>

```<code>    <%= f.text_field :name, class: 'form-control',id:"name" %>
</code>```

Body:
I'm trying to test a simple login form using cucumber / rspec / capybara. But I'm having trouble detecting elements on the page and doing any sort of test.

Unable to find field "username" that is not disabled (Capybara::ElementNotFound)

Feature File

Feature: Login

    Scenario: correct login credentials
        Given I am on the admin_login page
        When I fill in "username" with "thomas"

ENV

require 'capybara'
require 'rspec'
require 'capybara/cucumber'
require 'rack'
require_relative '../../config'

ENV['RACK_ENV'] = 'test'

Capybara.ignore_hidden_elements = false
Capybara.app = Sinatra::Application

class Sinatra::ApplicationWorld
    include RSpec::Expectations
    include RSpec::Matchers
    include Capybara::DSL
end

World do
    Sinatra::ApplicationWorld.new
end

WEB STEP

When /^(?:|I )fill in "([^\"]*)" with "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, value, selector|
  with_scope(selector) do
    fill_in(field,visible: false, :with => value)
  end
end

HTML

Please Sign In To Pied Piper

                            <form role="form" action="/admin/login" method="post" label="form">
                                <fieldset label ="form" >

                                        <input label="username" class="form-control" placeholder="username" name="username" id="username" type="text" value="<%= params[:username] %>" autofocus>

                                        <input class="form-control" placeholder="Password" name="password" type="password" value="<%= params[:password]%>">

                                            <input name="remember" type="checkbox" value="Remember Me">Remember Me

                                    <button type="submit">Login</button>
                                    <button>Return to Main Site</button>
                                </fieldset>
                            </form>

Body:
I got the same problem with my rails appliction and the way I solved it was by giving an id to that field

    <%= f.text_field :name, class: 'form-control',id:"name" %>


问:
How to run jQuery code for devices with a viewport of less than 1000px and only on the homepage
I have the following jQuery code which I need to run only in the homepage as well as for devices with a viewport of less than 1000px. I have tried with the if statements but I keep ruining the code. I am stuck from this point on. Here is the code I have:</p>

```<code>jQuery(document).ready(function($){
 $(window).on('scroll', function(){
  var y = $(window).scrollTop();
   if( y > 0 ){
   $('#top').fadeIn();
   $('#header-space').fadeIn(); }
 else {
   $('#top').fadeOut();
   $('#header-space').fadeOut(); }
 });
 });
</code>```

答:
Try this:</p>

```<code>jQuery(document).ready(function($) {
    $(window).on('scroll resize', function() { // fired on scroll or resize
        var ww = $(window).width(); // get window width
        var y = $(window).scrollTop();
        if( ww < 1000 && $('body').hasClass('home') ){
            if(y > 0) {
                $('#top').fadeIn();
                $('#header-space').fadeIn();
            } else {
                $('#top').fadeOut();
                $('#header-space').fadeOut();
            }
        }

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

Body:
I have the following jQuery code which I need to run only in the homepage as well as for devices with a viewport of less than 1000px. I have tried with the if statements but I keep ruining the code. I am stuck from this point on. Here is the code I have:

jQuery(document).ready(function($){
 $(window).on('scroll', function(){
  var y = $(window).scrollTop();
   if( y > 0 ){
   $('#top').fadeIn();
   $('#header-space').fadeIn(); }
 else {
   $('#top').fadeOut();
   $('#header-space').fadeOut(); }
 });
 });

Body:
Try this:

jQuery(document).ready(function($) {
    $(window).on('scroll resize', function() { // fired on scroll or resize
        var ww = $(window).width(); // get window width
        var y = $(window).scrollTop();
        if( ww < 1000 && $('body').hasClass('home') ){
            if(y > 0) {
                $('#top').fadeIn();
                $('#header-space').fadeIn();
            } else {
                $('#top').fadeOut();
                $('#header-space').fadeOut();
            }
        }

    });
});