问:
importing jquery plugin is not work in react app
I try to import a jquery flexslider plugin in Slider component. But it's give me error " $(this.el).flexSlider() is not a function  ". And in My text editor it's also show me i declier flexSlider variable but never use.

I load jquery in my index.html file and also in my Slider component. And in my Slider component in import flexslider which I installed by npm.

```<code>import React from 'react';
import $ from 'jquery';
import flexSlider from 'flexslider';

class Slider extends React.Component {
  componentDidMount(){
    this.$el = $(this.el);
    this.$el.flexSlider();
  }
  render(){
    return (
      <div className="slider" ref={el=> this.el = el}>
        {this.props.children}
      </div>
    )
  }
};

export default Slider;
</code>```

That give me the error " $(this.el).flexSlider() is not a function "

答:
Create one component jQuery, example (components/Jquery.js:

```<code>import React from 'react'
import jQuery from 'jquery' // Import directly from node-modules
window.jQuery = jQuery

export default () => (jQuery)
</code>```

In your component you will use a jQuery plugin, example (components/Slider.js):

```<code>import React, {Component} from 'react'
import $ from './Jquery' // Import component
import flexSlider from 'flexslider' // Import directly from node-modules

class Slider extends Component {
    componentDidMount() {
         $(".hero-slider").flexslider({
            controlNav: true,
            directionNav: false,
            animation: "fade"
        });
    }

    render = () => (
        <div className="hero hero-slider">
        <ul className="slides">
            <li data-bg-image="dummy/slider-1.jpg">
            <div className="container">
                         <h3 className="slider-subtitle">Your header goes here</h3>
            <h2 className="slider-title">Professional</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa molestiae necessitatibus possimus ducimus facere, error, nostrum. Quos sapiente ducimus maxime odio alias dolor consequuntur, maiores commodi exercitationem veniam. Id, ex?</p>
            <a href="#" className="button large">Read more</a>
            </div>
        </li>
                 <li data-bg-image="dummy/slider-2.jpg">
            <div className="container">
                <h3 className="slider-subtitle">Your header goes here</h3>
            <h2 className="slider-title">Professional</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. In maiores illo eligendi obcaecati reiciendis, vel perspiciatis aliquid esse architecto deleniti asperiores, laboriosam nemo rerum! Ipsam numquam delectus minus iure sit!</p>
            <a href="#" className="button large">Read more</a>
            </div>
        </li>
        <li data-bg-image="dummy/slider-3.jpg">
            <div className="container">
            <h3 className="slider-subtitle">Your header goes here</h3>
            <h2 className="slider-title">Professional</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam iure, alias error suscipit porro quidem minus, autem repellendus rerum labore corrupti! Quia quas, architecto, quis non pariatur quisquam nisi magnam.</p>
            <a href="#" className="button large">Read more</a>
            </div>
        </li>
        </ul>
    </div>
    )
}

export default Slider
</code>```

Just an example. Understand this to implement in your code.

Body:
I try to import a jquery flexslider plugin in Slider component. But it's give me error " $(this.el).flexSlider() is not a function  ". And in My text editor it's also show me i declier flexSlider variable but never use.

I load jquery in my index.html file and also in my Slider component. And in my Slider component in import flexslider which I installed by npm.

import React from 'react';
import $ from 'jquery';
import flexSlider from 'flexslider';

class Slider extends React.Component {
  componentDidMount(){
    this.$el = $(this.el);
    this.$el.flexSlider();
  }
  render(){
    return (

 this.el = el}>
        {this.props.children}

    )
  }
};

export default Slider;

That give me the error " $(this.el).flexSlider() is not a function "

Body:
Create one component jQuery, example (components/Jquery.js:

import React from 'react'
import jQuery from 'jquery' // Import directly from node-modules
window.jQuery = jQuery

export default () => (jQuery)

In your component you will use a jQuery plugin, example (components/Slider.js):

import React, {Component} from 'react'
import $ from './Jquery' // Import component
import flexSlider from 'flexslider' // Import directly from node-modules

class Slider extends Component {
    componentDidMount() {
         $(".hero-slider").flexslider({
            controlNav: true,
            directionNav: false,
            animation: "fade"
        });
    }

    render = () => (
        <div className="hero hero-slider">
        <ul className="slides">
            <li data-bg-image="dummy/slider-1.jpg">
            <div className="container">
                         <h3 className="slider-subtitle">Your header goes here</h3>
            <h2 className="slider-title">Professional</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa molestiae necessitatibus possimus ducimus facere, error, nostrum. Quos sapiente ducimus maxime odio alias dolor consequuntur, maiores commodi exercitationem veniam. Id, ex?</p>
            <a href="#" className="button large">Read more</a>
            </div>
        </li>
                 <li data-bg-image="dummy/slider-2.jpg">
            <div className="container">
                <h3 className="slider-subtitle">Your header goes here</h3>
            <h2 className="slider-title">Professional</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. In maiores illo eligendi obcaecati reiciendis, vel perspiciatis aliquid esse architecto deleniti asperiores, laboriosam nemo rerum! Ipsam numquam delectus minus iure sit!</p>
            <a href="#" className="button large">Read more</a>
            </div>
        </li>
        <li data-bg-image="dummy/slider-3.jpg">
            <div className="container">
            <h3 className="slider-subtitle">Your header goes here</h3>
            <h2 className="slider-title">Professional</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam iure, alias error suscipit porro quidem minus, autem repellendus rerum labore corrupti! Quia quas, architecto, quis non pariatur quisquam nisi magnam.</p>
            <a href="#" className="button large">Read more</a>
            </div>
        </li>
        </ul>
    </div>
    )
}

export default Slider

Just an example. Understand this to implement in your code.


来源: stackexchange

问:
Create a variable from a Remote Ping Response IP Address
I need to be able to ping a range of IP addresses and when I get a reply on one, then capture that IP to put in a variable which I can use to update the local computers host file.

The purpose of this script is to be used for a Point-to-Site Azure VPN service. A remote server is connecting as a client and is given a second IP address which changes on each connection. The other server can only communicate to the remote server on this IP address, but the application it uses only uses DNS Names, so I will need to update the hosts file with the connecting servers IP each time it dials in.

```<code>$subnet = "172.16.201.0"
$start = 1
$end = 10
$ping = 1
while ($start -le $end) {
$IP = "172.16.201.$start"
Write-Host "Pinging $IP" -ForegroundColor Cyan
Test-Connection -ComputerName $IP -count 1 -Quiet
$start++
}
</code>```

So far the above code only does a IP Sweep and outputs the success/failure of each IP. I need to capture the success IP and put that in a variable

答:
```<code>$dns = "domain.com"
$ipAddresses = @(
    "172.16.201.0"
    "172.16.201.1"
    "172.16.201.2"
    "172.16.201.3"
    "172.16.201.4"
    "172.16.201.5"
    "172.16.201.6"
    "172.16.201.7"
    "172.16.201.8"
    "172.16.201.9"
    "172.16.201.10"
)
foreach($ip in $ipAddresses) {
    Write-Host "Pinging $ip" -ForegroundColor Cyan
    $ping = Test-Connection -ComputerName "$ip" -count 1 -Quiet
    if ($ping) {
        Add-Content -Path "C:\Windows\System32\drivers\etc\hosts" -Value "$ip     $dns"
        Write-Host "The host file was updated with the successful IP and hostname: $ip    $dns" -ForegroundColor Cyan
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to be able to ping a range of IP addresses and when I get a reply on one, then capture that IP to put in a variable which I can use to update the local computers host file.

The purpose of this script is to be used for a Point-to-Site Azure VPN service. A remote server is connecting as a client and is given a second IP address which changes on each connection. The other server can only communicate to the remote server on this IP address, but the application it uses only uses DNS Names, so I will need to update the hosts file with the connecting servers IP each time it dials in.

$subnet = "172.16.201.0"
$start = 1
$end = 10
$ping = 1
while ($start -le $end) {
$IP = "172.16.201.$start"
Write-Host "Pinging $IP" -ForegroundColor Cyan
Test-Connection -ComputerName $IP -count 1 -Quiet
$start++
}

So far the above code only does a IP Sweep and outputs the success/failure of each IP. I need to capture the success IP and put that in a variable


问:
How to check if all array values are blank in Javascript
I have an array like:

```<code>["", "", "", "1", "", ""]
</code>```

I want to alert when all the array values are blanks, i.e, when the array is like this:

```<code>["", "", "", "", "", ""]
</code>```

How can I achieve this.

答:
const isEmpty=arr=>{
  return arr.filter(it=>it.length>0).length ==0
}

arr1 = ["",""]
arr2 = ["1",""]

console.log(isEmpty(arr1))
console.log(isEmpty(arr2))```

Body:
I have an array like:

["", "", "", "1", "", ""]

I want to alert when all the array values are blanks, i.e, when the array is like this:

["", "", "", "", "", ""]

How can I achieve this.


问:
Retrieve records based on Date
I have a date column in my table.
Is there any way in mysql to retrieve record based on date excluding the time part?

I have tried appending * but does not seems to work.

SELECT * FROM myTable where filterDate="2010-08-01 *"

Is there any way to do it like this rather then filtering it by using between?

Thanks.

答:
You can use DATE_FORMAT function of mysql</p>

```<code>SELECT * FROM myTable where DATE_FORMAT(filterDate,'%Y-%m-%d') ="2010-08-01"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Retrieve records based on Date

Body:
You can use DATE_FORMAT function of mysql

SELECT * FROM myTable where DATE_FORMAT(filterDate,'%Y-%m-%d') ="2010-08-01"


问:
Laravel The GET method is not supported for this route. Supported methods: POST
I have the next trouble
I have a form, and when I click to register button, show me the next:

"The GET method is not supported for this route. Supported methods: POST."

But my method is POST, this is my Route:

```<code>Route::post('/createpedido',[
'uses'=>'PedidosControlador@pedidoagregado',
'as'=>'Pedidos.pedidoagregado']);
</code>```

And this is part of my blade

```<code>            <form method="post" action="{{route('Pedidos.pedidoagregado')}}" enctype="multipart/form-data">
            {{csrf_field()}}
            <div class="row text-center">

                <div class="col-lg-12 col-sm-12">
                    <h2>Agregar Pedido</h2>
                    <h3>Cliente: {{$Clientes->nombreempresa}}</h3>
                </div>

                <div class="col-lg-6 col-sm-6">
                    <h2>Datos Pedido</h2>
                    <hr size="5" color="#FF0000" />
</code>```

And this is my complete controller

```<code>   public function pedidoagregado(Request $request)
{
    $validator = Validator::make($request->all(), [
        'pedido' => 'required|string|max:255',
        'fechapedido' => 'required|date|max:255',
        'fechaentrega' => 'required|date|max:255',
        'tipopedido' => 'required|string|max:255',
        'observaciones' => 'required|email|max:255',
    ]);

    if ($validator->fails()) {
        return redirect('/createpedido')
            ->withErrors($validator)
            ->withInput();
    }

    $pedido = $request['pedido'];
    $fechapedido = $request['fechapedido'];
    $fechaentrega = $request['fechaentrega'];
    $tipopedido = $request['tipopedido'];
    $observaciones = $request['observaciones'];
    $idcliente = $request['idcliente'];

    $pedidos = new Pedidos();

    $pedidos->idcliente = $idcliente ;
    $pedidos->npedido = $pedido;
    $pedidos->fechapedido = $fechapedido;
    $pedidos->fechaentrega = $fechaentrega;
    $pedidos->tipopedido = $tipopedido;
    $pedidos->observacones = $observaciones;
    $pedidos->save();

    $request->session()->flash('alert-success', 'Pedido Agregado Correctamente');

    if(Auth::user()->userlevel == "admin"){
    return redirect()->to('administrador/');
    }

    if(Auth::user()->userlevel == "ventas"){
        return redirect()->to('ventas/');
    }

}
</code>```

Thanks for your help

答:
I check your code, which you provided and everything is fine. I guess, there is a probability you make two routes one get the form and second for post route for posting your data to the server.

and perhaps by mistake, you give same alias to both routes.

You give method post so whether you give same alias it should work, perhaps you forget to close form tag or by mistake, you have another form inside your form.
Perhaps there is some issue with route cache.
so clear it with artisan command.

```<code>php artisan route:clear
</code>```

Perhaps This will work, there is some probability you did something wrong, so I suggest you recheck all part I included in the answer.

Body:
I have the next trouble
I have a form, and when I click to register button, show me the next:

"The GET method is not supported for this route. Supported methods: POST."

But my method is POST, this is my Route:

Route::post('/createpedido',[
'uses'=>'PedidosControlador@pedidoagregado',
'as'=>'Pedidos.pedidoagregado']);

And this is part of my blade

            <form method="post" action="{{route('Pedidos.pedidoagregado')}}" enctype="multipart/form-data">
            {{csrf_field()}}

Agregar Pedido

Cliente: {{$Clientes->nombreempresa}}

Datos Pedido

And this is my complete controller

   public function pedidoagregado(Request $request)
{
    $validator = Validator::make($request->all(), [
        'pedido' => 'required|string|max:255',
        'fechapedido' => 'required|date|max:255',
        'fechaentrega' => 'required|date|max:255',
        'tipopedido' => 'required|string|max:255',
        'observaciones' => 'required|email|max:255',
    ]);

    if ($validator->fails()) {
        return redirect('/createpedido')
            ->withErrors($validator)
            ->withInput();
    }

    $pedido = $request['pedido'];
    $fechapedido = $request['fechapedido'];
    $fechaentrega = $request['fechaentrega'];
    $tipopedido = $request['tipopedido'];
    $observaciones = $request['observaciones'];
    $idcliente = $request['idcliente'];

    $pedidos = new Pedidos();

    $pedidos->idcliente = $idcliente ;
    $pedidos->npedido = $pedido;
    $pedidos->fechapedido = $fechapedido;
    $pedidos->fechaentrega = $fechaentrega;
    $pedidos->tipopedido = $tipopedido;
    $pedidos->observacones = $observaciones;
    $pedidos->save();

    $request->session()->flash('alert-success', 'Pedido Agregado Correctamente');

    if(Auth::user()->userlevel == "admin"){
    return redirect()->to('administrador/');
    }

    if(Auth::user()->userlevel == "ventas"){
        return redirect()->to('ventas/');
    }

}

Thanks for your help

Body:
I check your code, which you provided and everything is fine. I guess, there is a probability you make two routes one get the form and second for post route for posting your data to the server.

and perhaps by mistake, you give same alias to both routes.

You give method post so whether you give same alias it should work, perhaps you forget to close form tag or by mistake, you have another form inside your form.
Perhaps there is some issue with route cache.
so clear it with artisan command.

php artisan route:clear

Perhaps This will work, there is some probability you did something wrong, so I suggest you recheck all part I included in the answer.


问:
How can I use Dropzone.js in my own function
I am having difficulties integrating Dropzone.js with my own ajax function, I don't know what I should do to use dropzone inside my ajax function. </p>

<p>This is my own ajax function code : </p>

```<code>function _ajaxForm(formHandler){
var action = $(formHandler).attr('action');
$.post(action, $(formHandler).serialize(), function(data){
    // I want to submit my fields and my form upload using this function
}, 'json');}
</code>```

答:
You just need to configure your dropzone accordingly.

Using the sending event you could do something like this:

```<code>Dropzone.options.myAwesomeDropzone = {
  // Some default configurations
  paramName: "file", // The name that will be used to transfer the file
  maxFilesize: 2, // MB
  // Additional configurations needed for your ajax call
  url: "insertyoururlhere",
  init: function () {
      this.on("error", function (error, message) {
        //do something to handle the error
      });
      this.on("success", function (success, response) {
        //do something
      });
      this.on("sending", function (file, xhr, formData) {
        //add any form data that you would have in your ajax function eg:
        //formData.append("id", 123);
      });
      this.on("complete", function () {
        this.removeAllFiles(true);
        //do something
      });
    }
});
</code>```

See this, this and this answer which might also help.

Body:
I am having difficulties integrating Dropzone.js with my own ajax function, I don't know what I should do to use dropzone inside my ajax function.

This is my own ajax function code :

function _ajaxForm(formHandler){
var action = $(formHandler).attr('action');
$.post(action, $(formHandler).serialize(), function(data){
    // I want to submit my fields and my form upload using this function
}, 'json');}

Body:
You just need to configure your dropzone accordingly.

Using the sending event you could do something like this:

Dropzone.options.myAwesomeDropzone = {
  // Some default configurations
  paramName: "file", // The name that will be used to transfer the file
  maxFilesize: 2, // MB
  // Additional configurations needed for your ajax call
  url: "insertyoururlhere",
  init: function () {
      this.on("error", function (error, message) {
        //do something to handle the error
      });
      this.on("success", function (success, response) {
        //do something
      });
      this.on("sending", function (file, xhr, formData) {
        //add any form data that you would have in your ajax function eg:
        //formData.append("id", 123);
      });
      this.on("complete", function () {
        this.removeAllFiles(true);
        //do something
      });
    }
});

See this, this and this answer which might also help.


问:
Datatable is not working when there is data from DB
Jquery datatable plugin is not working when it has data that selected from database by date. But it's working if there is no data in table. Here some code

Select all data from database table in controller :

```<code>$inbound['inbound'] = DB::table('REPORT_INBOUND')
    ->where('regdate', '=', date('Y-m-d', strtotime("2019-05-21")))
    ->get();
return view('/traffic', $inbound, $outbound);
</code>```

And i did copy paste that necessary scripts for example :

```<code><link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
</code>```

```<code><table id="ahhhaa" width="90%" class="table table-striped table-bordered table-hover display">
            <thead class="thead-light">
            <tr>
                <th>ID</th>
                <th>RegDate</th>
                <th>HPMN Code</th>
                <th>Country</th>
                <th>HPMN Name</th>
            </tr>
            </head>
            <tbody>
            @foreach($inbound as $value)
                <tr class="table table-hover">
                    <td>{{ $value->id }}</td>
                    <td>{{ $value->regdate }}</td>
                    <td>{{ $value->hpmn_code }}</td>
                    <td>{{ $value->country }}</td>
                    <td>{{ $value->hpmn_name }}</td>
            @endforeach
            </tbody>
</table>
</code>```

```<code>$(document).ready(function () {
   $('#ahhhaa').DataTable()
});
</code>```

Is there any error ?

答:
return your view page with data:</p>

```<code>return view('folder/file_name')->with($inbound);
</code>```

Body:
Jquery datatable plugin is not working when it has data that selected from database by date. But it's working if there is no data in table. Here some code

Select all data from database table in controller :

$inbound['inbound'] = DB::table('REPORT_INBOUND')
    ->where('regdate', '=', date('Y-m-d', strtotime("2019-05-21")))
    ->get();
return view('/traffic', $inbound, $outbound);

And i did copy paste that necessary scripts for example :

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

                ID
                RegDate
                HPMN Code
                Country
                HPMN Name

            @foreach($inbound as $value)

                    {{ $value->id }}
                    {{ $value->regdate }}
                    {{ $value->hpmn_code }}
                    {{ $value->country }}
                    {{ $value->hpmn_name }}
            @endforeach

$(document).ready(function () {
   $('#ahhhaa').DataTable()
});

Is there any error ?

Body:
return your view page with data:

return view('folder/file_name')->with($inbound);


问:
Can't attach Android Studio's debugger to Android process
I can't attach Android Studio's debugger to my debuggable application process. Anyone else had this issue? Basically I can't get my app listed in Choose Process dialog.

I'm selecting Attach debugger to Android process:

And then, here's how Process selection dialog from Android Studio looks like:

Any ideas why my app is not shown in the Choose Process list?

Although, DDMS sees my app in Devices | logcat list:

<img src="https://i.stack.imgur.com/EEx93.png" alt="Devices | logcat list">

Android Monitor also sees the app in Devices list:

I've tried these actions:

Restarting MacBook

Restarting devices: tried with Samsung Galaxy Note II N7100 (4.3) and Samsung Galaxy S4 (4.4.2)

Reenabling Settings->Developer Options on the devices

Reenabling Settings->Developer Options->USB debugging on the devices

Restarting adb by running adb kill-server and adb start-server

Reconnecting device from macbook and/or plugging to another USB port

Launching Genymotion virtual device on macbook

restarting in TCP mode port: 5555 by running adb tcpip 5555 and then connecting to it with adb connect 192.168.1.87

Waiting more&Restart when got this error saying ADB not responding. You can wait more, or kill "adb" process manually and click 'Restart' Errors in ADB: ddms: '$ANDROID_HOME/platform-tools/adb,start-server' failed -- run manually if necessary Error screenshot

Update:

What I've noticed is that device appears multiple times in the Android DDMS->Devices | logcat list. If I choose 1st device from the list, it shows, there's No debuggable applications, but I select last device (4th in the screenshot) I see my debuggable application. See screenshots: 1st and 4th. Although, even there's only 1 device in the list and showing debuggable device and application, process still does not appear in the Choose Process dialog.

答:
I just encountered this one as well. I was pulling my hair out and did everything that was posted here. I thought I could add to the solutions here in case everyone had tried everything. I solve it via making my build variant debuggable.

So I made a PR and it was merged, unfortunately my debuggable flag on my own build variant was turned off when I pulled the source back, so I just have to turn it back on:

on your build.gradle file:

```<code>android {
   ...
   buildTypes {
      ...
      my_build_type {
            minifyEnabled false
            shrinkResources false
            debuggable true    // was false before
      }
   }
}
</code>```

Also make sure that this build variant was set before you build your app to the device:

Body:
I just encountered this one as well. I was pulling my hair out and did everything that was posted here. I thought I could add to the solutions here in case everyone had tried everything. I solve it via making my build variant debuggable.

So I made a PR and it was merged, unfortunately my debuggable flag on my own build variant was turned off when I pulled the source back, so I just have to turn it back on:

on your build.gradle file:

android {
   ...
   buildTypes {
      ...
      my_build_type {
            minifyEnabled false
            shrinkResources false
            debuggable true    // was false before
      }
   }
}

Also make sure that this build variant was set before you build your app to the device:


问:
Cannot get DOM events on component in host component
I have a Vue component that contains a list of objects named lines.  I build a table from those lines using different components based on the line type.  This works perfectly.  Here's a stripped down version of the component:

```<code><template>
  <table>
    <tr v-for="line in lines"
        :key="line.key"
        :is="componentForType[line.eventType] || 'LogLine'"
        v-bind="line"
    />
  </table>
</template>

<script>
  export default {
    name: 'DebugLog',
    components: {
      LogLine,
      FormattedLogLine,
      UserDebug,
      Limits
    },
    data () {
      return {
        lines: [],
        selectedKey: null,
        componentForType: {
          'USER_DEBUG' : 'UserDebug',
          'LIMIT_USAGE_FOR_NS' : 'Limits',
          'EXCEPTION_THROWN' : 'FormattedLogLine',
          'FATAL_ERROR' : 'FormattedLogLine'
        }

      }
    },
    mounted() {
      // code that loads this.lines
    }
  }
</script>
</code>```

Now I want to be able to click any row of the table, and have the row become "selected", meaning that I want store line.key in this.selectedKey and use CSS to render that line differently.  But I can't get the events working.  Here's the updated <template>; nothing else is changed:

```<code><template>
  <table>
    <tr v-for="line in lines"
        :key="line.key"
        :is="componentForType[line.eventType] || 'LogLine'"
        v-bind="line"
        :class="{selected: line.key == selectedKey}"
        @click.capture="selectedKey = line.key"
    />
  </table>
</template>
</code>```

I've added the last 2 properties on the tr element - a dynamic class binding and a click event handler to set this.selectedKey to the active line's key.  But it isn't working.  I replaced the @click handler code with console.log(line.key) and nothing is logged, which tells me that my @click handler is never firing.  I originally wrote it with out the .capture modifier, but tried adding the modifier when the original didn't work.

Is vue.js stopping propagation from the child component to the parent?  Can I not bind the click event on the tr since it :is another vue component?  Or is there something else going on?  The examples I've found in the docs are much simpler and I'm not sure they correspond to my situation.  The various child components are not binding any click events.  I'd prefer to handle the event entirely in the parent as shown, since I will have a number of types of child component, and I don't want to have to implement click handlers in each.

Update: Looking at my child components, I note that each contains a tr tag that must effectively replace the tr in the parent template.  For example, my most basic component is LogLine, shown here:

```<code><template>
  <tr>
    <td>{{timeStamp}}</td>
    <td>{{eventType}}</td>
    <td>{{lineNumber}}</td>
    <td>{{lineData}}</td>
  </tr>
</template>

<script>
  export default {
    name: 'LogLine',
    props: ['timeStamp', 'eventType', 'lineData', 'lineNumber'],
    data: function () {
      return {}
    }
  }
</script>
</code>```

So I'm guessing that the binding in the parent isn't actually binding on the tr in the DOM; it's just binding on the Vue component, listening for a click event to be sent from the child with $emit; and that each child component will need to bind @click on its tr and emit it to the parent.  Assuming I'm right, is there any shortcut I can use from the parent template to have vue forward the DOM events?  Any other option I'm missing besides binding click in every child component?

答:
Piggy-backing off of Jacob's answer here. Since you're essentially attaching an event listener to a dynamic component it expects a custom click event. So you have two options here:

Listen for the native DOM click event within that component (by attaching a click event listener to a normal DOM element within the component) and emit a custom click event to the parent.

Use the .native modifier to listen for the native DOM click event instead of a custom one directly in the parent.

Body:
I have a Vue component that contains a list of objects named lines.  I build a table from those lines using different components based on the line type.  This works perfectly.  Here's a stripped down version of the component:

<template>

</template>

Now I want to be able to click any row of the table, and have the row become "selected", meaning that I want store line.key in this.selectedKey and use CSS to render that line differently.  But I can't get the events working.  Here's the updated <template>; nothing else is changed:

<template>

</template>

I've added the last 2 properties on the tr element - a dynamic class binding and a click event handler to set this.selectedKey to the active line's key.  But it isn't working.  I replaced the @click handler code with console.log(line.key) and nothing is logged, which tells me that my @click handler is never firing.  I originally wrote it with out the .capture modifier, but tried adding the modifier when the original didn't work.

Is vue.js stopping propagation from the child component to the parent?  Can I not bind the click event on the tr since it :is another vue component?  Or is there something else going on?  The examples I've found in the docs are much simpler and I'm not sure they correspond to my situation.  The various child components are not binding any click events.  I'd prefer to handle the event entirely in the parent as shown, since I will have a number of types of child component, and I don't want to have to implement click handlers in each.

Update: Looking at my child components, I note that each contains a tr tag that must effectively replace the tr in the parent template.  For example, my most basic component is LogLine, shown here:

<template>

    {{timeStamp}}
    {{eventType}}
    {{lineNumber}}
    {{lineData}}

</template>

So I'm guessing that the binding in the parent isn't actually binding on the tr in the DOM; it's just binding on the Vue component, listening for a click event to be sent from the child with $emit; and that each child component will need to bind @click on its tr and emit it to the parent.  Assuming I'm right, is there any shortcut I can use from the parent template to have vue forward the DOM events?  Any other option I'm missing besides binding click in every child component?


问:
replace single slash with double slash, php
how replace single slash with double slash?
I have this text:

```<code>"/data/folder/"

 and i need get

"//data//folder//"
</code>```

i try with replace, but get error:

```<code>$data = str_replace("\", "\\", $data);
</code>```

答:
You want to replace forward slash but your str_replace is having back slash.

Try:

```<code>$data = str_replace("/", "//", $data);
</code>```

Cause of error:

\ is used escaping. So the \ in "\" is actually escaping the second ".

Body:
how replace single slash with double slash?
I have this text:

"/data/folder/"

 and i need get

"//data//folder//"

i try with replace, but get error:

$data = str_replace("\", "\\", $data);

Body:
You want to replace forward slash but your str_replace is having back slash.

Try:

$data = str_replace("/", "//", $data);

Cause of error:

\ is used escaping. So the \ in "\" is actually escaping the second ".


问:
Insert one table data into another table
In my database currently, have 2 tables with data called student and subject.

In my web application have a new requirement, so I have to add additional mapping table called StudentSubject. However now I need to insert data to that table(StudentSubject) as follows. How can I write a script to achieve it? And may I know should I need to write Pre-Deployment or Post-Deployment Script to do this? If yes how can I do it?

答:
Simple by cross Join.</p>

```<code>INSERT INTO StudentSubject
SELECT StudentId, SubjectId
FROM Student, Subject

--OR

INSERT INTO StudentSubject
SELECT StudentId, SubjectId
FROM Student
CROSS JOIN Subject
</code>```

Body:
Simple by cross Join.

INSERT INTO StudentSubject
SELECT StudentId, SubjectId
FROM Student, Subject

--OR

INSERT INTO StudentSubject
SELECT StudentId, SubjectId
FROM Student
CROSS JOIN Subject


问:
How to wrap validation messge on Flutter?
I added TextFormField validation message..Everything working good. But All text not displayed.

```<code>Container(
            padding: EdgeInsets.all(16.0),
            margin: EdgeInsets.only(top: 30.0),
            child: TextFormField(
              validator: (value) {
                if (value.isEmpty) {
               return 'The password you entered does not meet the minimum requirement. Please refer the Password Policy for more details.';
              },
              obscureText: true,
              controller: confirmPasswordController,
              keyboardType: TextInputType.emailAddress,
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.all(20.0),
                labelText: AppTranslations.of(context)
                    .text("passwordpage_username"),
              ),
            ),
          ),
</code>```

答:
Try this code</p>

```<code>Expanded(
   child: Container(
     padding: EdgeInsets.all(16.0),
     margin: EdgeInsets.only(top: 30.0),
     child: TextFormField(
          validator: (value) {
            if (value.isEmpty) {
           return 'The password you entered does not meet the minimum requirement.\n Please refer the Password Policy for more details.';
          },
          obscureText: true,
          controller: confirmPasswordController,
          keyboardType: TextInputType.emailAddress,
          decoration: InputDecoration(
            contentPadding: const EdgeInsets.all(20.0),
            labelText: AppTranslations.of(context)
                .text("passwordpage_username"),
          ),
        ),
       )
      ),
</code>```

Body:
I added TextFormField validation message..Everything working good. But All text not displayed.

Container(
            padding: EdgeInsets.all(16.0),
            margin: EdgeInsets.only(top: 30.0),
            child: TextFormField(
              validator: (value) {
                if (value.isEmpty) {
               return 'The password you entered does not meet the minimum requirement. Please refer the Password Policy for more details.';
              },
              obscureText: true,
              controller: confirmPasswordController,
              keyboardType: TextInputType.emailAddress,
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.all(20.0),
                labelText: AppTranslations.of(context)
                    .text("passwordpage_username"),
              ),
            ),
          ),

Body:
Try this code

Expanded(
   child: Container(
     padding: EdgeInsets.all(16.0),
     margin: EdgeInsets.only(top: 30.0),
     child: TextFormField(
          validator: (value) {
            if (value.isEmpty) {
           return 'The password you entered does not meet the minimum requirement.\n Please refer the Password Policy for more details.';
          },
          obscureText: true,
          controller: confirmPasswordController,
          keyboardType: TextInputType.emailAddress,
          decoration: InputDecoration(
            contentPadding: const EdgeInsets.all(20.0),
            labelText: AppTranslations.of(context)
                .text("passwordpage_username"),
          ),
        ),
       )
      ),


问:
Cannot bind parameter because parameter 'AccountPassword' is specified more than once ,how to fix this issue, thanks
Import-Module activedirectory
$ADUsers = Import-Csv -Path "C:\Script\CreateUser.Mass\20190527.Wave.csv"

foreach ($User in $ADUsers)

{

```<code>$GivenName = $User.'GivenName'
$Surname = $User.'Surname'
$Displayname = $User.'DisplayName'
$Title = $User.'Title'
$Department = $User.'Department'
$Office = $User.'Office'
$Company = $User.'Company'
$StreetAddress = $User.'StreetAddress'
$City = $User.'City'
$Country = $User.'Country'
$HomePage = $User.'HomePage'
$Password = $User.'Password'

$SAM = $User.'SamAccountName'
$OU = "OU=Users-Massimport,OU=SITA-HK,DC=swiresita,DC=com"
$UPN = $User.'DisplayName' + "@swiresita.com"

New-ADUser  -Name "$Displayname" -GivenName "$GivenName" -Surname "$Surname" -Displayname "$Displayname" -Title "$Title" -Department "$Department" -Office "$Office" -Company "$Company" -StreetAddress  "$StreetAddress" -City "$City" -Country "$Country" -HomePage "$HomePage" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -SamAccountName $SAM -UserPrincipalName $UPN -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false -PasswordNeverExpires $false
</code>```

}

答:
As mentioned by Bill_Stewart in the comments, use splatting:

```<code>foreach ($User in $ADUsers)
{

    $adUserParameters  = @{
        GivenName = $User.'GivenName'
        Surname = $User.'Surname'
        Displayname = $User.'DisplayName'
        Title = $User.'Title'
        Department = $User.'Department'
        Office = $User.'Office'
        Company = $User.'Company'
        StreetAddress = $User.'StreetAddress'
        City = $User.'City'
        Country = $User.'Country'
        HomePage = $User.'HomePage'
        Password = $User.'Password'
        SAM = $User.'SamAccountName'
        OU = "OU=Users-Massimport,OU=SITA-HK,DC=swiresita,DC=com"
        UPN = ($User.'DisplayName' + "@swiresita.com")
        AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
        Enabled = $true
        ChangePasswordAtLogon = $false
        PasswordNeverExpires = $false
    }

    New-ADUser @adUserParameters
}
</code>```

If you're on an older version of powershell you can use '`' (grave sign) to add a new line while continuing the call to New-AdUser:

```<code>New-ADUser  `
    -Name "$Displayname" `
    -GivenName "$GivenName" `
    -Surname "$Surname" `
    -Displayname "$Displayname" `
    -Title "$Title" `
    -Department "$Department" `
    -Office "$Office" `
    -Company "$Company" `
    -StreetAddress  "$StreetAddress" `
    -City "$City" `
    -Country "$Country" `
    -HomePage "$HomePage" `
    -SamAccountName $SAM `
    -UserPrincipalName $UPN `
    -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
    -Enabled $true `
    -Path "$OU" `
    -ChangePasswordAtLogon $false `
    -PasswordNeverExpires $false
</code>```

Body:
Import-Module activedirectory
$ADUsers = Import-Csv -Path "C:\Script\CreateUser.Mass\20190527.Wave.csv"

foreach ($User in $ADUsers)

{

$GivenName = $User.'GivenName'
$Surname = $User.'Surname'
$Displayname = $User.'DisplayName'
$Title = $User.'Title'
$Department = $User.'Department'
$Office = $User.'Office'
$Company = $User.'Company'
$StreetAddress = $User.'StreetAddress'
$City = $User.'City'
$Country = $User.'Country'
$HomePage = $User.'HomePage'
$Password = $User.'Password'

$SAM = $User.'SamAccountName'
$OU = "OU=Users-Massimport,OU=SITA-HK,DC=swiresita,DC=com"
$UPN = $User.'DisplayName' + "@swiresita.com"

New-ADUser  -Name "$Displayname" -GivenName "$GivenName" -Surname "$Surname" -Displayname "$Displayname" -Title "$Title" -Department "$Department" -Office "$Office" -Company "$Company" -StreetAddress  "$StreetAddress" -City "$City" -Country "$Country" -HomePage "$HomePage" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -SamAccountName $SAM -UserPrincipalName $UPN -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false -PasswordNeverExpires $false

}

Body:
As mentioned by Bill_Stewart in the comments, use splatting:

foreach ($User in $ADUsers)
{

    $adUserParameters  = @{
        GivenName = $User.'GivenName'
        Surname = $User.'Surname'
        Displayname = $User.'DisplayName'
        Title = $User.'Title'
        Department = $User.'Department'
        Office = $User.'Office'
        Company = $User.'Company'
        StreetAddress = $User.'StreetAddress'
        City = $User.'City'
        Country = $User.'Country'
        HomePage = $User.'HomePage'
        Password = $User.'Password'
        SAM = $User.'SamAccountName'
        OU = "OU=Users-Massimport,OU=SITA-HK,DC=swiresita,DC=com"
        UPN = ($User.'DisplayName' + "@swiresita.com")
        AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
        Enabled = $true
        ChangePasswordAtLogon = $false
        PasswordNeverExpires = $false
    }

    New-ADUser @adUserParameters
}

If you're on an older version of powershell you can use '`' (grave sign) to add a new line while continuing the call to New-AdUser:

New-ADUser  `
    -Name "$Displayname" `
    -GivenName "$GivenName" `
    -Surname "$Surname" `
    -Displayname "$Displayname" `
    -Title "$Title" `
    -Department "$Department" `
    -Office "$Office" `
    -Company "$Company" `
    -StreetAddress  "$StreetAddress" `
    -City "$City" `
    -Country "$Country" `
    -HomePage "$HomePage" `
    -SamAccountName $SAM `
    -UserPrincipalName $UPN `
    -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
    -Enabled $true `
    -Path "$OU" `
    -ChangePasswordAtLogon $false `
    -PasswordNeverExpires $false


问:
Determining Thread Safety in Unit Tests
I am writing a multi threaded application and I am also trying to work out how to write suitable unit tests for it. I think that's probably another question on how best to do that.

One more question, I have a class like the below knowing its not thread safe and want to prove it in a unit test but cannot work out how to do it:

```<code>public class MyClass
{
    private List<string> MyList = new List<string>();

    public void Add(string Data)
    {
        MyList.Add(Data);  //This is not thread safe!!
    }
}
</code>```

答:
I had a similar problem where we found Thread Safety bugs. To fix it we had to prove it and then fix it. That quest brought me to this page but I could not find any real answer. As many of the above answers explained why. But never the less I found a possible way that might help others:

```<code>public static async Task<(bool IsSuccess, Exception Error)> RunTaskInParallel(Func<Task> task, int numberOfParallelExecutions = 2)
    {
        var cancellationTokenSource = new CancellationTokenSource();
        Exception error = null;
        int tasksCompletedCount = 0;
        var result = Parallel.For(0, numberOfParallelExecutions, GetParallelLoopOptions(cancellationTokenSource),
                      async index =>
                      {
                          try
                          {
                              await task();
                          }
                          catch (Exception ex)
                          {
                              error = ex;
                              cancellationTokenSource.Cancel();
                          }
                          finally
                          {
                              tasksCompletedCount++;
                          }

                      });

        int spinWaitCount = 0;
        int maxSpinWaitCount = 100;
        while (numberOfParallelExecutions > tasksCompletedCount && error is null && spinWaitCount < maxSpinWaitCount))
        {
            await Task.Delay(TimeSpan.FromMilliseconds(100));
            spinWaitCount++;
        }

        return (error == null, error);
    }
</code>```

This is not the cleanest code nor our final result but the logic stays the same. This code proved our Thread Safety bug every time.

Here is how we used it:

```<code>int numberOfParallelExecutions = 2;
RunTaskInParallel(() => doSomeThingAsync(), numberOfParallelExecutions);
</code>```

Hope this helps someone.

Title: Determining Thread Safety in Unit Tests

Body:
I am writing a multi threaded application and I am also trying to work out how to write suitable unit tests for it. I think that's probably another question on how best to do that.

One more question, I have a class like the below knowing its not thread safe and want to prove it in a unit test but cannot work out how to do it:

public class MyClass
{
    private List<string> MyList = new List<string>();

    public void Add(string Data)
    {
        MyList.Add(Data);  //This is not thread safe!!
    }
}

Body:
I had a similar problem where we found Thread Safety bugs. To fix it we had to prove it and then fix it. That quest brought me to this page but I could not find any real answer. As many of the above answers explained why. But never the less I found a possible way that might help others:

public static async Task<(bool IsSuccess, Exception Error)> RunTaskInParallel(Func<Task> task, int numberOfParallelExecutions = 2)
    {
        var cancellationTokenSource = new CancellationTokenSource();
        Exception error = null;
        int tasksCompletedCount = 0;
        var result = Parallel.For(0, numberOfParallelExecutions, GetParallelLoopOptions(cancellationTokenSource),
                      async index =>
                      {
                          try
                          {
                              await task();
                          }
                          catch (Exception ex)
                          {
                              error = ex;
                              cancellationTokenSource.Cancel();
                          }
                          finally
                          {
                              tasksCompletedCount++;
                          }

                      });

        int spinWaitCount = 0;
        int maxSpinWaitCount = 100;
        while (numberOfParallelExecutions > tasksCompletedCount && error is null && spinWaitCount < maxSpinWaitCount))
        {
            await Task.Delay(TimeSpan.FromMilliseconds(100));
            spinWaitCount++;
        }

        return (error == null, error);
    }

This is not the cleanest code nor our final result but the logic stays the same. This code proved our Thread Safety bug every time.

Here is how we used it:

int numberOfParallelExecutions = 2;
RunTaskInParallel(() => doSomeThingAsync(), numberOfParallelExecutions);

Hope this helps someone.


问:
Yarnpkg can't add private package via ssh althought I've been added it
I can't perform yarn to install my packages.

Some of my packages are private like this:

```<code>"my-package": "git+ssh://git@mycompany.com:company/my-package#0.2.35"
</code>```

It produce this error.

```<code>git@my-company.com: Permission denied (publickey,password).
fatal: Could not read from remote repository.
</code>```

But I can git clone them via ssh, how do I solve this problem?

答:
If your default (~/.ssh/id_rsa) private SSH key is passphrase protected (passphrase, not password), then try at least to add it to the ssh agent.

As in yarnpkg/yarn issue 3942

To anyone else from the future like myself ssh-add -l -E md5 (for OpenSSH >= 6.8) seems to have cleared the issue up, while proclaiming that no identities were added.

To check which key is actually used, set GIT_SSH_COMMAND to ssh -v before your command.

Also, try and register another SSH key, this time with a legacy format (if your current key has 70 chars per line)

Body:
I can't perform yarn to install my packages.

Some of my packages are private like this:

"my-package": "git+ssh://git@mycompany.com:company/my-package#0.2.35"

It produce this error.

git@my-company.com: Permission denied (publickey,password).
fatal: Could not read from remote repository.

But I can git clone them via ssh, how do I solve this problem?


问:
Add a Button dynamically to a LinearLayout in Android
I am working on a project that needs to add buttons dynamically. But whenever I run my application the application force closes. I've learned that the problem is when I try to add buttons.</p>

```<code>package com.Feras.TestProject;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class TestProject extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    AddAll();
    // Set Text for the button in the Old Testament

}
public void AddAll() {
    LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout1);
    Button btn = new Button(this);
    btn.setText("MyButton");
    linearLayout.addView(btn);

    }
}
</code>```

答: there will only occure an error if linearLayout is null, ensure that layout1 is a valid Item of R.layout.main</p>

Body:
I am working on a project that needs to add buttons dynamically. But whenever I run my application the application force closes. I've learned that the problem is when I try to add buttons.

package com.Feras.TestProject;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class TestProject extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    AddAll();
    // Set Text for the button in the Old Testament

}
public void AddAll() {
    LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout1);
    Button btn = new Button(this);
    btn.setText("MyButton");
    linearLayout.addView(btn);

    }
}


问:
How to tell if bootstrap.js or bootstrap.bundle.js is loaded?
My code depends on both Bootstrap 4 and Popper.js. Bootstrap has a bundled JS file that includes Popper.js, but I can't figure out how to tell if the bundled or non-bundled version is loaded.

If bootstrap.js and popper.js are both included separately, I can test if Popper is defined, but if bootstrap.bundle.js is included Popper is not defined but the Bootstrap components that rely on Popper still work.

I can use something like typeof $().modal to check if bootstrap is included, but this is true of both the bundled and non-bundled verison.

<!DOCTYPE html>

        <title>Bootstrap Bundle Test</title>

```

In this example, I would expect Popper to be a function since it's included in the Bootstrap bundle, but it is undefined.

答: You can try to check if a proper method available in global space. And if it's give you true it's then you know  bootstrap.js and popper.js are both included separately otherwise it's bootstrap.bundle.js</p>

Body:
My code depends on both Bootstrap 4 and Popper.js. Bootstrap has a bundled JS file that includes Popper.js, but I can't figure out how to tell if the bundled or non-bundled version is loaded.

If bootstrap.js and popper.js are both included separately, I can test if Popper is defined, but if bootstrap.bundle.js is included Popper is not defined but the Bootstrap components that rely on Popper still work.

I can use something like typeof $().modal to check if bootstrap is included, but this is true of both the bundled and non-bundled verison.

<!DOCTYPE html>

        <title>Bootstrap Bundle Test</title>

In this example, I would expect Popper to be a function since it's included in the Bootstrap bundle, but it is undefined.


问:
Exclude specific headers from clang-tidy
I have several projects with many headers that I want to parse, but there are  several headers which I do not want to parse with clang-tidy

My folder hierarchy is as follows

```<code>A\
|
|-B\
| |
| |-C\
| | |
| | └-coco.h
| └-D\
└-E\
</code>```

My projects are inside C and D folders and I want them to parse all headers under B so my solution was
HeaderFilterRegex: 'B/*'
There are many headers that i want to include so I can't name each one.

however inside C and D folders there are several headers which I would like to exclude (for example coco.h).

I tried putting NO_LINT in the cpp that includes coco.h and that didn't help,

How Can I do this?

Thanks

答:
I found a workaround that fits my purpose (I have a limited list of files that I want to filter out and they have unique names)

I use the line-filter and add all the files that i want to filter out. In the line range I put a line that doesn't exist, this way it filters the file out. In the end of the line filter I add .h and .cpp so it will filter in the rest of the files.

E.g.lets say i want to filter out only coco.cpp

```<code>-line-filter=[{"name":"coco.cpp","lines":[[9999999,9999999]]},{"name":".h"},{"name":".cpp"}]
</code>```

One thing to note, and why i thought it didn't work is the following: the line-filter only works after it does the analysis and header-filter only works on includes.

In coco.cpp I had a line (call to template) which caused a warning but the warning showed on a header which was supposed to be filtered out by header-filter.

It wasn't filtered out because the warning was due to the cpp but the actual warning showed on the header so the line-filter didn't help until I put this specific header in line-filter as well.

Not very intuitive.

Body:
I have several projects with many headers that I want to parse, but there are  several headers which I do not want to parse with clang-tidy

My folder hierarchy is as follows

A\
|
|-B\
| |
| |-C\
| | |
| | └-coco.h
| └-D\
└-E\

My projects are inside C and D folders and I want them to parse all headers under B so my solution was
HeaderFilterRegex: 'B/*'
There are many headers that i want to include so I can't name each one.

however inside C and D folders there are several headers which I would like to exclude (for example coco.h).

I tried putting NO_LINT in the cpp that includes coco.h and that didn't help,

How Can I do this?

Thanks

Body:
I found a workaround that fits my purpose (I have a limited list of files that I want to filter out and they have unique names)

I use the line-filter and add all the files that i want to filter out. In the line range I put a line that doesn't exist, this way it filters the file out. In the end of the line filter I add .h and .cpp so it will filter in the rest of the files.

E.g.lets say i want to filter out only coco.cpp

-line-filter=[{"name":"coco.cpp","lines":[[9999999,9999999]]},{"name":".h"},{"name":".cpp"}]

One thing to note, and why i thought it didn't work is the following: the line-filter only works after it does the analysis and header-filter only works on includes.

In coco.cpp I had a line (call to template) which caused a warning but the warning showed on a header which was supposed to be filtered out by header-filter.

It wasn't filtered out because the warning was due to the cpp but the actual warning showed on the header so the line-filter didn't help until I put this specific header in line-filter as well.

Not very intuitive.


问:
why swiper slider doesn't play after using *ngFor
I'm using angular 7 for my project and I need to make a highligth section using swiper slider by idangero but i got a problem when using *ngFor i can render the data correctly but the slider won't play except i use ctr + shift + i or console after open it. and got stuck only for the last data I input. what i want to achieve is a slider that render data like this page.

I already read this topic but still not solve my problem:

Swiper issue after append slides

Swiper slider not working unless page is resized

this is my html code:

```<code><!-- start slider section -->
<section class="no-padding main-slider height-100 mobile-height wow fadeIn ">
  <div class="swiper-full-screen swiper-container height-100 width-100 black-move">
    <div class="swiper-wrapper">

      <!-- start slider item -->
      <div class="swiper-slide cover-background" style="background-image:url('http://placehold.it/1920x991');" *ngFor="let data of allNews">
        <div class="container position-relative full-screen">
          <div class="col-md-12 slider-typography text-center text-md-left">
            <div class="slider-text-middle-main">
              <div class="slider-text-middle">
                <h1 class="alt-font text-extra-dark-gray font-weight-700 letter-spacing-minus-1 line-height-80 width-55 margin-35px-bottom lg-width-60 md-width-70 lg-line-height-auto sm-width-100 sm-margin-15px-bottom">{{data.title}}</h1>

                <p class="text-extra-dark-gray text-large margin-four-bottom width-40 lg-width-50 md-width-60 sm-width-100 sm-margin-15px-bottom">{{data.summary}}</p>

                <div class="btn-dual">
                  <a href="#" target="_blank" class="btn btn-transparent-dark-gray btn-rounded btn-small margin-20px-lr sm-margin-5px-top">Selengkapnya</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- end slider item -->

    </div>
    <!-- start slider pagination -->
    <div class="swiper-pagination swiper-full-screen-pagination"></div>
    <!-- end slider pagination -->
  </div>
</section>
<!-- end slider section -->

</code>```

for the json:

```<code>[{
    "_id": "5ceac4c07b8ae43702a9ed75",
    "title": "test 1",
    "summary": "Very Test 1",
    "imageCover": "5ceac4c07b8ae43702a9ed76 Cover.jpg"
  },
  {
    "_id": "5ceaa000e5f34b3a55b456ed",
    "title": "Test 2",
    "summary": "Very Test 2",
    "imageCover": "5ceaa000e5f34b3a55b486ed Cover.jpg"
  }
],
</code>```

can someone help me to solve this? the data itself already render but the swiper doesn't autoplay and i can't manually it

答:
Never used swipper, but according to their getting started page, you need to "jump start" it.

```<code>import Swiper from 'swiper';

var mySwiper = new Swiper('.swiper-container', { /* ... */ });
</code>```

since this looks like it depends on the DOM to work, i'd make sure to run it after the view fully loaded.

so something like

```<code> import Swiper from 'swiper';

 // ...

 ngAfterViewInit() {
    const mySwiper = new Swiper('.swiper-container');
 }
</code>```

this obviously works as far as I can tell: demo with your code

Body:
I'm using angular 7 for my project and I need to make a highligth section using swiper slider by idangero but i got a problem when using *ngFor i can render the data correctly but the slider won't play except i use ctr + shift + i or console after open it. and got stuck only for the last data I input. what i want to achieve is a slider that render data like this page.

I already read this topic but still not solve my problem:

Swiper issue after append slides

Swiper slider not working unless page is resized

this is my html code:

{{data.title}}

{{data.summary}}

                  Selengkapnya

for the json:

[{
    "_id": "5ceac4c07b8ae43702a9ed75",
    "title": "test 1",
    "summary": "Very Test 1",
    "imageCover": "5ceac4c07b8ae43702a9ed76 Cover.jpg"
  },
  {
    "_id": "5ceaa000e5f34b3a55b456ed",
    "title": "Test 2",
    "summary": "Very Test 2",
    "imageCover": "5ceaa000e5f34b3a55b486ed Cover.jpg"
  }
],

can someone help me to solve this? the data itself already render but the swiper doesn't autoplay and i can't manually it

Body:
Never used swipper, but according to their getting started page, you need to "jump start" it.

import Swiper from 'swiper';

var mySwiper = new Swiper('.swiper-container', { /* ... */ });

since this looks like it depends on the DOM to work, i'd make sure to run it after the view fully loaded.

so something like

 import Swiper from 'swiper';

 // ...

 ngAfterViewInit() {
    const mySwiper = new Swiper('.swiper-container');
 }

this obviously works as far as I can tell: demo with your code


问:
Count a foreach loop and create new element in php
I'm working on a Mega Menu for WooCommerce Product Category. I'm able to get the list of all Subcategories using the code below;

```<code>$parent_id = 37; //ID of the Parent Category
$subCat_of_parent = get_terms('product_cat',array('child_of' => $parent_id));
</code>```

Then used in a html structure as below;

```<code><div class="row">
    <div class="col-md-6">
        <ul>
        <?php
        foreach ($subCat_of_parent as $subcat) {
            ?>
            <li>
                <a href="<?php echo get_category_link($subcat->term_id); ?>"><?php echo $subcat->name; ?></a>
            </li>
            <?php
        }
         ?>
        </ul>
    </div>
</div>
</code>```

This worked by getting all the list of subcategory of the parent category in this format;

```<code><div class="row">
    <div class="col-md-6">
        <ul>
           <li><a>1st subcategory</a></li>
           <li><a>2nd subcategory</a></li>
           <li><a>3rd subcategory</a></li>
           <li><a>4th subcategory</a></li>
           <li><a>5th subcategory</a></li>
           <li><a>6th subcategory</a></li>
        </ul>
    <div>
</div>
</code>```

what i want to achieve is after the 3rd subcategory, it should break and continue on a new column, so that i can get something like this;

```<code><div class="row">
    <div class="col-md-6">
        <ul>
           <li><a>1st subcategory</a></li>
           <li><a>2nd subcategory</a></li>
           <li><a>3rd subcategory</a></li>
        </ul>
    <div>

    <div class="col-md-6">
        <ul>
           <li><a>4th subcategory</a></li>
           <li><a>5th subcategory</a></li>
           <li><a>6th subcategory</a></li>
        </ul>
    <div>
</div>
</code>```

How can i achieve this? Thanks for your help in advance

答:
You need to emit the inner

 and the

 part every three categories.

Here is the pseudocode:

Emit

Set a counter, something like $i = 0

Start your for loop, foreach ($subCat_of_parent as $subcat) {

Now say if ($i == 0), emit the start div tag and start ul tag.

Emit your list item

$i = ($i + 1) % 3

Now say if ($i == 0), emit the close ul tag and close div tag.

If the number of subcategories is not a multiple of three, you need extra logic at the end to make sure the last group is properly closed off.

Body:
I'm working on a Mega Menu for WooCommerce Product Category. I'm able to get the list of all Subcategories using the code below;

$parent_id = 37; //ID of the Parent Category
$subCat_of_parent = get_terms('product_cat',array('child_of' => $parent_id));

Then used in a html structure as below;

        <?php
        foreach ($subCat_of_parent as $subcat) {
            ?>

                <a href="<?php echo get_category_link($subcat->term_id); ?>"><?php echo $subcat->name; ?>

            <?php
        }
         ?>

This worked by getting all the list of subcategory of the parent category in this format;

1st subcategory

2nd subcategory

3rd subcategory

4th subcategory

5th subcategory

6th subcategory

what i want to achieve is after the 3rd subcategory, it should break and continue on a new column, so that i can get something like this;

1st subcategory

2nd subcategory

3rd subcategory

4th subcategory

5th subcategory

6th subcategory

How can i achieve this? Thanks for your help in advance

Body:
You need to emit the inner <div class="col-md-6"><ul> and the </ul></div> part every three categories.

Here is the pseudocode:

Emit <div class="row">

Set a counter, something like $i = 0

Start your for loop, foreach ($subCat_of_parent as $subcat) {

Now say if ($i == 0), emit the start div tag and start ul tag.

Emit your list item

$i = ($i + 1) % 3

Now say if ($i == 0), emit the close ul tag and close div tag.

If the number of subcategories is not a multiple of three, you need extra logic at the end to make sure the last group is properly closed off.


问:
C++ where I'll need local extension or foreign method?
I'm not familiar with C++ enough to know where those 2 very similar refactorings (introduce local extension and introduce foreign method) will be needed. I know cases that forces to use those, but I can't figure sample classes that will need this "trick". I'm making C++ refactoring tutorial, to help new developers, but it looks like I need yours help too :)

If you used it, please tell me in where and why. Thanks in advance.

答:
"Foreign" methods are methods that operate on, but aren't members of a class. In Java, that just means (static) methods of other classes that take the first class as an argument. In C++, you'll need to be aware of free functions. Unlike Java , in C++ methods can exist outside classes. int main() is the most famous one. The STL is also packed with free functions. Just have a peek in  alone.

For Java, the site you linked advises that "foreign methods are a work-around"  and suggest "Introduce Local Extension" as a alternative refactoring. In C++, free functions are not a work-around. That means there's much less pressure to introduce local extensions.

Furthermore, in C++ functions are not virtual by default, and objects are often passed by value. This means that the "introduce local extensions" technique often fails.

I hope this goes to show the fundamental problem with your approach: you're taking refactoring techniques for Java, which address specific Java weaknesses, and try to convert them into C++ which has a rather different set of weaknesses. Even where it works, it's often unnecessary.


问:
I am trying to store current date and time in asyncstorage, but the return value I get is a promise and I can't see the values
I tried passing the values as Json (key-pair values) but I don't get to to see the values in response.</p>

答:
If you want to get value directly in a variable then you should use Async/await

then in your code you can get data like this

```<code>let data = await AsyncStorage.getItem('data');
</code>```

to convert data to json

```<code>jsonData = JSON.parse(data);
</code>```

Body:
If you want to get value directly in a variable then you should use Async/await

then in your code you can get data like this

let data = await AsyncStorage.getItem('data');

to convert data to json

jsonData = JSON.parse(data);


问:
Maven Exception NoClassDefFoundError ClassNotFoundException but Maven Dependency Exists Command Line
I am having a problem with maven. I have included a dependency as such in my pom.xml:

```<code><dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-csv</artifactId>
  <version>1.6</version>
</dependency>
</code>```

I am using Intellij as an IDE, and I get no compile warnings there or anything. I am using the command line to run the maven commands, and I can run mvn install compile package all without trouble.

However, when I try running the jar as such:

```<code>java -cp target/stride-1.0-SNAPSHOT.jar com.myapp.maven.App
</code>```

I get this error:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/csv/CSVFormat
    at com.stride.maven.App.parseCsv(App.java:43)
    at com.stride.maven.App.main(App.java:25)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.csv.CSVFormat
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
</code>```

Clearly, maven cannot find that path. I tried deleting the .m2, rebuilding, and mostly everything I have found on stackoverflow, but I cannot find the issue, or get visibility into the issue. Note, in my Intellij I can see the dependency in the external libraries.

I have also tried using shade to copy the dependancies to the jar:

```<code>    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-shade-plugin</artifactId>
      <executions>
        <execution>
          <goals>
            <goal>shade</goal>
          </goals>
          <configuration>
            <shadedArtifactAttached>true</shadedArtifactAttached>
            <transformers>
              <transformer implementation=
                                   "org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                <mainClass>com.myapp.maven.App</mainClass>
              </transformer>
            </transformers>
          </configuration>
        </execution>
      </executions>
    </plugin>
</code>```

Following which I reran mvn clean install package and then my build command. No luck.

I have also tried Maven Assembly plugin. Guess what, no luck!

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
            <configuration>
                <archive>
                <manifest>
                    <mainClass>
                        com.myapp.maven.App
                    </mainClass>
                </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

I confirmed the dependencies are not even getting built in.

Thanks!

答:
Maven works great in this case.
However, you seem to miss the point of dependency.

When you define a dependency maven uses it during the compilation (hence no errors in both intelliJ and when you execute mvn install)

But this doesn't mean that dependency is placed right into the jar.

There are more complicated packaging types of application where it indeed works like this (dependant jars are included into the artifact) for example Spring boot application, Web Archives (WAR) and so forth. But since you compile a regular JAR it will include only the classes of your module and won't include classes of commons-csv in this case.

So in order to be able to run this application you should chose one of:

Put Jar of commons-csv (as well as other dependencies that you might have) into class path: java -classpath <path-to-commons-csv> -jar YourApp

Use Maven Shade Plugin to create a jar that will indeed include all the dependencies as classes

Body:
I am having a problem with maven. I have included a dependency as such in my pom.xml:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-csv</artifactId>
  <version>1.6</version>
</dependency>

I am using Intellij as an IDE, and I get no compile warnings there or anything. I am using the command line to run the maven commands, and I can run mvn install compile package all without trouble.

However, when I try running the jar as such:

java -cp target/stride-1.0-SNAPSHOT.jar com.myapp.maven.App

I get this error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/csv/CSVFormat
    at com.stride.maven.App.parseCsv(App.java:43)
    at com.stride.maven.App.main(App.java:25)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.csv.CSVFormat
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Clearly, maven cannot find that path. I tried deleting the .m2, rebuilding, and mostly everything I have found on stackoverflow, but I cannot find the issue, or get visibility into the issue. Note, in my Intellij I can see the dependency in the external libraries.

I have also tried using shade to copy the dependancies to the jar:

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-shade-plugin</artifactId>
      <executions>
        <execution>
          <goals>
            <goal>shade</goal>
          </goals>
          <configuration>
            <shadedArtifactAttached>true</shadedArtifactAttached>
            <transformers>
              <transformer implementation=
                                   "org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                <mainClass>com.myapp.maven.App</mainClass>
              </transformer>
            </transformers>
          </configuration>
        </execution>
      </executions>
    </plugin>

Following which I reran mvn clean install package and then my build command. No luck.

I have also tried Maven Assembly plugin. Guess what, no luck!

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
            <configuration>
                <archive>
                <manifest>
                    <mainClass>
                        com.myapp.maven.App
                    </mainClass>
                </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </execution>
    </executions>
</plugin>

I confirmed the dependencies are not even getting built in.

Thanks!


问:
How do I deal with "An attempt has been made to free an RCW that is in use. " Error
I know this question might be duplicate questions but I have a problem and need a solution to overcome it.

I've made a project and used functions and Sub everywhere.

One of the function/Sub is like,

```<code>Public Sub ExecuteQuery(Xcn As OleDbConnection)
    Try
        If Xcn.State = ConnectionState.Open Then Xcn.Close()
        Xcn.Open()
        cmd.Connection = Xcn
        cmd.ExecuteNonQuery()
        Xcn.Close()
    Catch e As Exception
        Throw e
    End Try
End Sub
</code>```

I just use executequery(con) instead of writing whole sentence everytime.

Now the question is that I created a bw_worker and running a sub that includes small subs like I showed above asynchronously.

For example, A sub is that I run async like,

```<code>Private Sub RunCode()
    dim cmd as new oledbcommand("Select * from table",con)
    if con.state = ConnectionState.closed then con.open()
    execute reader stuff here
    if con.state = ConnectionState.Open then con.close()
    ExecuteQuery(con)
    cmd = new Oledbcommand("Select * from Table2",con)
    ExecuteQuery(con)
End Sub
</code>```

I don't know if its good practice or not but now problem arises.

I am trying to create a loading screen for some time taking functions and subs so I referred this Link and faced the error.

NOTE: I understood the error it gives but I want to know a workaround if possible. Like something possible without changing a lot of code.

答:
If you keep your database objects local they won't be open on another thread. Commands too. This code will demonstrate how to use Using blocks which will close and dispose of your database objects even if there is an error. Please no .AddWithValue. The .Add method forces you to name a datatype which will help with visually providing a clue that the datatype passed in matches. There are also several database reasons to use .Add. See https://www.dbdelta.com/addwithvalue-is-evil/  and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

It is okay to have a class level variable for the connection string so you don't have to type it all the time.

```<code>Private ConnString As String = "Your connection string"

Private Sub RunCode()
    Using con As New OleDbConnection(ConnString)
        Using cmd As New OleDbCommand("Select * from table", con)
            con.Open()
            Using reader = cmd.ExecuteReader
                'reader stuff here
            End Using
        End Using
    End Using
End Sub
</code>```

Body:
I know this question might be duplicate questions but I have a problem and need a solution to overcome it.

I've made a project and used functions and Sub everywhere.

One of the function/Sub is like,

Public Sub ExecuteQuery(Xcn As OleDbConnection)
    Try
        If Xcn.State = ConnectionState.Open Then Xcn.Close()
        Xcn.Open()
        cmd.Connection = Xcn
        cmd.ExecuteNonQuery()
        Xcn.Close()
    Catch e As Exception
        Throw e
    End Try
End Sub

I just use executequery(con) instead of writing whole sentence everytime.

Now the question is that I created a bw_worker and running a sub that includes small subs like I showed above asynchronously.

For example, A sub is that I run async like,

Private Sub RunCode()
    dim cmd as new oledbcommand("Select * from table",con)
    if con.state = ConnectionState.closed then con.open()
    execute reader stuff here
    if con.state = ConnectionState.Open then con.close()
    ExecuteQuery(con)
    cmd = new Oledbcommand("Select * from Table2",con)
    ExecuteQuery(con)
End Sub

I don't know if its good practice or not but now problem arises.

I am trying to create a loading screen for some time taking functions and subs so I referred this Link and faced the error.

NOTE: I understood the error it gives but I want to know a workaround if possible. Like something possible without changing a lot of code.

Body:
If you keep your database objects local they won't be open on another thread. Commands too. This code will demonstrate how to use Using blocks which will close and dispose of your database objects even if there is an error. Please no .AddWithValue. The .Add method forces you to name a datatype which will help with visually providing a clue that the datatype passed in matches. There are also several database reasons to use .Add. See https://www.dbdelta.com/addwithvalue-is-evil/  and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

It is okay to have a class level variable for the connection string so you don't have to type it all the time.

Private ConnString As String = "Your connection string"

Private Sub RunCode()
    Using con As New OleDbConnection(ConnString)
        Using cmd As New OleDbCommand("Select * from table", con)
            con.Open()
            Using reader = cmd.ExecuteReader
                'reader stuff here
            End Using
        End Using
    End Using
End Sub


问:
Display Park Name and Time outside Loop
How do I display the parkName and time outside the for loop?

for(int i=1; i<=5; i++) {
    System.out.print("\n\nEnter park name: ");
    String parkName = input.nextLine();

    System.out.print("Enter run time: ");
    String runTime = input.nextLine();

    //convert to double the user input which was a string
    //create new variable for time as double

    Double time = Double.parseDouble(runTime);
    parkRunner.recordNewRuns(parkName, time);
}
```

答:
One way of doing that is store the records in a Map inside your recordNewRuns method and print the map at the end.

```<code>public class ParkRunner {

    static Map<String, Double> map = new HashMap();

    public static void recordNewRuns(String parkName, double time) {
        map.put(parkName, time);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 1; i <= 5; i++) {

            System.out.print("\n\nEnter park name: ");
            String parkName = input.nextLine();

            System.out.print("Enter run time: ");
            String runTime = input.nextLine();

            // convert to double the user input which was a string
            // create new variable for time as double

            Double time = Double.parseDouble(runTime);

            ParkRunner.recordNewRuns(parkName, time);
        }

        System.out.println(map);

        input.close();
    }
}
</code>```

Title: Display Park Name and Time outside Loop

Body:
One way of doing that is store the records in a Map inside your recordNewRuns method and print the map at the end.

public class ParkRunner {

    static Map<String, Double> map = new HashMap();

    public static void recordNewRuns(String parkName, double time) {
        map.put(parkName, time);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 1; i <= 5; i++) {

            System.out.print("\n\nEnter park name: ");
            String parkName = input.nextLine();

            System.out.print("Enter run time: ");
            String runTime = input.nextLine();

            // convert to double the user input which was a string
            // create new variable for time as double

            Double time = Double.parseDouble(runTime);

            ParkRunner.recordNewRuns(parkName, time);
        }

        System.out.println(map);

        input.close();
    }
}


问:
How to simplify the way I wrote the NgFor script?
I am trying to put the array list to one dialog.

In the dialog, When I pull the array out through NgFor, the way I wrote looks so stupid

is there any way to optimize the script?

Putting the data in Mother Page

```<code>  const dialogRef = this.dialog.open(NationalityDailogComponent, dialogConfig).afterClosed()
  .subscribe( data => {
    this.selectNationality = data;
            console.log(this.selectNationality);
  });
</code>```

Getting the data in Dialog Page

```<code>ngOnInit() {
    this.NationlityList = this.passedData;
}
</code>```

Extract the data

```<code><div *ngFor="let item of NationlityList.NationlityList; let i = index">
  <div *ngIf="i % 6 == 0" class="row">
      <mat-checkbox *ngIf="i + 0 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i].Nationality)"> {{ NationlityList.NationlityList[i].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 1 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+1].Nationality)"> {{ NationlityList.NationlityList[i+1].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 2 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+2].Nationality)"> {{ NationlityList.NationlityList[i+2].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 3 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+3].Nationality)"> {{ NationlityList.NationlityList[i+3].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 4 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+4].Nationality)"> {{ NationlityList.NationlityList[i+4].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 5 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+5].Nationality)"> {{ NationlityList.NationlityList[i+5].Nationality }} </mat-checkbox>
  </div>
</div>
</code>```

In component, I did replace the 'NationlityList.NationlityList' in mat-checkbox with the 'item' but it's not work.

答:
A few things I see missing here (and it could be you have it but just didn't paste it into the snippet):

MAT_DIALOG_DATA isn't injected into the dialog component.

Once the data is injected, since it looks like you're passing in an object of type MatDialogConfig, you'd need to access the data from the config via the "data" property. I.e. this.NationlityList = this.passedData.data;

Lastly, and a minor thing, since you're subscribing here, you no longer have a dialogReference and instead have a subscription.

const dialogRef = this.dialog.open(NationalityDailogComponent,
      dialogConfig).afterClosed()
  .subscribe( data => {
    this.selectNationality = data;
            console.log(this.selectNationality);
  });

Body:
I am trying to put the array list to one dialog.

In the dialog, When I pull the array out through NgFor, the way I wrote looks so stupid

is there any way to optimize the script?

Putting the data in Mother Page

  const dialogRef = this.dialog.open(NationalityDailogComponent, dialogConfig).afterClosed()
  .subscribe( data => {
    this.selectNationality = data;
            console.log(this.selectNationality);
  });

Getting the data in Dialog Page

ngOnInit() {
    this.NationlityList = this.passedData;
}

Extract the data

      <mat-checkbox *ngIf="i + 0 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i].Nationality)"> {{ NationlityList.NationlityList[i].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 1 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+1].Nationality)"> {{ NationlityList.NationlityList[i+1].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 2 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+2].Nationality)"> {{ NationlityList.NationlityList[i+2].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 3 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+3].Nationality)"> {{ NationlityList.NationlityList[i+3].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 4 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+4].Nationality)"> {{ NationlityList.NationlityList[i+4].Nationality }} </mat-checkbox>
      <mat-checkbox *ngIf="i + 5 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+5].Nationality)"> {{ NationlityList.NationlityList[i+5].Nationality }} </mat-checkbox>

In component, I did replace the 'NationlityList.NationlityList' in mat-checkbox with the 'item' but it's not work.


问:
Need a matrix with counts of intersecting values
I have a data frame which looks like this:

```<code>Fruit    Colour
Apple      Red
Apple      Green
Cherry     Red
Lemon      Yellow
Banana     Yellow
Blueberry  Purple
Grapes     Purple
Grapes     Green
</code>```

And would like a matrix which looks like this:

```<code>           Apple    Cherry    Lemon    Banana    Blueberry    Grapes
Apple       0         1         0         0         0            1
Cherry      1         0         0         0         0            0
Lemon       0         0         0         1         0            0
Banana      0         0         1         0         0            0
Blueberry   0         0         0         0         0            1
Grapes      1         0         0         0         1            0
</code>```

Corresponding to a the number of shared values between the rows in the colour column.

I've tried something like this:

```<code>df1 <- dcast(fruit_frame, Fruit~Colour)
</code>```

Which gives me a dataframe with the colour as the columns and fruit as rows and number of occurrences of each colour but it isn't quite what I am looking for. Is there an easy way to do this in R or python?

Thanks you in advance.

答:
An option in R would be

```<code>out <- tcrossprod(table(fruit_frame))
diag(out) <- 0
</code>```

Body:
I have a data frame which looks like this:

Fruit    Colour
Apple      Red
Apple      Green
Cherry     Red
Lemon      Yellow
Banana     Yellow
Blueberry  Purple
Grapes     Purple
Grapes     Green

And would like a matrix which looks like this:

           Apple    Cherry    Lemon    Banana    Blueberry    Grapes
Apple       0         1         0         0         0            1
Cherry      1         0         0         0         0            0
Lemon       0         0         0         1         0            0
Banana      0         0         1         0         0            0
Blueberry   0         0         0         0         0            1
Grapes      1         0         0         0         1            0

Corresponding to a the number of shared values between the rows in the colour column.

I've tried something like this:

df1 <- dcast(fruit_frame, Fruit~Colour)

Which gives me a dataframe with the colour as the columns and fruit as rows and number of occurrences of each colour but it isn't quite what I am looking for. Is there an easy way to do this in R or python?

Thanks you in advance.

Body:
An option in R would be

out <- tcrossprod(table(fruit_frame))
diag(out) <- 0


问:
Android Sqlite INSERT error when table contains only _id
I have a SQLite table that contains only the _id:

```<code>"create table rule (_id integer primary key);";
</code>```

When running this set of commands:

```<code>ContentValues initialValues = new ContentValues();
mDb.insert(TABLE, null, initialValues)
</code>```

I obtain the following exception:

```<code>android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO rule(null) VALUES (NULL)
</code>```

The initial error occurs because ContentValues cannot be empty. Android provides a convenience parameter called nullColumnHack that allows you to pass a single column with the value null, to bypass this problem.

However this doesn't apply in my case because the row id (_id) cannot be null! Based on the syntax found in the SQLite language docs, I would like to be able to run the SQLite code:

```<code>INSERT INTO rule DEFAULT VALUES;
</code>```

How can i achieve something like this using the android insert method? Or is there something I need to add to my create statement?

UPDATE: In the situation where a table contains ONLY a rowid, the proper syntax is to use INSERT INTO __ DEFAULT VALUES.

The sqlite insert method listed in android does not support DEFAULT VALUES as an option.

A bug has been filed with google and to get support for default values the following commands would need to be executed:

```<code>mDb.execSQL("INSERT INTO rule DEFAULT VALUES;");
Cursor c = mDb.rawQuery("SELECT last_insert_rowid()",null);
c.moveToFirst();
int rowid = c.getInt(0);
</code>```

As stated in the accepted answer, we can get around this (and DEFAULT VALUES) by using nullHackColumn and assigning the row id (_id) to null and letting SQLite make the conversion from null to the auto-incremented value.

答:
the insert needs a null value you just have to put</p>

```<code>db.insert ("people", null, c);
</code>```

Body:
I have a SQLite table that contains only the _id:

"create table rule (_id integer primary key);";

When running this set of commands:

ContentValues initialValues = new ContentValues();
mDb.insert(TABLE, null, initialValues)

I obtain the following exception:

android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO rule(null) VALUES (NULL)

The initial error occurs because ContentValues cannot be empty. Android provides a convenience parameter called nullColumnHack that allows you to pass a single column with the value null, to bypass this problem.

However this doesn't apply in my case because the row id (_id) cannot be null! Based on the syntax found in the SQLite language docs, I would like to be able to run the SQLite code:

INSERT INTO rule DEFAULT VALUES;

How can i achieve something like this using the android insert method? Or is there something I need to add to my create statement?

UPDATE: In the situation where a table contains ONLY a rowid, the proper syntax is to use INSERT INTO __ DEFAULT VALUES.

The sqlite insert method listed in android does not support DEFAULT VALUES as an option.

A bug has been filed with google and to get support for default values the following commands would need to be executed:

mDb.execSQL("INSERT INTO rule DEFAULT VALUES;");
Cursor c = mDb.rawQuery("SELECT last_insert_rowid()",null);
c.moveToFirst();
int rowid = c.getInt(0);

As stated in the accepted answer, we can get around this (and DEFAULT VALUES) by using nullHackColumn and assigning the row id (_id) to null and letting SQLite make the conversion from null to the auto-incremented value.

Body:
the insert needs a null value you just have to put

db.insert ("people", null, c);


问:
Validation of result before executing the query
When running a stored procedure to fetch some rows, First I want to validate if the query will return a row before sending the result, and second if it is possible to validate without running the same query twice.

I am using a cursor to store the yielded result, So I tried the cursor attribute %ROWCOUNT & %NOTFOUND. But the doesnt quite work. Plus I want to do this without running a loop on the cursor.

```<code>procedure MODULE_LIST_GK(p_module_Id IN MODULE_LIST.MODULE_ID% TYPE,
                                     p_Error_Code     out nvarchar2,
                                     p_Error_Msg      out nvarchar2,
                                     p_Cursor         out sys_refcursor)   IS
 BEGIN
    OPEN p_Cursor FOR
       SELECT A.MODULE_ID,
         A.MODULE_NM,
         A.AUTH_STATUS_ID
         FROM MODULE_LIST A
         WHERE A.MODULE_ID=p_module_Id;

       SELECT COUNT(MODULE_ID)
       INTO v_row_num
        FROM MODULE_LIST A
        WHERE A.MODULE_ID=p_module_Id;

       IF v_row_num=0 THEN
         p_Error_Code := SQLCODE;
         p_Error_Msg := 'Does not Exists';
         Return;
       end IF;
    EXCEPTION
      WHEN OTHERS THEN
        p_error_code:= SQLCODE;
        p_error_msg := SQLERRM;
  END MODULE_LIST_GK;
</code>```

答:
Your implementation have several points that could be improved.

First if you expect that for lot of parameters the returned cursor will be empty,
than first check the empty cursor and only after this check open the cursor. You do it vice versa.

How to check if the cursor is empty? Unfortunatelly you must fetch the first row to be able to verify it.

```<code> open l_cur for
   select id, status from tab where id = p_id;
 fetch l_cur into l_id, l_status;
 if l_cur%NOTFOUND then
    p_Error_Msg := 'Does not Exists';
    Return;
 end if;
</code>```

This check is far more effective that the often used count(*) as it is considering only the first (few) rows and not counting all rows in the cursor.

If the check fails you are ready, othervise simple open the cursor and return it.

```<code> open  l_cur for
   select id, status from tab where id = p_id;
   p_Cursor := l_cur;
</code>```

Two additional thinks come to mind.

You should rething the generall approach if the database is very dynamic. How would you handle the case when other session deletes some row between the check and the second open of the cursor?

Finally consider returning an exception instead of the return code.

Body:
When running a stored procedure to fetch some rows, First I want to validate if the query will return a row before sending the result, and second if it is possible to validate without running the same query twice.

I am using a cursor to store the yielded result, So I tried the cursor attribute %ROWCOUNT & %NOTFOUND. But the doesnt quite work. Plus I want to do this without running a loop on the cursor.

procedure MODULE_LIST_GK(p_module_Id IN MODULE_LIST.MODULE_ID% TYPE,
                                     p_Error_Code     out nvarchar2,
                                     p_Error_Msg      out nvarchar2,
                                     p_Cursor         out sys_refcursor)   IS
 BEGIN
    OPEN p_Cursor FOR
       SELECT A.MODULE_ID,
         A.MODULE_NM,
         A.AUTH_STATUS_ID
         FROM MODULE_LIST A
         WHERE A.MODULE_ID=p_module_Id;

       SELECT COUNT(MODULE_ID)
       INTO v_row_num
        FROM MODULE_LIST A
        WHERE A.MODULE_ID=p_module_Id;

       IF v_row_num=0 THEN
         p_Error_Code := SQLCODE;
         p_Error_Msg := 'Does not Exists';
         Return;
       end IF;
    EXCEPTION
      WHEN OTHERS THEN
        p_error_code:= SQLCODE;
        p_error_msg := SQLERRM;
  END MODULE_LIST_GK;

Body:
Your implementation have several points that could be improved.

First if you expect that for lot of parameters the returned cursor will be empty,
than first check the empty cursor and only after this check open the cursor. You do it vice versa.

How to check if the cursor is empty? Unfortunatelly you must fetch the first row to be able to verify it.

 open l_cur for
   select id, status from tab where id = p_id;
 fetch l_cur into l_id, l_status;
 if l_cur%NOTFOUND then
    p_Error_Msg := 'Does not Exists';
    Return;
 end if;

This check is far more effective that the often used count(*) as it is considering only the first (few) rows and not counting all rows in the cursor.

If the check fails you are ready, othervise simple open the cursor and return it.

 open  l_cur for
   select id, status from tab where id = p_id;
   p_Cursor := l_cur;

Two additional thinks come to mind.

You should rething the generall approach if the database is very dynamic. How would you handle the case when other session deletes some row between the check and the second open of the cursor?

Finally consider returning an exception instead of the return code.