问:
Check if devices has biometric enabled with androidx biometric prompt
In Android BiometricPrompt prompt has replaced the deprecated FingerprintManager.
FingerPrintManager has two functions hasEnrolledFingerprints() and isHardwareDetected() to check if the device supports fingerprints and if the user has enrolled any fingerprint authentication.

With the new BiometricPrompt it seems there are no functions to check this without trying to prompt the BiometricPrompt. There is a BiometricPrompt.AuthenticationCallback.onAuthenticationError( that is called with an error code indicating if the device supports biometric and if the user has biometric authentication enrolled.

So I can only get this information if I try to authenticate from the user. Is there a way to check without trying to prompt the authentication to check if the device supports biometrics and the user has enrolled them?

答:
Use BiometricManager it has a method

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

it returns

```<code>BIOMETRIC_ERROR_NONE_ENROLLED if the user does not have any enrolled
BIOMETRIC_ERROR_HW_UNAVAILABLE if none are currently supported/enabled
BIOMETRIC_SUCCESS if a biometric can currently be used (enrolled and available)
BIOMETRIC_ERROR_NO_HARDWARE
</code>```

Check out the official documentation https://developer.android.com/reference/android/hardware/biometrics/BiometricManager.html

Body:
Use BiometricManager it has a method

canAuthenticate()

it returns

BIOMETRIC_ERROR_NONE_ENROLLED if the user does not have any enrolled
BIOMETRIC_ERROR_HW_UNAVAILABLE if none are currently supported/enabled
BIOMETRIC_SUCCESS if a biometric can currently be used (enrolled and available)
BIOMETRIC_ERROR_NO_HARDWARE

Check out the official documentation https://developer.android.com/reference/android/hardware/biometrics/BiometricManager.html


来源: stackexchange

问:
No provider for Facebook (Ionic Native)

ERROR Error: No provider for Facebook!

           &nbspat injectionError (core.es5.js:1231)

           &nbspat noProviderError (core.es5.js:1269)

           &nbspat ReflectiveInjector_.throwOrNull (core.es5.js:2770)

           &nbspat ReflectiveInjector.getByKeyDefault (core.es5.js:2809)

           &nbspat ReflectiveInjector.getByKey (core.es5.js:2741)

           &nbspat ReflectiveInjector.get (core.es5.js:2610)

           &nbspat AppModuleInjector.NgModuleInjector.get (core.es5.js:3578)

           &nbspat resolveDep (core.es5.js:11039)

           &nbspat createClass (core.es5.js:10903)

           at createDirectiveInstance (core.es5.js:10723)
 View_MyApp_Host_0 @ MyApp_Host.html:1

答:
Selected answer works till Ionic3. For Ionic 4+:
In whichever module has the component that uses FB login, add:

```<code>import { Facebook } from '@ionic-native/facebook/ngx';
</code>```

[Note the /ngx]

and add the provider for that @NgModule

```<code>providers: [ Facebook, .... ]
</code>```

ContentLicense: CC BY-SA 3.0

Title: No provider for Facebook (Ionic Native)

Body:
Selected answer works till Ionic3. For Ionic 4+:
In whichever module has the component that uses FB login, add:

import { Facebook } from '@ionic-native/facebook/ngx';

[Note the /ngx]

and add the provider for that @NgModule

providers: [ Facebook, .... ]

ContentLicense: CC BY-SA 4.0


问:
Imageview won't show image with piccsso if the image is in HTTP format
I am using Picasso to inflate image from URL to Imageview:

```<code>
@Override
    public void onBindViewHolder(@NonNull HeroesViewHolder holder, int position) {

        Hero currentHero = heroList.get(position);
        String str = String.join(",", currentHero.abilities);

        holder.heroTitle.setText(currentHero.title);
        holder.heroAbilities.setText(str);
        Picasso.get().load(currentHero.image).resize(500, 500).into(holder.heroesImage);

    }

</code>```

The thing is that everything that is HTTP protocol won't show up at emulator & physical device, only the ones that are HTTPS. Instead of showing it, it just leaves a black space.

The images that are HTTP protocol are also .png extension, if that has anything to do with that.

how can I workaround this issue?

答:
Try this </p>

```<code>Picasso.with(getApplicationContext())
     .load(img_url)
     .resize(5,5)
     .fit().centerCrop().into(methodImage);
</code>```

Body:
I am using Picasso to inflate image from URL to Imageview:

@Override
    public void onBindViewHolder(@NonNull HeroesViewHolder holder, int position) {

        Hero currentHero = heroList.get(position);
        String str = String.join(",", currentHero.abilities);

        holder.heroTitle.setText(currentHero.title);
        holder.heroAbilities.setText(str);
        Picasso.get().load(currentHero.image).resize(500, 500).into(holder.heroesImage);

    }

The thing is that everything that is HTTP protocol won't show up at emulator & physical device, only the ones that are HTTPS. Instead of showing it, it just leaves a black space.

The images that are HTTP protocol are also .png extension, if that has anything to do with that.

how can I workaround this issue?

Body:
Try this

Picasso.with(getApplicationContext())
     .load(img_url)
     .resize(5,5)
     .fit().centerCrop().into(methodImage);


问:
How to only add specific value to a column?
How do I make sure it only concat one value once it already got value?
For example is the message already got the text "cat", how do I make the "dog" doesnt include?</p>

```<code>SELECT name, message,

concat(

if(message like '%cat%', 'cat', ''),
if(message like '%dog%', 'dog', ''),
) as intent

FROM table;
</code>```

答:
Use a CASE expression:

```<code>SELECT
    name,
    message,
    CASE WHEN message LIKE '%cat%' THEN 'cat'
         WHEN message LIKE '%dog%' THEN 'dog' END AS intent
FROM yourTable;
</code>```

Body:
How do I make sure it only concat one value once it already got value?
For example is the message already got the text "cat", how do I make the "dog" doesnt include?

SELECT name, message,

concat(

if(message like '%cat%', 'cat', ''),
if(message like '%dog%', 'dog', ''),
) as intent

FROM table;

Body:
Use a CASE expression:

SELECT
    name,
    message,
    CASE WHEN message LIKE '%cat%' THEN 'cat'
         WHEN message LIKE '%dog%' THEN 'dog' END AS intent
FROM yourTable;


问:
Cannot pass idpHint option to Keycloak
I am using IDP provider for authentication and trying to bypass the standard keycloak login screen (so I need to go immediately to the IDP specific authorization screen). According to this documentation https://keycloak.gitbooks.io/server-adminstration-guide/content/topics/identity-broker/suggested.html we can simply provide idpHint for this. Though that doesn't work.

let keycloakAuth : any = new Keycloak('keycloak.json');
keycloakAuth.createLoginUrl({idpHint: 'ad-oidc'});

It failed with

Uncaught TypeError: Cannot read property 'redirectUri' of undefined
    at Keycloak.kc.createLoginUrl (keycloak-core.js:212)

As far as I understand that's because adapter is not created yet. So probably we need to pass this option sometimes later (but not sure at which phase).

I was able to do this only by hardcoding the idpHint inside of the keycloak-core.js itself temporarily. Looking forward to avoid this.

Thanks in advance.

答:
I solved the problem like this:

```<code>let kc = Keycloak('/backend/frontend.json');
let kcLogin = kc.login;
kc.login = (options) => {
  options.idpHint = 'some-hint';
  kcLogin(options);
};
kc.init({ onLoad: 'login-required' }).success((authenticated) => {
  console.log('Logged in!');
}});
</code>```

This way the very first login attempt already uses the hint. I somehow don't get, why there is no simple way to use the idpHint option, the inceptor is the only way I found to use it, without directly patching the keycloak.js file.

It would be perfect, if the Keycloak constructor just would accept an idpHint option.

Title: Cannot pass idpHint option to Keycloak

Body:
I solved the problem like this:

let kc = Keycloak('/backend/frontend.json');
let kcLogin = kc.login;
kc.login = (options) => {
  options.idpHint = 'some-hint';
  kcLogin(options);
};
kc.init({ onLoad: 'login-required' }).success((authenticated) => {
  console.log('Logged in!');
}});

This way the very first login attempt already uses the hint. I somehow don't get, why there is no simple way to use the idpHint option, the inceptor is the only way I found to use it, without directly patching the keycloak.js file.

It would be perfect, if the Keycloak constructor just would accept an idpHint option.


问:
What do terminal commands such as -v, -i, -f mean when you have them in a command?
This might be a generic question, but what do commands like -v, -f, -i mean when you have them in a command that is posted in the terminal? Where can I look up the command meaning? </p>

<p>Example commands would be: </p>

```<code>python file.py -v
sudo dpkg -i path/file
sudo apt-get install -f
</code>```

答:
These are simply the program arguments of the program or subprogram. You are able to find the information about these arguments in the help messages of the program.
For example, you can find apt-get install help message via simply typing apt-get install in the command line, or typing apt-get install --help. For unix commands, most have manuals and you can read them via man <command>.

Body:
This might be a generic question, but what do commands like -v, -f, -i mean when you have them in a command that is posted in the terminal? Where can I look up the command meaning?

Example commands would be:

python file.py -v
sudo dpkg -i path/file
sudo apt-get install -f


问:
Merge pandas datagrame on one key with overlapping columns, chose first non-empty
Take these two dataframes:

```<code>a = pd.DataFrame({'id': [1,2,3], 'some':[None, None, 1], 'else': [11,22,33]})
b = pd.DataFrame({'id':[3,4,5], 'some': [5,5,5], 'el': [333,444,555]})
</code>```

I want to merge them on the id column but as you can see the some column would overlap on id=3. That means that running a.merge(b, on='id', how='outer') results in this:

```<code>   id  some_x  else  some_y     el
0   1     NaN  11.0     NaN    NaN
1   2     NaN  22.0     NaN    NaN
2   3     1.0  33.0     5.0  333.0
3   4     NaN   NaN     5.0  444.0
4   5     NaN   NaN     5.0  555.0
</code>```

How can I have it just keep the some column with the first provided values i.e. 1 instead of 5 and no _x _y columns?

答:
I suspect you want one of two things: The simpler (but less likely) is that you just want the 'some' column from a, in which case you can simply drop some['b'] before the merge:

```<code>a.merge(b.drop('some', axis=1))
</code>```

Or, you want the value of a['some'] if its non-null, otherwise use b['some'], in which case you can use .fillna():

```<code>c = a.merge(b, on='id', how='outer')
c['some'] = c.some_x.fillna(c.some_y)
</code>```

Body:
Take these two dataframes:

a = pd.DataFrame({'id': [1,2,3], 'some':[None, None, 1], 'else': [11,22,33]})
b = pd.DataFrame({'id':[3,4,5], 'some': [5,5,5], 'el': [333,444,555]})

I want to merge them on the id column but as you can see the some column would overlap on id=3. That means that running a.merge(b, on='id', how='outer') results in this:

   id  some_x  else  some_y     el
0   1     NaN  11.0     NaN    NaN
1   2     NaN  22.0     NaN    NaN
2   3     1.0  33.0     5.0  333.0
3   4     NaN   NaN     5.0  444.0
4   5     NaN   NaN     5.0  555.0

How can I have it just keep the some column with the first provided values i.e. 1 instead of 5 and no _x _y columns?

Body:
I suspect you want one of two things: The simpler (but less likely) is that you just want the 'some' column from a, in which case you can simply drop some['b'] before the merge:

a.merge(b.drop('some', axis=1))

Or, you want the value of a['some'] if its non-null, otherwise use b['some'], in which case you can use .fillna():

c = a.merge(b, on='id', how='outer')
c['some'] = c.some_x.fillna(c.some_y)


问:
how to make a php server script response with some data from database to a python http request
I have a device that sends python http request to a server. I want to make a server side php response script that collect some data from a database and send back to the device in the form of json. I made the python http request. the scrip contains a json message (information about the device) how to make the server php to response with data from database (it should identify the device from http request that holds IP). I need to send some  configuration parameters(maximumCurrent, maximumVoltage) they are in a database (configDB) with table name (Parameters) with columns deviceIP, maximumCurrent, maximumVoltage. Any suggestions.
(I know php, but dont't know how to make it run automatically based on the http request. because I am planning to send more http request. so php script should response based on different requests )</p>

```<code>import requests
import urllib3
import json
import os
import time
import sys

#http Reques

url = 'http://someurl_to_server'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

while True:
    postMessage = '{"Info": {"deviceIP": {"IP" :12345}}}'
    response = requests.post(url, json=postMessage, headers=headers)

    try:
        decodedresponse = json.loads(response.text)

    except(ValueError, KeyError, TypeError):
        print("JSON Error")
~~~
</code>```

答:
Very basic variant:</p>

```<code><?php
if(!empty($_POST['json'])){
    $link = mysqli_connect("localhost", "my_user", "my_password", "my_db");

    if (!$link) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
    }

    if (mysqli_query($link, "INSERT INTO your_table('your_field') VALUES('".json_decode($_POST['json'])."')") {
        echo json_encode("Insert successfully.\n");
    }
    else{
        echo json_encode($_POST);
    }
    mysqli_close($link);
}
</code>```

Body:
I have a device that sends python http request to a server. I want to make a server side php response script that collect some data from a database and send back to the device in the form of json. I made the python http request. the scrip contains a json message (information about the device) how to make the server php to response with data from database (it should identify the device from http request that holds IP). I need to send some  configuration parameters(maximumCurrent, maximumVoltage) they are in a database (configDB) with table name (Parameters) with columns deviceIP, maximumCurrent, maximumVoltage. Any suggestions.
(I know php, but dont't know how to make it run automatically based on the http request. because I am planning to send more http request. so php script should response based on different requests )

import requests
import urllib3
import json
import os
import time
import sys

#http Reques

url = 'http://someurl_to_server'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

while True:
    postMessage = '{"Info": {"deviceIP": {"IP" :12345}}}'
    response = requests.post(url, json=postMessage, headers=headers)

    try:
        decodedresponse = json.loads(response.text)

    except(ValueError, KeyError, TypeError):
        print("JSON Error")
~~~

Body:
Very basic variant:

<?php
if(!empty($_POST['json'])){
    $link = mysqli_connect("localhost", "my_user", "my_password", "my_db");

    if (!$link) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
    }

    if (mysqli_query($link, "INSERT INTO your_table('your_field') VALUES('".json_decode($_POST['json'])."')") {
        echo json_encode("Insert successfully.\n");
    }
    else{
        echo json_encode($_POST);
    }
    mysqli_close($link);
}


问:
Why width style value not show in input?
I'm trying to take the width from the "demo" div and put it in the "input number" value. I can not figure out where I made a mistake...

function myFunction() {
    var element = document.getElementById("poster"),
    style = window.getComputedStyle(element),
    width = style.getPropertyValue('width');

  document.getElementById("demo").value = width;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<div id="poster" style="width:35px;height:45px;background-color:blue;"></div>

<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">

<button onclick="myFunction()" type="button">Click Me!</button>
 </code>```

答:
You need to convert your width to number because you use input number not text. Actually, your width is a string (35px).

function myFunction() {
    var element = document.getElementById("poster"),
    style = window.getComputedStyle(element),
    width = style.getPropertyValue('width');

  document.getElementById("demo").value = parseFloat(width);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="poster" style="width:35px;height:45px;background-color:blue;"></div>

<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">

<button onclick="myFunction()" type="button">Click Me!</button></code>```

Body:
I'm trying to take the width from the "demo" div and put it in the "input number" value. I can not figure out where I made a mistake...

function myFunction() {
    var element = document.getElementById("poster"),
    style = window.getComputedStyle(element),
    width = style.getPropertyValue('width');

  document.getElementById("demo").value = width;
}

<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">

<button onclick="myFunction()" type="button">Click Me!</button>

Body:
You need to convert your width to number because you use input number not text. Actually, your width is a string (35px).

function myFunction() {
    var element = document.getElementById("poster"),
    style = window.getComputedStyle(element),
    width = style.getPropertyValue('width');

  document.getElementById("demo").value = parseFloat(width);
}

<div id="poster" style="width:35px;height:45px;background-color:blue;"></div>

<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">

<button onclick="myFunction()" type="button">Click Me!</button>


问:
How to set onClickListener for items in a ListView (items of listview are generated dynamically by retreiving data from firebase)
Hi Iam trying to make a chatApp.Iam successful with initial steps like user authentication,registration.After a successfull login user gets a screen as shown in this image:

Now the list of users here are generated by following code:

```<code>ListView listView;
View view;
ArrayList<String> usernames = new ArrayList<>();
String name;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference();
DatabaseReference userRef = root.child("users");

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
   view = inflater.inflate(R.layout.fragment_users,container,false);
   listView =(ListView) view.findViewById(R.id.listView);
   final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (getContext(),android.R.layout.simple_list_item_1,usernames);
   listView.setAdapter(arrayAdapter);

   userRef.addChildEventListener(new ChildEventListener() {
     @Override
     public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
       String value = dataSnapshot.getValue().toString();
       try
       {
         JSONObject object = new JSONObject(value);
         name = object.getString("username");
       }
       catch(JSONException e)
       {
         e.printStackTrace();
       }

       usernames.add(name);
       arrayAdapter.notifyDataSetChanged();
     }

     @Override
     public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}

     @Override
     public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onCancelled(@NonNull DatabaseError databaseError) {}
  });

  return view;
}
</code>```

Now whenever user clicks on particular name I've to take him to a messageActivity(more precisely another activity). Please tell me how I can add onClickListeners or any other possible method to do this?

答:
Use onItemClickListener : </p>

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
      String selectedName = usernames.get(position);
      // Do what you want with username here

   }
});
</code>```

Body:
Hi Iam trying to make a chatApp.Iam successful with initial steps like user authentication,registration.After a successfull login user gets a screen as shown in this image:

Now the list of users here are generated by following code:

ListView listView;
View view;
ArrayList<String> usernames = new ArrayList<>();
String name;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference();
DatabaseReference userRef = root.child("users");

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
   view = inflater.inflate(R.layout.fragment_users,container,false);
   listView =(ListView) view.findViewById(R.id.listView);
   final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (getContext(),android.R.layout.simple_list_item_1,usernames);
   listView.setAdapter(arrayAdapter);

   userRef.addChildEventListener(new ChildEventListener() {
     @Override
     public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
       String value = dataSnapshot.getValue().toString();
       try
       {
         JSONObject object = new JSONObject(value);
         name = object.getString("username");
       }
       catch(JSONException e)
       {
         e.printStackTrace();
       }

       usernames.add(name);
       arrayAdapter.notifyDataSetChanged();
     }

     @Override
     public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}

     @Override
     public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onCancelled(@NonNull DatabaseError databaseError) {}
  });

  return view;
}

Now whenever user clicks on particular name I've to take him to a messageActivity(more precisely another activity). Please tell me how I can add onClickListeners or any other possible method to do this?

Body:
Use onItemClickListener :

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
      String selectedName = usernames.get(position);
      // Do what you want with username here

   }
});


问:
Do not download empty folders while downloading from SFTP server using Python
I got a code to download files recursively in Python on this site. This code also downloads empty directories on server also.

Please help me to modify this code so that it does not download empty directories from the server.

Code I have (based on Python pysftp get_r from Linux works fine on Linux but not on Windows):

```<code>import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
</code>```

答:
Try this</p>

```<code>import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    no_of_entries=0;
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:
                pass
            sub = get_r_portable(sftp, remotepath, localpath, preserve_mtime);
            if(sub==0):
                os.rmdir(localpath);
            else:
                no_of_entries+=sub;
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime);
            no_of_entries+=1;
    return no_of_entries;

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
</code>```

Body:
I got a code to download files recursively in Python on this site. This code also downloads empty directories on server also.

Please help me to modify this code so that it does not download empty directories from the server.

Code I have (based on Python pysftp get_r from Linux works fine on Linux but not on Windows):

import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)

Body:
Try this

import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    no_of_entries=0;
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:
                pass
            sub = get_r_portable(sftp, remotepath, localpath, preserve_mtime);
            if(sub==0):
                os.rmdir(localpath);
            else:
                no_of_entries+=sub;
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime);
            no_of_entries+=1;
    return no_of_entries;

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)


答:
You cas use DISTINCT to pick a value just once as below-</p>

```<code>SELECT group_concat(DISTINCT N)
FROM
(
    select 'Dog' N UNION ALL
    SELECT 'CAT' UNION ALL
    SELECT 'CAT'
)A
</code>```

Title: How to only add specific value to a column?

Body:
You cas use DISTINCT to pick a value just once as below-

SELECT group_concat(DISTINCT N)
FROM
(
    select 'Dog' N UNION ALL
    SELECT 'CAT' UNION ALL
    SELECT 'CAT'
)A


问:
How to fix 'WKWebViewManager.evaluateJavaScript is not a function
I'm working on a React Native app, from Expo. I ejected the project to ExpoKit and added react-native-wkwebview-reborn. I'm facing some issues with this library as always appear this error:

Here is my code:
ContentWebView.ios.js

```<code>render() {
return (
    <View style={styles.container}>
      <WKWebView
          ref={WEBVIEW_REF}
          sendCookies={true}
          style={styles.webview}
          source={{uri: this.props.url}}
          allowsLinkPreview={false}
          onMessage={(e) => this._handleMessage(e)}
          onNavigationStateChange={(e) => this._onNavigationStateChange(e)}
      />
</code>```

and here is where my app crashes :

```<code>_onNavigationStateChange(e) {
    this.refs[WEBVIEW_REF].evaluateJavaScript('window.postMessage({cookies: document.cookie}); clearInterval(window.myCartInterval); window.myCartInterval = setInterval(function(){window.postMessage({cookies: document.cookie});},5000);');
  }
</code>```

If you have any idea it would be so useful! Thanks

答: The function is named injectJavaScript in React Native</p>

Body:
I'm working on a React Native app, from Expo. I ejected the project to ExpoKit and added react-native-wkwebview-reborn. I'm facing some issues with this library as always appear this error:

Here is my code:
ContentWebView.ios.js

render() {
return (
    <View style={styles.container}>
      <WKWebView
          ref={WEBVIEW_REF}
          sendCookies={true}
          style={styles.webview}
          source={{uri: this.props.url}}
          allowsLinkPreview={false}
          onMessage={(e) => this._handleMessage(e)}
          onNavigationStateChange={(e) => this._onNavigationStateChange(e)}
      />

and here is where my app crashes :

_onNavigationStateChange(e) {
    this.refs[WEBVIEW_REF].evaluateJavaScript('window.postMessage({cookies: document.cookie}); clearInterval(window.myCartInterval); window.myCartInterval = setInterval(function(){window.postMessage({cookies: document.cookie});},5000);');
  }

If you have any idea it would be so useful! Thanks


问:
C# strange with DateTime
I got some strange result for:

```<code>Console.WriteLine(new DateTime(1296346155).ToString());
</code>```

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))

答:
The constructor for DateTime that accept long type is expecting ticks value, not seconds or even milliseconds, and not from 1/1/1970 like in other languages.

So 1296346155 ticks is 129 seconds.

Title: C# strange with DateTime

Body:
I got some strange result for:

Console.WriteLine(new DateTime(1296346155).ToString());

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))


问:
C# Updating a DataGridView/DataSource from MySQL
I'm writing a program that updates user accounts on a MySQL database.  The program is going to be used on multiple computers at once.

Currently I load the MySQL data into a DGV by this and refresh in a similar way;

```<code>mySqlDataAdapter = new MySqlDataAdapter("SELECT * FROM a_Users;", connection); // Query the database
DataSet DS = new DataSet(); // Create new DataSet
mySqlDataAdapter.Fill(DS); // Fill the Dataset with the information gathered above
dataGridView1.DataSource = DS.Tables[0]; // Set the dgv source to the newly created DataSet
</code>```

and when editing I get the DGV row to a DataRow, and then update the DGV by changing the DataRow like this (from another form);

```<code>DataRow dr = (dataGridView1.Rows[SelectedRow].DataBoundItem as DataRowView).Row; // Get the selected row to a new DataRow
dr["Phone Number"] = PhoneNumber_tb.Text;
</code>```

My problem is, I want to update the DGV with any new/modified rows from the MySQL database every xx seconds, and if modifying a row when this happens the DataRow is then Invalid as the above code re-makes the whole structure.

Is there a way to update the DGV or DGV DataSource and maintain the ability to use the DataRow I pulled for editing?
How can I update the Datasource with any changes from the MySQL database.

I have tried BindingSource and a whole bunch of other things I have googled.

I could find UserID in the DGV then update the row that way, if no answer is found here.

Currently when editing a user, if the DGV refreshes with the SQL Database my edit form will not update the DGV as the DataRow no longer exists where it was.

答:
This is what I am using, works nicely.
Only gets the rows that have been updated since we last checked.  Still using the example in the question to retrieve the Database initially</p>

```<code>mySqlDataAdapter = new MySqlDataAdapter("SELECT * FROM a_Users WHERE DTGModified > " + LastUpdated.ToString() + ";", connection); // Query the database
DataTable DT = new DataTable(); // Create new DataSet
mySqlDataAdapter.Fill(DT); // Fill the Dataset with the information gathered above
LastUpdated = DateTime.Now.ToString("yyyyMMddHHmmss"); // Save the time we retrieved the database

foreach (DataRow dr in (dataGridView1.DataSource as DataTable).Rows)
{
    foreach(DataRow DTdr in DT.Rows)
    {
        if (dr["ID"].ToString() != DTdr["ID"].ToString()) continue;

        dr.ItemArray = DTdr.ItemArray;
    }
}
</code>```

Body:
I'm writing a program that updates user accounts on a MySQL database.  The program is going to be used on multiple computers at once.

Currently I load the MySQL data into a DGV by this and refresh in a similar way;

mySqlDataAdapter = new MySqlDataAdapter("SELECT * FROM a_Users;", connection); // Query the database
DataSet DS = new DataSet(); // Create new DataSet
mySqlDataAdapter.Fill(DS); // Fill the Dataset with the information gathered above
dataGridView1.DataSource = DS.Tables[0]; // Set the dgv source to the newly created DataSet

and when editing I get the DGV row to a DataRow, and then update the DGV by changing the DataRow like this (from another form);

DataRow dr = (dataGridView1.Rows[SelectedRow].DataBoundItem as DataRowView).Row; // Get the selected row to a new DataRow
dr["Phone Number"] = PhoneNumber_tb.Text;

My problem is, I want to update the DGV with any new/modified rows from the MySQL database every xx seconds, and if modifying a row when this happens the DataRow is then Invalid as the above code re-makes the whole structure.

Is there a way to update the DGV or DGV DataSource and maintain the ability to use the DataRow I pulled for editing?
How can I update the Datasource with any changes from the MySQL database.

I have tried BindingSource and a whole bunch of other things I have googled.

I could find UserID in the DGV then update the row that way, if no answer is found here.

Currently when editing a user, if the DGV refreshes with the SQL Database my edit form will not update the DGV as the DataRow no longer exists where it was.

Body:
This is what I am using, works nicely.
Only gets the rows that have been updated since we last checked.  Still using the example in the question to retrieve the Database initially

mySqlDataAdapter = new MySqlDataAdapter("SELECT * FROM a_Users WHERE DTGModified > " + LastUpdated.ToString() + ";", connection); // Query the database
DataTable DT = new DataTable(); // Create new DataSet
mySqlDataAdapter.Fill(DT); // Fill the Dataset with the information gathered above
LastUpdated = DateTime.Now.ToString("yyyyMMddHHmmss"); // Save the time we retrieved the database

foreach (DataRow dr in (dataGridView1.DataSource as DataTable).Rows)
{
    foreach(DataRow DTdr in DT.Rows)
    {
        if (dr["ID"].ToString() != DTdr["ID"].ToString()) continue;

        dr.ItemArray = DTdr.ItemArray;
    }
}


问:
CloudCompare fails to launch with error: "QXcbConnection: Could not connect to display :0"
In the last week, CloudCompare has suddenly stopped launching. When trying to launch via desktop icon, nothing happens. When trying to launch via commandline (e.g. $ cloudcompare.CloudCompare) nothing happens and I get the following error:

```<code>QXcbConnection: Could not connect to display :0
Aborted (core dumped)
</code>```

Trying to launch CloudCompare with sudo/as root user returns a slightly different error message:

```<code>mkdir: cannot create directory '/run/user/0': Permission denied
QXcbConnection: Could not connect to display :0
</code>```

Having looked around Github, here and various other forums, this seems to be a problem that people have encountered with other programs that use Qt and/or OpenGL (see 1, 2, 3). I also realise that this isn't really enough information to debug the problem, so if there is any other diagnostic info I can/should provide, let me know and I will add it.

EDIT: I can actually get CloudCompare working again by completely uninstalling it and then re-installing it. However that doesn't explain the original problem or how to solve it.

My Environment

OS & Version: Ubuntu 14.04 LTS

CC Version: v2.8.1 (latest)

Graphics card: Intel Haswell Mobile

Qt version: 5.2.1

答:
I resolve this by installing qt5-default on ubuntu

```<code>sudo apt-get install qt5-default
</code>```

Body:
In the last week, CloudCompare has suddenly stopped launching. When trying to launch via desktop icon, nothing happens. When trying to launch via commandline (e.g. $ cloudcompare.CloudCompare) nothing happens and I get the following error:

QXcbConnection: Could not connect to display :0
Aborted (core dumped)

Trying to launch CloudCompare with sudo/as root user returns a slightly different error message:

mkdir: cannot create directory '/run/user/0': Permission denied
QXcbConnection: Could not connect to display :0

Having looked around Github, here and various other forums, this seems to be a problem that people have encountered with other programs that use Qt and/or OpenGL (see 1, 2, 3). I also realise that this isn't really enough information to debug the problem, so if there is any other diagnostic info I can/should provide, let me know and I will add it.

EDIT: I can actually get CloudCompare working again by completely uninstalling it and then re-installing it. However that doesn't explain the original problem or how to solve it.

My Environment

OS & Version: Ubuntu 14.04 LTS

CC Version: v2.8.1 (latest)

Graphics card: Intel Haswell Mobile

Qt version: 5.2.1

Body:
I resolve this by installing qt5-default on ubuntu

sudo apt-get install qt5-default


问:
Convert file: Uri to File in Android
What is the easiest way to convert from an android.net.Uri object which holds a file: type to a java.io.File object in Android?

I tried the following but it doesn't work:

File file = new File(Environment.getExternalStorageDirectory(), "read.me");
Uri uri = Uri.fromFile(file);
File auxFile = new File(uri.toString());
assertEquals(file.getAbsolutePath(), auxFile.getAbsolutePath());
```

答:
Add in onActivityResult, getting docx, or pdf file

```<code>var imageUriPath = ""
imageUriPath =
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val split = (imageUri.path ? : "").split(":") //split the path.
    split[1]
  } else {
    imageUri.path ? : ""
  }
val file = File(imageUriPath)
</code>```

Title: Convert file: Uri to File in Android

Body:
Add in onActivityResult, getting docx, or pdf file

var imageUriPath = ""
imageUriPath =
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val split = (imageUri.path ? : "").split(":") //split the path.
    split[1]
  } else {
    imageUri.path ? : ""
  }
val file = File(imageUriPath)


问:
what is the 'alpha' value of pixel shader?
hi there day i am in process to make 2d game using directx11 api.
and it come to point that i need to use transparent effect.

so i have a green background and one footprint on middle.

and simply without setting anything but alpha value of returning color in pixel shader, i made a bit of success, but the problem is that it doesn't work for white color.

this is Pixel Shader code

```<code>cbuffer CB_TRANSPARENCY : register(b0)
{
    float tp;
};

Texture2D footprint : register(t0);
SamplerState samplerState : register(s0);

struct PS_INPUT
{
    float4 pos : SV_POSITION;
    float2 tex : TEXCOORD;
};

float4 main(PS_INPUT input) : SV_Target
{
    float3 texColor = footprint.Sample(samplerState, input.tex).xyz;
    return float4(texColor, tp);
}
</code>```

it there something that i miss?
or should i use some blendingstate thing?
any help would be appreciated

[edit] here's something to edit. actually alpha value doesn't do anything without blending setting. just one variable to be used for any custom calculation.
In my project, i was using spritebathch,spritefont class for rendering font on screen,
So i guess in spritebatch class, there might be blendingState under the hood that blend black color, so that i have got this effect without setting my blendingState.

答:
Yes, you need to create a blend state with appropriate alpha processing mode and then make sure that created blend state is attached to output merging stage of the rendering pipeline prior to drawing:</p>

```<code>D3D11_BLEND_DESC blendStateDesc{};
blendStateDesc.AlphaToCoverageEnable = FALSE;
blendStateDesc.IndependentBlendEnable = FALSE;
blendStateDesc.RenderTarget[0].BlendEnable = TRUE;
blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_DEST_ALPHA;
blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

if(not SUCCEEDED(p_device->CreateBlendState(&blendStateDesc, &blendState)))
{
    std::abort();
}

p_device_context->OMSetBlendState(blendState, nullptr, 0xFFFFFFFF);
//draw calls...
</code>```

Body:
hi there day i am in process to make 2d game using directx11 api.
and it come to point that i need to use transparent effect.

so i have a green background and one footprint on middle.

and simply without setting anything but alpha value of returning color in pixel shader, i made a bit of success, but the problem is that it doesn't work for white color.

this is Pixel Shader code

cbuffer CB_TRANSPARENCY : register(b0)
{
    float tp;
};

Texture2D footprint : register(t0);
SamplerState samplerState : register(s0);

struct PS_INPUT
{
    float4 pos : SV_POSITION;
    float2 tex : TEXCOORD;
};

float4 main(PS_INPUT input) : SV_Target
{
    float3 texColor = footprint.Sample(samplerState, input.tex).xyz;
    return float4(texColor, tp);
}

it there something that i miss?
or should i use some blendingstate thing?
any help would be appreciated

[edit] here's something to edit. actually alpha value doesn't do anything without blending setting. just one variable to be used for any custom calculation.
In my project, i was using spritebathch,spritefont class for rendering font on screen,
So i guess in spritebatch class, there might be blendingState under the hood that blend black color, so that i have got this effect without setting my blendingState.

Body:
Yes, you need to create a blend state with appropriate alpha processing mode and then make sure that created blend state is attached to output merging stage of the rendering pipeline prior to drawing:

D3D11_BLEND_DESC blendStateDesc{};
blendStateDesc.AlphaToCoverageEnable = FALSE;
blendStateDesc.IndependentBlendEnable = FALSE;
blendStateDesc.RenderTarget[0].BlendEnable = TRUE;
blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_DEST_ALPHA;
blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

if(not SUCCEEDED(p_device->CreateBlendState(&blendStateDesc, &blendState)))
{
    std::abort();
}

p_device_context->OMSetBlendState(blendState, nullptr, 0xFFFFFFFF);
//draw calls...


问:
Angular component styles
I have a CSS class in the style.css which should apply to any components within my app. I have a component A that needs this class which works fine. And this component has another component B inside it which needs this class too. But this class won't work in this inner component B. Any ideas?

style.css:

```<code>.my-hover:hover {...}
</code>```

component A:

```<code>....
<div class="my-hover"></div>
<app-component-b *ngIf="aCondition"></app-component-b>
</code>```

component B:

```<code><div class="my-hover"></div>
</code>```

If I prefix my CSS class with ::ng-deep, then this class will not work in A or B.

答:
You can inject styles to child components from Host using this techniqe :

:host >>> app-component-b div.my-hover{
   /* your style here */
   display: flex;
}

refer this - https://blog.angular-university.io/angular-host-context/

Title: Angular component styles

Body:
I have a CSS class in the style.css which should apply to any components within my app. I have a component A that needs this class which works fine. And this component has another component B inside it which needs this class too. But this class won't work in this inner component B. Any ideas?

style.css:

.my-hover:hover {...}

component A:

....

<app-component-b *ngIf="aCondition"></app-component-b>

component B:

If I prefix my CSS class with ::ng-deep, then this class will not work in A or B.


问:
How to create 2 SNS Topics on 2 folders in single S3 bucket?
I have an S3 bucket with 2 folders (ABC & DEF). files are uploaded into these 2 folders. Can we create a cloudformation template which creates 2 SNS Topics on these 2 folders respectively?</p>

答:
Yes you can.

The aws s3 bucket property LifeCycleConfig.Rule is an array.

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig.html

All you need to do is specify two life cycle notification rules with the two different prefixes:

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-prefix

The catch is that the two prefixes cannot overlap.

Also, just so you know, there's no concept of "folder" in s3. AWS console achieves the illusion of folder by calling list s3 object api with delimeter of "/"

https://docs.aws.amazon.com/AmazonS3/latest/API/v2-RESTBucketGET.html


问:
how to filter array list of collection view which is in accessory view
//  I just want to filter array list which is shown in collection view cell when user enter text in the textfield.
    On textfield editing collection data will be sort and filter according to textfield input. In case of collection view has a data about states, If I input 'A' in textfield, all collection data will be sort and display all state names starting with alphabet 'A'. Please tell me logic for this.

ios iphone

here is the link of my project ---- https://drive.google.com/drive/folders/1d56PWO2j6YcDU2AJyCseZC16dfUeV7Bd?usp=sharing //

ViewController.swift

```<code>import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let customView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as? CustomView {
            self.textField.inputAccessoryView = customView
        }
    }
}

class CustomView: UIView, UICollectionViewDataSource {
    @IBOutlet weak var collectionView: UICollectionView!

    let words = ["abscind","downwind","headwind","lind","rescind","sind","skinned","tailwind","thin-skinned","tinned","twinned","upwind","whirlwind","wind"]

    override func awakeFromNib() {
        super.awakeFromNib()
        self.collectionView.register(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "cell")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.words.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
        cell.label.text = self.words[indexPath.row]
        return cell
    }
}

class CustomCell: UICollectionViewCell {
    @IBOutlet weak var label: UILabel!
}
</code>```

答:
You should not suppose to ask question like this, you should also provide the code that you have tried  </p>

```<code>let array = ["Alabama", "Alaska", "Arizona", "Arkansas", "Aalborg", "Indiana", "New Jersey"]
let searchtext = "A"

let filterArray = array.filter({ $0.hasPrefix(searchtext) }).sorted()
</code>```

Body:
//  I just want to filter array list which is shown in collection view cell when user enter text in the textfield.
    On textfield editing collection data will be sort and filter according to textfield input. In case of collection view has a data about states, If I input 'A' in textfield, all collection data will be sort and display all state names starting with alphabet 'A'. Please tell me logic for this.

ios iphone

here is the link of my project ---- https://drive.google.com/drive/folders/1d56PWO2j6YcDU2AJyCseZC16dfUeV7Bd?usp=sharing //

ViewController.swift

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let customView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as? CustomView {
            self.textField.inputAccessoryView = customView
        }
    }
}

class CustomView: UIView, UICollectionViewDataSource {
    @IBOutlet weak var collectionView: UICollectionView!

    let words = ["abscind","downwind","headwind","lind","rescind","sind","skinned","tailwind","thin-skinned","tinned","twinned","upwind","whirlwind","wind"]

    override func awakeFromNib() {
        super.awakeFromNib()
        self.collectionView.register(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "cell")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.words.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
        cell.label.text = self.words[indexPath.row]
        return cell
    }
}

class CustomCell: UICollectionViewCell {
    @IBOutlet weak var label: UILabel!
}

Body:
You should not suppose to ask question like this, you should also provide the code that you have tried

let array = ["Alabama", "Alaska", "Arizona", "Arkansas", "Aalborg", "Indiana", "New Jersey"]
let searchtext = "A"

let filterArray = array.filter({ $0.hasPrefix(searchtext) }).sorted()


问:
C++ Matrix Class - Suggestions
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

```<code>template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix<U>&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix<U>&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}
</code>```

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.

答:
I wouldn't use a vector of vectors to achieve this. This way you're adding quite some overhead to all lookups without any real need for it. Just allocate a one or two dimensional array of T and use that one within your class instead. This would also allow fast copying to other object instances without having to iterate through all fields as well as resetting the whole matrix.

Also you should make your members const when they shouldn't be changed later on (in your example r and c). To initialize them just use the constructor list in Tony's post.

Title: C++ Matrix Class - Suggestions

Body:
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.


问:
Understanding scoping of event handlers in web workers
Consider the following webworker code from: https://www.html5rocks.com/en/tutorials/workers/basics/

Web page:

```<code><button onclick="sayHI()">Say HI</button>
<button onclick="unknownCmd()">Send unknown command</button>
<button onclick="stop()">Stop worker</button>
<output id="result"></output>

<script>
  function sayHI() {
    worker.postMessage({'cmd': 'start', 'msg': 'Hi'});
  }

  function stop() {
    // worker.terminate() from this script would also stop the worker.
    worker.postMessage({'cmd': 'stop', 'msg': 'Bye'});
  }

  function unknownCmd() {
    worker.postMessage({'cmd': 'foobard', 'msg': '???'});
  }

  var worker = new Worker('doWork2.js');

  worker.addEventListener('message', function(e) {
    document.getElementById('result').textContent = e.data;
  }, false);
</script>
</code>```

Then in doWork2.js:

```<code>self.addEventListener('message', function(e) {
  var data = e.data;
  switch (data.cmd) {
    case 'start':
      self.postMessage('WORKER STARTED: ' + data.msg);
      break;
    case 'stop':
      self.postMessage('WORKER STOPPED: ' + data.msg +
                       '. (buttons will no longer work)');
      self.close(); // Terminates the worker.
      break;
    default:
      self.postMessage('Unknown command: ' + data.msg);
  };
}, false);
</code>```

So when you click SayHi, the "message" event handler defined in doWork2 picks up the event first. Then it fires another "message" event which is picked up by the handler defined on the main page that prints out the message.

The flow of steps is as such.

User clicks button, raises message event.

Handler in doWork2 is executed.

Handler in doWork2 raises message event

Handler on webpage is executed

Please answer the following 2 questions:

Question 1:  In step 2. above why is the handler in doWork2 triggered, but not the handler on the page?

Question 2: In step 4 after the event is triggered from doWork2 why is the handler on the page executed, but the one in doWork2 isn't recursively executed?

答:
the reason why doWorks2 event listener gets fired before is because the way javascript is interpreting your code. The code execution in Javascript happens in case of async functions in 2 directions. There is a call stack that has the commands that run in synchronous order or classical sequence and then for async functions there is a message queueing which queues up the events in the order they were added in.

See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

Body:
Consider the following webworker code from: https://www.html5rocks.com/en/tutorials/workers/basics/

Web page:

<button onclick="sayHI()">Say HI</button>
<button onclick="unknownCmd()">Send unknown command</button>
<button onclick="stop()">Stop worker</button>
<output id="result"></output>

Then in doWork2.js:

self.addEventListener('message', function(e) {
  var data = e.data;
  switch (data.cmd) {
    case 'start':
      self.postMessage('WORKER STARTED: ' + data.msg);
      break;
    case 'stop':
      self.postMessage('WORKER STOPPED: ' + data.msg +
                       '. (buttons will no longer work)');
      self.close(); // Terminates the worker.
      break;
    default:
      self.postMessage('Unknown command: ' + data.msg);
  };
}, false);

So when you click SayHi, the "message" event handler defined in doWork2 picks up the event first. Then it fires another "message" event which is picked up by the handler defined on the main page that prints out the message.

The flow of steps is as such.

User clicks button, raises message event.

Handler in doWork2 is executed.

Handler in doWork2 raises message event

Handler on webpage is executed

Please answer the following 2 questions:

Question 1:  In step 2. above why is the handler in doWork2 triggered, but not the handler on the page?

Question 2: In step 4 after the event is triggered from doWork2 why is the handler on the page executed, but the one in doWork2 isn't recursively executed?


问:
What can be written in exchange of Oledb.parameters.AddwithValue() to add a Parameter to a Command?
I am been told that cmd.Parameters.AddWithValue is not good and we should write cmd.Parameters.Add instead.

Some of the link referred to me are :
Link 1 and Link 2.

I referred the link but the link gave examples with SQL Connection. I am using Oledb Connection everywhere. And .Add don't work properly with Oledb Connection.

On digging on stack overflow and other sites I found that almost everyone using .AddWithValue.
Some used .Add and I tried their method and got error like "Must declare a scalar variable.".
Again searching the error gives result to use .AddWithValue

I am currently using parameters like this

```<code> cmd = New OleDbCommand("INSERT INTO TABLE (Col1,Col2,Col3)
                         VALUES('" & ColVal1 & "','" & ColVal2 & "',?)", con1)
                                'With cmd.Parameters
                                '    .Add(New OleDbParameter("@Trans_Date", TransDate))
                                '    '.Add(New OleDbParameter("@Password", txtPassword.Text))
                                'End With
                                cmd.Parameters.AddWithValue("@Col3", OleDbType.Date).Value = TransDate
</code>```

And it works fine for me.
So what should I use and How?

答:
That code is wrong.  When you call AddWithValue, the second argument is the value and the data type is inferred from that.  If you were going to call AddWithValue then it would look like this:

```<code>cmd.Parameters.AddWithValue("@Col3", TransDate)
</code>```

The reason that you should call Add instead is that it may occur that the inferred data type does not match what the database actually needs and that can cause problems on some occasions.  Your code is the right pattern but should be calling Add rather than AddWithValue:

```<code>cmd.Parameters.Add("@Col3", OleDbType.Date).Value = TransDate
</code>```

As it is, you are creating a parameter with a value of OleDbType.Date and a data type inferred from that, then you explicitly set the Value to TransDate.  That's wrong.

Also, the whole point of using parameters is to avoid the issues that can arise form string concatenation and you're using string concatenation anyway.  Don't!  Use parameter EVERY time:

```<code>cmd = New OleDbCommand("INSERT INTO MyTable (Col1, Col2, Col3) VALUES (@Col1, @Col2, @Col3)", con1)

With cmd.Parameters
    .Parameters.Add("@Col1", OleDbType.VarChar).Value = ColVal1
    .Parameters.Add("@Col2", OleDbType.VarChar).Value = ColVal2
    .Parameters.Add("@Col3", OleDbType.Date).Value = TransDate
End With
</code>```

Body:
I am been told that cmd.Parameters.AddWithValue is not good and we should write cmd.Parameters.Add instead.

Some of the link referred to me are :
Link 1 and Link 2.

I referred the link but the link gave examples with SQL Connection. I am using Oledb Connection everywhere. And .Add don't work properly with Oledb Connection.

On digging on stack overflow and other sites I found that almost everyone using .AddWithValue.
Some used .Add and I tried their method and got error like "Must declare a scalar variable.".
Again searching the error gives result to use .AddWithValue

I am currently using parameters like this

 cmd = New OleDbCommand("INSERT INTO TABLE (Col1,Col2,Col3)
                         VALUES('" & ColVal1 & "','" & ColVal2 & "',?)", con1)
                                'With cmd.Parameters
                                '    .Add(New OleDbParameter("@Trans_Date", TransDate))
                                '    '.Add(New OleDbParameter("@Password", txtPassword.Text))
                                'End With
                                cmd.Parameters.AddWithValue("@Col3", OleDbType.Date).Value = TransDate

And it works fine for me.
So what should I use and How?

Body:
That code is wrong.  When you call AddWithValue, the second argument is the value and the data type is inferred from that.  If you were going to call AddWithValue then it would look like this:

cmd.Parameters.AddWithValue("@Col3", TransDate)

The reason that you should call Add instead is that it may occur that the inferred data type does not match what the database actually needs and that can cause problems on some occasions.  Your code is the right pattern but should be calling Add rather than AddWithValue:

cmd.Parameters.Add("@Col3", OleDbType.Date).Value = TransDate

As it is, you are creating a parameter with a value of OleDbType.Date and a data type inferred from that, then you explicitly set the Value to TransDate.  That's wrong.

Also, the whole point of using parameters is to avoid the issues that can arise form string concatenation and you're using string concatenation anyway.  Don't!  Use parameter EVERY time:

cmd = New OleDbCommand("INSERT INTO MyTable (Col1, Col2, Col3) VALUES (@Col1, @Col2, @Col3)", con1)

With cmd.Parameters
    .Parameters.Add("@Col1", OleDbType.VarChar).Value = ColVal1
    .Parameters.Add("@Col2", OleDbType.VarChar).Value = ColVal2
    .Parameters.Add("@Col3", OleDbType.Date).Value = TransDate
End With


问:
Byzantine fault tolerance (BFT) and Crash fault tolerance (CFT)
Crash fault tolerance (CFT) is one level of resiliency, where the system can still correctly reach consensus if components fail. While Byzantine fault tolerance (BFT), which says the orderer can do its job even in the presence of malicious actors. Below are my questions

CFT is more useful for single enterprise. Presently Hyperleger Fabric uses Kafka which is CFT. Even in the case of multiple organization we are using Kafka in Hyperledger Fabric network. Does it mean still we are using CFT?

In CFT, How system can still correctly reach consensus if components fail? For example network is down, or malcious node present in system etc

Can CFT work even in presence of malicious actor?

How Hyperledger Fabric implements BFT? When will they release it?

What is the main difference between CFT & BFT?

答:
CFT is more useful for single enterprise. Presently Hyperleger Fabric uses Kafka which is CFT. Even in the case of multiple organization we are using Kafka in Hyperledger Fabric network. Does it mean still we are using CFT?

Yes it's still CFT, Crash Fault Tolerant model guaranties to withstand system failures, such as crashes, network partitioning. Having N nodes in your consensus system CFT capable to withstand up to N/2 such crashes. Fact that you might distribute it across organizations or different clouds won't change this assumption.

In CFT, How system can still correctly reach consensus if components fail? For example network is down, or malcious node present in system etc

In CFT model there is quorum of N/2 + 1 nodes which has to agree on certain value, therefore as long as you have N/2 + 1 nodes available, which means you have a quorum you will be able to reach agreement, since majority agrees on it. And NO it cannot guarantee anything in presence of malicious actors.

Can CFT work even in presence of malicious actor?

Nope.

How Hyperledger Fabric implements BFT? When will they release it?

There is a plan to implement BFT protocol and integrate in into Fabric, however exact days currently under carefully design and planning. I guess it will be reveled at one of the bi-weekly maintainers meetings.

What is the main difference between CFT & BFT?

The key difference is in the assumptions and threat/failure model, CFT can withstand up to N/2 system failures, while no guarantees on adversary nodes. BFT provides with guarantees to withstand and correctly reach consensus in presence of N/3 failures of any kind including Byzantine. You can think of it as two phase commit versus three phase commit.


问:
How do I find out how many records of 1 model have associated objects of an association?
I have two models - Property & Photos.

```<code>class Property < ActiveRecord::Base
  has_many :photos, dependent: :destroy
end

class Photo < ActiveRecord::Base
  belongs_to :property
end
</code>```

All I want to do is create a scope that returns only the Properties that actually have photos (i.e. photos.count > 0).

I have tried a million iterations of queries, and they don't work for one reason or another.

See some examples of what I have tried and the results:

```<code>[32] pry(main)> Property.includes(:photos).where('photos.count > 0').count
   (4.1ms)  SELECT COUNT(DISTINCT "properties"."id") FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
[33] pry(main)> Property.joins(:photos).where('photos.count > 0').count
   (11.1ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^

[38] pry(main)> Property.joins(:photos).count("properties.id").count
   (158.2ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `count' for 72604:Fixnum
from (pry):38:in `__pry__'

[39] pry(main)> Property.joins(:photos).count("properties.id")
   (50.6ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
=> 72604

[40] pry(main)> Photo.joins(:properties).count("photos.id")
ActiveRecord::ConfigurationError: Association named 'properties' was not found on Photo; perhaps you misspelled it?
from /.rvm/gems/ruby-2.3.7@myapp/gems/activerecord-3.2.22.5/lib/active_record/associations/join_dependency.rb:112:in `build'

[41] pry(main)> Photo.joins(:property).count("photos.id")
   (65.0ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604

[42] pry(main)> Photo.joins(:property).count("photos.id")
   (60.5ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604

[43] pry(main)> Property.joins(:photos).count("properties.id").distinct
   (46.4ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `distinct' for 72604:Fixnum
from (pry):43:in `__pry__'

[44] pry(main)> Property.joins(:photos).distinct.count("properties.id")
=> 0
</code>```

This should be simple, but for some reason it's much more difficult than I expected.

Thoughts?

答:
In Rails-5, you can use left_outer_joins,

```<code>Property.left_outer_joins(:photos).where(photos: {id: nil})
</code>```

SQL generated will be,

```<code>SELECT properties.*
FROM properties
LEFT OUTER JOIN photos
ON photos.property_id = property.id
WHERE photos.id IS NULL
</code>```

In Rails-3, You can try following

```<code>Property.joins("LEFT OUTER JOIN photos ON properties.id = photos.property_id").where(photos: {id: nil})
</code>```

Body:
I have two models - Property & Photos.

class Property < ActiveRecord::Base
  has_many :photos, dependent: :destroy
end

class Photo < ActiveRecord::Base
  belongs_to :property
end

All I want to do is create a scope that returns only the Properties that actually have photos (i.e. photos.count > 0).

I have tried a million iterations of queries, and they don't work for one reason or another.

See some examples of what I have tried and the results:

[32] pry(main)> Property.includes(:photos).where('photos.count > 0').count
   (4.1ms)  SELECT COUNT(DISTINCT "properties"."id") FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
[33] pry(main)> Property.joins(:photos).where('photos.count > 0').count
   (11.1ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^

[38] pry(main)> Property.joins(:photos).count("properties.id").count
   (158.2ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `count' for 72604:Fixnum
from (pry):38:in `__pry__'

[39] pry(main)> Property.joins(:photos).count("properties.id")
   (50.6ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
=> 72604

[40] pry(main)> Photo.joins(:properties).count("photos.id")
ActiveRecord::ConfigurationError: Association named 'properties' was not found on Photo; perhaps you misspelled it?
from /.rvm/gems/ruby-2.3.7@myapp/gems/activerecord-3.2.22.5/lib/active_record/associations/join_dependency.rb:112:in `build'

[41] pry(main)> Photo.joins(:property).count("photos.id")
   (65.0ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604

[42] pry(main)> Photo.joins(:property).count("photos.id")
   (60.5ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604

[43] pry(main)> Property.joins(:photos).count("properties.id").distinct
   (46.4ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `distinct' for 72604:Fixnum
from (pry):43:in `__pry__'

[44] pry(main)> Property.joins(:photos).distinct.count("properties.id")
=> 0

This should be simple, but for some reason it's much more difficult than I expected.

Thoughts?

Body:
In Rails-5, you can use left_outer_joins,

Property.left_outer_joins(:photos).where(photos: {id: nil})

SQL generated will be,

SELECT properties.*
FROM properties
LEFT OUTER JOIN photos
ON photos.property_id = property.id
WHERE photos.id IS NULL

In Rails-3, You can try following

Property.joins("LEFT OUTER JOIN photos ON properties.id = photos.property_id").where(photos: {id: nil})


问:
Migrate Magnolia from Enterprise Edition to Community Edition
Is it possible to migrate Magnolia 5.5 from Enterprise Edition to Community Edition. We have been using Magnolia Enterprise Edition Pro with multisite und commercetools module. We do not need any Professional Edition features and want to keep on our web presence on Magnolia.

Mit freundlichen Grüßen
Alexander Fuchs

答:
You can use community licence as long as you don't have any enterprise modules in the webapp. That being said, multisite is an enterprise feature so you have to replace it one way or the other.

Cheers,

Ilgun


答:
DateTime expects "A date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar." (from msdn)

This question shows how you can convert a unix timestamp to a DateTime.

Title: C# strange with DateTime

Body:
I got some strange result for:

Console.WriteLine(new DateTime(1296346155).ToString());

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))


问:
WPBakery Page Builder - Checkboxes won't retain values from v6.xx
For the last few years I have been developing a custom theme and various plugins that add options to WPBakery Page Builder elements and create new custom elements, etc.

Everything has worked perfectly up to Page Builder v5.7.  But then when v6.0.x came out, suddenly every Checkbox option I have added to every element, be it a custom element or one of Page Builder's standard elements, has a problem:  As soon as I click the element in the Page Editor to open it's settings, all checkboxes clear and become unticked regardless of their default or saved values.

If I tick a checkbox and save settings, when I view the front end of the site the option has indeed saved and is working as it should be;  but when I open the element's settings window again, they all clear.

I have looked at all my code and compared it to other plugin's code and all of WPBakery's documentation, etc, and I can't see a problem anywhere.  I thought it might be a bug with Page Builder v6.0.x and I have sent them a support ticket, but they haven't been able to give me an answer. Other people's plugins seem to be working though, along with all of Page Builder's own built-in elements, which leads me to believe that it must be something to do with my code.

Here is an example:

```<code>// After VC Init
add_action( 'vc_after_init', 'gd_after_init_actions' );

// ADD OPTIONS TO VISUAL COMPOSER ELEMENTS //
function gd_after_init_actions() {
  // ADD FULL WIDTH CHECKBOX TO SINGLE IMAGE ELEMENTS //
  $single_image_attributes = array(
    'type' => 'checkbox',
    'class' => 'full_width_image',
    'param_name' => 'full_width_image',
    'value' => array('Force Full Width' => true),
    'weight' => 1
  );
  vc_add_param('vc_single_image', $single_image_attributes);
}
</code>```

This adds a "Force Full Width" checkbox to Page Builder's standard "Single Image" element.  The checkbox appears perfectly and if I check it, save and then view the front end of the site, the checkbox does indeed work;  the checkbox value has saved and the image is stretched to full width.  But then if I go back to the back end and click on the Single Image element to edit it's settings again, the checkbox becomes unchecked and it's saved value is lost.

Similarly, with plugins in which I am adding options with vc_map(), here is a sample:

```<code>function vc_before_init_actions(){

    // Stop all if VC is not enabled
    if ( !defined( 'WPB_VC_VERSION' ) ) {
        return;
    }

    // ELEMENT CLASS //
    class vcResponsiveYouTubeVideo extends WPBakeryShortCode {

        // ELEMENT INIT //
        function __construct() {
            add_action( 'init', array( $this, 'vc_youtube_video_mapping' ) );
            add_shortcode( 'vc_youtube', array( $this, 'vc_youtube_video_html' ) );
        }

        // ELEMENT MAPPING //
        public function vc_youtube_video_mapping() {

            // Map the block with vc_map()
            $youtubeIcon = plugins_url('responsive-youtube-icon.png',__FILE__ );
            vc_map(
                array(
                    'name' => __('Responsive YouTube Video', 'text-domain'),
                    'base' => 'vc_youtube',
                    'category' => __('Custom Elements', 'text-domain'),
                    'icon' => $youtubeIcon,
                    'params' => array(
                        array(
                            'type' => 'checkbox',
                            'param_name' => 'lightbox',
                            'value' => array('Pop up video in lightbox' => true),
                            'admin_label' => false,
                            'weight' => 0,
                            'group' => 'Custom Group'
                        ),
                    )
                )
            );
        }
[etc...]
}
</code>```

This is just a snippet of the code and there is much more to it, but this is just the part pertaining to one of the checkbox options that I have in this particular plugin.  Just like the previous example, if I check it and save the options, it works, but then if I come back into the element's settings, it clears.

Even checkboxes that are set to be checked by default:

```<code>array(
    'type' => 'checkbox',
    'param_name' => 'branding',
    'value' => array('Keep YouTube Branding in Control Bar' => true),
    'std' => true,
    'admin_label' => false,
    'weight' => 0,
    'group' => 'Custom Group'
),
</code>```

This checkbox still clears as soon as I click open the settings window.

I've done a fair bit of testing and it appears this issue exists (so far) only with Checkboxes.  All the other inputs I've created, such as textfields, colorpickers, dropdowns, etc, all save fine and retain their values when I re-open the settings window.

Does anyone any have ideas on this?

答:
we found an issue, it caused because we added strict compare for key-value pairs for checkboxes, but in your mapping value is boolean true, however shortcode saves this as string "1" and when edit form is opening then strict compare fails.

For BC we will fix this in our next release, there is a patch:

```<code>Index: include/params/default_params.php
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- include/params/default_params.php   (revision afcb0ccf521c36ce176651964792d18c1f9b1bfc)
+++ include/params/default_params.php   (date 1559032145000)
@@ -85,7 +85,9 @@
    $values = isset( $settings['value'] ) && is_array( $settings['value'] ) ? $settings['value'] : array( esc_html__( 'Yes', 'js_composer' ) => 'true' );
    if ( ! empty( $values ) ) {
        foreach ( $values as $label => $v ) {
-           $checked = in_array( $v, $current_value, true ) ? 'checked' : '';
+           // NOTE!! Don't use strict compare here for BC!
+           // @codingStandardsIgnoreLine
+           $checked = in_array( $v, $current_value ) ? 'checked' : '';
            $output .= ' <label class="vc_checkbox-label"><input id="' . $settings['param_name'] . '-' . $v . '" value="' . $v . '" class="wpb_vc_param_value ' . $settings['param_name'] . ' ' . $settings['type'] . '" type="checkbox" name="' . $settings['param_name'] . '" ' . $checked . '>' . $label . '</label>';
        }
    }
</code>```

Body:
For the last few years I have been developing a custom theme and various plugins that add options to WPBakery Page Builder elements and create new custom elements, etc.

Everything has worked perfectly up to Page Builder v5.7.  But then when v6.0.x came out, suddenly every Checkbox option I have added to every element, be it a custom element or one of Page Builder's standard elements, has a problem:  As soon as I click the element in the Page Editor to open it's settings, all checkboxes clear and become unticked regardless of their default or saved values.

If I tick a checkbox and save settings, when I view the front end of the site the option has indeed saved and is working as it should be;  but when I open the element's settings window again, they all clear.

I have looked at all my code and compared it to other plugin's code and all of WPBakery's documentation, etc, and I can't see a problem anywhere.  I thought it might be a bug with Page Builder v6.0.x and I have sent them a support ticket, but they haven't been able to give me an answer. Other people's plugins seem to be working though, along with all of Page Builder's own built-in elements, which leads me to believe that it must be something to do with my code.

Here is an example:

// After VC Init
add_action( 'vc_after_init', 'gd_after_init_actions' );

// ADD OPTIONS TO VISUAL COMPOSER ELEMENTS //
function gd_after_init_actions() {
  // ADD FULL WIDTH CHECKBOX TO SINGLE IMAGE ELEMENTS //
  $single_image_attributes = array(
    'type' => 'checkbox',
    'class' => 'full_width_image',
    'param_name' => 'full_width_image',
    'value' => array('Force Full Width' => true),
    'weight' => 1
  );
  vc_add_param('vc_single_image', $single_image_attributes);
}

This adds a "Force Full Width" checkbox to Page Builder's standard "Single Image" element.  The checkbox appears perfectly and if I check it, save and then view the front end of the site, the checkbox does indeed work;  the checkbox value has saved and the image is stretched to full width.  But then if I go back to the back end and click on the Single Image element to edit it's settings again, the checkbox becomes unchecked and it's saved value is lost.

Similarly, with plugins in which I am adding options with vc_map(), here is a sample:

function vc_before_init_actions(){

    // Stop all if VC is not enabled
    if ( !defined( 'WPB_VC_VERSION' ) ) {
        return;
    }

    // ELEMENT CLASS //
    class vcResponsiveYouTubeVideo extends WPBakeryShortCode {

        // ELEMENT INIT //
        function __construct() {
            add_action( 'init', array( $this, 'vc_youtube_video_mapping' ) );
            add_shortcode( 'vc_youtube', array( $this, 'vc_youtube_video_html' ) );
        }

        // ELEMENT MAPPING //
        public function vc_youtube_video_mapping() {

            // Map the block with vc_map()
            $youtubeIcon = plugins_url('responsive-youtube-icon.png',__FILE__ );
            vc_map(
                array(
                    'name' => __('Responsive YouTube Video', 'text-domain'),
                    'base' => 'vc_youtube',
                    'category' => __('Custom Elements', 'text-domain'),
                    'icon' => $youtubeIcon,
                    'params' => array(
                        array(
                            'type' => 'checkbox',
                            'param_name' => 'lightbox',
                            'value' => array('Pop up video in lightbox' => true),
                            'admin_label' => false,
                            'weight' => 0,
                            'group' => 'Custom Group'
                        ),
                    )
                )
            );
        }
[etc...]
}

This is just a snippet of the code and there is much more to it, but this is just the part pertaining to one of the checkbox options that I have in this particular plugin.  Just like the previous example, if I check it and save the options, it works, but then if I come back into the element's settings, it clears.

Even checkboxes that are set to be checked by default:

array(
    'type' => 'checkbox',
    'param_name' => 'branding',
    'value' => array('Keep YouTube Branding in Control Bar' => true),
    'std' => true,
    'admin_label' => false,
    'weight' => 0,
    'group' => 'Custom Group'
),

This checkbox still clears as soon as I click open the settings window.

I've done a fair bit of testing and it appears this issue exists (so far) only with Checkboxes.  All the other inputs I've created, such as textfields, colorpickers, dropdowns, etc, all save fine and retain their values when I re-open the settings window.

Does anyone any have ideas on this?

Body:
we found an issue, it caused because we added strict compare for key-value pairs for checkboxes, but in your mapping value is boolean true, however shortcode saves this as string "1" and when edit form is opening then strict compare fails.

For BC we will fix this in our next release, there is a patch:

Index: include/params/default_params.php
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- include/params/default_params.php   (revision afcb0ccf521c36ce176651964792d18c1f9b1bfc)
+++ include/params/default_params.php   (date 1559032145000)
@@ -85,7 +85,9 @@
    $values = isset( $settings['value'] ) && is_array( $settings['value'] ) ? $settings['value'] : array( esc_html__( 'Yes', 'js_composer' ) => 'true' );
    if ( ! empty( $values ) ) {
        foreach ( $values as $label => $v ) {
-           $checked = in_array( $v, $current_value, true ) ? 'checked' : '';
+           // NOTE!! Don't use strict compare here for BC!
+           // @codingStandardsIgnoreLine
+           $checked = in_array( $v, $current_value ) ? 'checked' : '';
            $output .= ' <label class="vc_checkbox-label"><input id="' . $settings['param_name'] . '-' . $v . '" value="' . $v . '" class="wpb_vc_param_value ' . $settings['param_name'] . ' ' . $settings['type'] . '" type="checkbox" name="' . $settings['param_name'] . '" ' . $checked . '>' . $label . '</label>';
        }
    }


问:
Difference between member function and property
What is the difference?

```<code>val isFinished: Boolean
        get() = actor.actions.size == 0
</code>```

```<code>fun isFinished() = actor.actions.size == 0
</code>```

I have no idea.

I expect them to be the same.

答:
Class Property

Your first example is a class property:

```<code>class MyClass {
    val isFinished: Boolean
        get() = actor.actions.size == 0
}
</code>```

This property defines an (optional) explicit get method, often referred to as a "getter". You could also omit the getter and do:

```<code>class MyClass {
    val isFinished: Boolean = (actor.actions.size == 0) //parens not necessary
}
</code>```

If omitted, as shown in the last example, the value will rather be a constant value which isn't re-calculated on each access. Both variants serve different use cases but in most cases, the latter will be sufficient.

Regardless, for a client of this class, the property can be accessed like this:

```<code>val mc = MyClass()
mc.isFinished
</code>```

This shows accessing a property in Kotlin.

Class member function

Functions in Kotlin can also define functions, which can be referred to as member functions. Your second example demonstrates this feature:

```<code>class MyClass {
    fun isFinished() = actor.actions.size == 0
}
</code>```

Defining a member function is similar to properties with explicit getters but still different for a client, since they have to invoke a function rather than accessing a property:

```<code>val mc = MyClass()
mc.isFinished()
</code>```

Side Note

Note that the shown function utilizes an expression body which is equivalent to the following block body approach:

```<code>class MyClass {
   fun isFinished() {
       return actor.actions.size == 0
   }
}
</code>```

Learn more about functions here.

Body:
What is the difference?

val isFinished: Boolean
        get() = actor.actions.size == 0

fun isFinished() = actor.actions.size == 0

I have no idea.

I expect them to be the same.

Body:
Class Property

Your first example is a class property:

class MyClass {
    val isFinished: Boolean
        get() = actor.actions.size == 0
}

This property defines an (optional) explicit get method, often referred to as a "getter". You could also omit the getter and do:

class MyClass {
    val isFinished: Boolean = (actor.actions.size == 0) //parens not necessary
}

If omitted, as shown in the last example, the value will rather be a constant value which isn't re-calculated on each access. Both variants serve different use cases but in most cases, the latter will be sufficient.

Regardless, for a client of this class, the property can be accessed like this:

val mc = MyClass()
mc.isFinished

This shows accessing a property in Kotlin.

Class member function

Functions in Kotlin can also define functions, which can be referred to as member functions. Your second example demonstrates this feature:

class MyClass {
    fun isFinished() = actor.actions.size == 0
}

Defining a member function is similar to properties with explicit getters but still different for a client, since they have to invoke a function rather than accessing a property:

val mc = MyClass()
mc.isFinished()

Side Note

Note that the shown function utilizes an expression body which is equivalent to the following block body approach:

class MyClass {
   fun isFinished() {
       return actor.actions.size == 0
   }
}

Learn more about functions here.