问:
Prevent onDestroy when Bluetooth connection state changes
Goal

If an already connected bluetooth device disconnects, and an Activity is already running, close the Activity

Problem

When the bluetooth device connection state changes through BluetoothAdapterProperties: CONNECTION_STATE_CHANGE, it seems like a new Activity is created or the current one restarts.

There is nothing in the code that listens and/or should react to bluetooth connection state changes.

The problem manifests itself in the use of BroadcastReceivers which in turn starts the Activity using intents. For some reason the Activity keep running through its lifecycle, spawning up new windows, even if the only change in bluetooth connectivity is BluetoothAdapterProperties: CONNECTION_STATE_CHANGE

I've tested this solely on a Nexus 6P with Android N. I have no idea yet what kind of implications this implementation means for any other devices yet. But I at least need to get this working on one device.

UPDATE

I have done a fair bit of experimentation and found that if I don't register the BroadcastReceiver in AndroidManifest, the problem with onDestroy being called disappears. But, I want to be able to react to Bluetooth connecting devices, so that I can launch my activity and then process input. If the activity gets destroyed every time a new device connects/disconnects, this won't work at all. What's the reasoning for having the BroadcastReceiver finishing an activity if it's already running and can I control that behaviour?

UPDATE 2

I can also conclude that disabling the statically declared BroadcastReceiver using this method https://stackoverflow.com/a/6529365/975641 doesn't improve things. As soon as the Manifest-BroadcastReceiver catches the ACL_CONNECTED intent from Android, and start my custom activity, it will ruthlessly call onDestroy on it when the connection state changes (which is usually just before an ACL_DISCONNECTED). It does not matter if I have ACL_DISCONNECTED declared in the Manifest or not. As long as I have my receiver listening for ACL_CONNECTED intents and I launch my Activity based on that, onDestroy will be called when the connection state changes. So frustrating.

Manifest

```<code><uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.VIBRATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".BtActivity"
        android:launchMode="singleTop" />
    <receiver android:name=".BtConnectionBroadcastReceiver" android:priority="100000">
        <intent-filter>
            <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
            <action android:name="android.intent.action.MEDIA_BUTTON" />
            <action android:name="android.media.VOLUME_CHANGED_ACTION" />
        </intent-filter>
    </receiver>
</application>
</code>```

BtConnectionBroadcastReceiver

```<code>public class BtConnectionBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "BT";
    public static final String BROADCAST_ACTION_CONNECTED = "CONNECTED";
    public static final String BROADCAST_ACTION_DISCONNECTED = "DISCONNECTED";
    SharedPreferences mSharedPreferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        // When discovery finds a device
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            Log.d(TAG, "DEVICE CONNECTED");
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.d("DEVICE NAME", device.getName());
            Log.d("DEVICE ADDRESS", device.getAddress());
            Intent i = new Intent(context, BtActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            context.startActivity(i);
        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            Log.d(TAG, "DEVICE DISCONNECTED");
            intent = new Intent();
            intent.setAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
            context.sendBroadcast(intent);
        }
    }
</code>```

BtActivity

```<code>public class BtActivity extends AppCompatActivity {
private static final String TAG = "BT";
Window mWindow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_bt);

    Log.d(TAG, "onCreate");
    IntentFilter filter = new IntentFilter(BtConnectionBroadcastReceiver.INTENT_FILTER);
    filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_CONNECTED);
    filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
    //registerReceiver(mReceiver, filter);

    mWindow = getWindow();
    WindowManager.LayoutParams params = new WindowManager.LayoutParams();
    //params.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
    params.screenBrightness = 0.2f;
    mWindow.setAttributes(params);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    mWindow.getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                    View.SYSTEM_UI_FLAG_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "onResume");
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy");
}

BroadcastReceiver mReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "BROADCAST RECEIVED IN ACTIVITY");
        String mac;
        if(intent.getAction().equals(BtConnectionBroadcastReceiver.BROADCAST_DEVICE_CONNECTED)) {
            Log.d(TAG, "CONNECT BROADCAST RECEIVED");
            mac = intent.getStringExtra("mac");
            checkConnectedDevice(mac, true); // This adds a device to an internal list
            Log.d(TAG, "Activity nr of devices:" +mNrOfDevices);
        }
        if(intent.getAction().equals(BtConnectionBroadcastReceiver.BROADCAST_DEVICE_DISCONNECTED)) {
            Log.d(TAG, "DISCONNECT BROADCAST RECEIVED");
            mac = intent.getStringExtra("mac");
            checkConnectedDevice(mac, false); // This removes a device from an internal list
            Log.d(TAG, "Activity nr of devices:" +mNrOfDevices);
            if(mNrOfDevices < 1) {
                Log.d(TAG, "No more connected devices");
                finish();
            }
        }
        abortBroadcast();
    }
};
}
</code>```

When I run this code, I get the following chain:

Start MainActivity (not included, it only contains an activity with the default main layout, so that the applications receiver is registered)

Switch on a bluetooth device (This has been paired earlier, so android knows about it)

Wait until it connects and get this:

DEVICE CONNECTED

onCreate

onResume

Switch off the bluetooth device and I then get this:

DEVICE DISCONNECTED

onDestroy

onCreate

onResume

I can't grasp why the activity is getting destroyed restarting at this point. The activity is already running, the BroadcastReceiver only sends a broadcast to an already running activity. I can't figure out why there's a reason for the Activity to kill itself and then restart again. This leaves me in a state of the Activity still running, but it is not the original Activity that was started.

I do however see something in the logcats that seem to have something to do with this, and it's in this sequencing;

06-02 15:45:09.156 26431 26431 D BT : DEVICE DISCONNECTED

06-02 15:45:09.213 19547 19547 D BluetoothAdapterService: handleMessage() - MESSAGE_PROFILE_CONNECTION_STATE_CHANGED

06-02 15:45:09.213 26431 26431 D BT : onDestroy

06-02 15:45:09.214 19547 19547 D BluetoothAdapterProperties: CONNECTION_STATE_CHANGE: FF:FF:20:00:C1:47: 2 -> 0

06-02 15:45:09.216  3502  3805 D CachedBluetoothDevice: onProfileStateChanged: profile HID newProfileState 0

06-02 15:45:09.237   414   414 W SurfaceFlinger: couldn't log to binary event log: overflow.

06-02 15:45:09.239 26431 26431 D BT : onCreate

06-02 15:45:09.243 26431 26431 D BT : onResume

答:
Having read this https://developer.android.com/guide/components/broadcasts.html#effects_on_process_state I can probably safely conclude that the reason for why onDestroy gets called is because the receiver affects the process in which it is run, effectively meaning when the receiver has run its onReceive method, it will destroy itself and take the Activity with it.

I would of course have wished it was working differently, but I believe this is what effectively is going on and need to take another approach.

Body:
Goal

If an already connected bluetooth device disconnects, and an Activity is already running, close the Activity

Problem

When the bluetooth device connection state changes through BluetoothAdapterProperties: CONNECTION_STATE_CHANGE, it seems like a new Activity is created or the current one restarts.

There is nothing in the code that listens and/or should react to bluetooth connection state changes.

The problem manifests itself in the use of BroadcastReceivers which in turn starts the Activity using intents. For some reason the Activity keep running through its lifecycle, spawning up new windows, even if the only change in bluetooth connectivity is BluetoothAdapterProperties: CONNECTION_STATE_CHANGE

I've tested this solely on a Nexus 6P with Android N. I have no idea yet what kind of implications this implementation means for any other devices yet. But I at least need to get this working on one device.

UPDATE

I have done a fair bit of experimentation and found that if I don't register the BroadcastReceiver in AndroidManifest, the problem with onDestroy being called disappears. But, I want to be able to react to Bluetooth connecting devices, so that I can launch my activity and then process input. If the activity gets destroyed every time a new device connects/disconnects, this won't work at all. What's the reasoning for having the BroadcastReceiver finishing an activity if it's already running and can I control that behaviour?

UPDATE 2

I can also conclude that disabling the statically declared BroadcastReceiver using this method https://stackoverflow.com/a/6529365/975641 doesn't improve things. As soon as the Manifest-BroadcastReceiver catches the ACL_CONNECTED intent from Android, and start my custom activity, it will ruthlessly call onDestroy on it when the connection state changes (which is usually just before an ACL_DISCONNECTED). It does not matter if I have ACL_DISCONNECTED declared in the Manifest or not. As long as I have my receiver listening for ACL_CONNECTED intents and I launch my Activity based on that, onDestroy will be called when the connection state changes. So frustrating.

Manifest

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.VIBRATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".BtActivity"
        android:launchMode="singleTop" />
    <receiver android:name=".BtConnectionBroadcastReceiver" android:priority="100000">
        <intent-filter>
            <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
            <action android:name="android.intent.action.MEDIA_BUTTON" />
            <action android:name="android.media.VOLUME_CHANGED_ACTION" />
        </intent-filter>
    </receiver>
</application>

BtConnectionBroadcastReceiver

public class BtConnectionBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "BT";
    public static final String BROADCAST_ACTION_CONNECTED = "CONNECTED";
    public static final String BROADCAST_ACTION_DISCONNECTED = "DISCONNECTED";
    SharedPreferences mSharedPreferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        // When discovery finds a device
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            Log.d(TAG, "DEVICE CONNECTED");
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.d("DEVICE NAME", device.getName());
            Log.d("DEVICE ADDRESS", device.getAddress());
            Intent i = new Intent(context, BtActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            context.startActivity(i);
        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            Log.d(TAG, "DEVICE DISCONNECTED");
            intent = new Intent();
            intent.setAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
            context.sendBroadcast(intent);
        }
    }

BtActivity

public class BtActivity extends AppCompatActivity {
private static final String TAG = "BT";
Window mWindow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_bt);

    Log.d(TAG, "onCreate");
    IntentFilter filter = new IntentFilter(BtConnectionBroadcastReceiver.INTENT_FILTER);
    filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_CONNECTED);
    filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
    //registerReceiver(mReceiver, filter);

    mWindow = getWindow();
    WindowManager.LayoutParams params = new WindowManager.LayoutParams();
    //params.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
    params.screenBrightness = 0.2f;
    mWindow.setAttributes(params);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    mWindow.getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                    View.SYSTEM_UI_FLAG_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "onResume");
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy");
}

BroadcastReceiver mReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "BROADCAST RECEIVED IN ACTIVITY");
        String mac;
        if(intent.getAction().equals(BtConnectionBroadcastReceiver.BROADCAST_DEVICE_CONNECTED)) {
            Log.d(TAG, "CONNECT BROADCAST RECEIVED");
            mac = intent.getStringExtra("mac");
            checkConnectedDevice(mac, true); // This adds a device to an internal list
            Log.d(TAG, "Activity nr of devices:" +mNrOfDevices);
        }
        if(intent.getAction().equals(BtConnectionBroadcastReceiver.BROADCAST_DEVICE_DISCONNECTED)) {
            Log.d(TAG, "DISCONNECT BROADCAST RECEIVED");
            mac = intent.getStringExtra("mac");
            checkConnectedDevice(mac, false); // This removes a device from an internal list
            Log.d(TAG, "Activity nr of devices:" +mNrOfDevices);
            if(mNrOfDevices < 1) {
                Log.d(TAG, "No more connected devices");
                finish();
            }
        }
        abortBroadcast();
    }
};
}

When I run this code, I get the following chain:

Start MainActivity (not included, it only contains an activity with the default main layout, so that the applications receiver is registered)

Switch on a bluetooth device (This has been paired earlier, so android knows about it)

Wait until it connects and get this:

DEVICE CONNECTED

onCreate

onResume

Switch off the bluetooth device and I then get this:

DEVICE DISCONNECTED

onDestroy

onCreate

onResume

I can't grasp why the activity is getting destroyed restarting at this point. The activity is already running, the BroadcastReceiver only sends a broadcast to an already running activity. I can't figure out why there's a reason for the Activity to kill itself and then restart again. This leaves me in a state of the Activity still running, but it is not the original Activity that was started.

I do however see something in the logcats that seem to have something to do with this, and it's in this sequencing;

06-02 15:45:09.156 26431 26431 D BT : DEVICE DISCONNECTED

06-02 15:45:09.213 19547 19547 D BluetoothAdapterService: handleMessage() - MESSAGE_PROFILE_CONNECTION_STATE_CHANGED

06-02 15:45:09.213 26431 26431 D BT : onDestroy

06-02 15:45:09.214 19547 19547 D BluetoothAdapterProperties: CONNECTION_STATE_CHANGE: FF:FF:20:00:C1:47: 2 -> 0

06-02 15:45:09.216  3502  3805 D CachedBluetoothDevice: onProfileStateChanged: profile HID newProfileState 0

06-02 15:45:09.237   414   414 W SurfaceFlinger: couldn't log to binary event log: overflow.

06-02 15:45:09.239 26431 26431 D BT : onCreate

06-02 15:45:09.243 26431 26431 D BT : onResume


来源: stackexchange

问:
Search icon not working in css
I am using the following code for css:

```<code>#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
</code>```

Search Box:

```<code><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
</code>```

It is looking like this:

However, I want the search box to look like this:

Please note that I have the png file in my css folder. This example is a replication of https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table.

答:
You write: "I have the png file in my css folder."

Where is the CSS folder: At the same level as your HTML file?

Then you should write background-image: url('css/searchicon.png');

ContentLicense: CC BY-SA 3.0

Title: Search icon not working in css

Body:
I am using the following code for css:

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

Search Box:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

It is looking like this:

However, I want the search box to look like this:

Please note that I have the png file in my css folder. This example is a replication of https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table.


问:
An error has ocurredJSPlugin.3005
I installed IE11 on server 2008r2.
I was trying to debug using IE11 and I am having the following error. The error I am having in the Dom Explorer tab is:

Diagnostic:

Exception in window.onload: Error: An error has ocurredJSPlugin.3005

Stack Trace:

```<code>Error: An error has ocurredJSPlugin.3005 at getString (res://C:\Program Files\Internet Explorer\F12Resources.dll/23/pluginhost/plugin.f12.js:5021:27) at ToolWindowHelpers.loadString (res://C:\Program Files\Internet Explorer\F12Resources.dll/23/Common/CommonMerged.js:5803:13) at TabPanes..
</code>```

答:
write this in your code into  tag like this:

```<code><head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
</head>
</code>```

if someone have the same problem

Title: An error has ocurredJSPlugin.3005

Body:
I installed IE11 on server 2008r2.
I was trying to debug using IE11 and I am having the following error. The error I am having in the Dom Explorer tab is:

Diagnostic:

Exception in window.onload: Error: An error has ocurredJSPlugin.3005

Stack Trace:

Error: An error has ocurredJSPlugin.3005 at getString (res://C:\Program Files\Internet Explorer\F12Resources.dll/23/pluginhost/plugin.f12.js:5021:27) at ToolWindowHelpers.loadString (res://C:\Program Files\Internet Explorer\F12Resources.dll/23/Common/CommonMerged.js:5803:13) at TabPanes..

Body:
write this in your code into  tag like this:

<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
</head>

if someone have the same problem


问:
How to catch data from <form enctype="json">
How can I show in console the data of a form in JSON format with a click function or before submit function?
I'm using this for the form with JSON</p>

```<code>    <form enctype='application/json'>
  <input name='url[0][namme]' value=''>
  <select name='url[0][type]'>
    <option>Document</option>
    <option>Audio</option>
    <option>Video</option>
  </select>
  <input name='url[0][link]' value=''>
      <button id="save" class="btn btn-default">Save</button>
       <button id="add" class="btn btn-default">ADD</button>

    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
    var cont =0;
        $("#save").click(function () {
            $("form").submit(function () {

                return false;
            });

        })
        $("#add").click(function () {
            cont++;
            $("form").append("<br><input name='url["+cont+"][namme]' value=''>  <select name='url["+cont+"][type]'>     <option>Document</option>   <option>Audio</option>      <option>Video</option>  </select>  <input name='url["+cont+"][link]' value=''>");
        });

    </script>
</code>```

答:
try this:
      console.log(JSON.stringify(data));</p>

Body:
How can I show in console the data of a form in JSON format with a click function or before submit function?
I'm using this for the form with JSON

    <form enctype='application/json'>
  <input name='url[0][namme]' value=''>
  <select name='url[0][type]'>
    <option>Document</option>
    <option>Audio</option>
    <option>Video</option>
  </select>
  <input name='url[0][link]' value=''>
      <button id="save" class="btn btn-default">Save</button>
       <button id="add" class="btn btn-default">ADD</button>

    </form>


问:
Look up of comma separated data in another table
I do have 2 tables where in the table data frame consist data with comma separated values.

Need to find out which category present in lookup data frame i.e. in Option 1 out of "Cat A, Cat B, Cat C" which category is present. if found, need to show the score against it.

incase multiple instance found, we need to show the score of first occurrence hence in first case Cat C and Cat Z both comes under Option 1 however we need to show the score for Cat C only which is 2.

Table

```<code>Option           | Cat
-----             ------
Option 1         | Cat A, Cat B, Cat C, Cat Z
Option 2         | Cat X, Cat Y, Cat Z, Cat B
Option 3         | Cat P, Cat Q, Cat R, Cat S, Cat T
Option 1         | Cat T
Option 3         | Cat E, Cat F
</code>```

Lookup

```<code>Cat   |   Option    |   Score

Cat A |   Option 2   |   8
Cat B |   Option 3   |   3
Cat C |   Option 1   |   2
Cat X |   Option 3   |   9
Cat Y |   Option 1   |   1
Cat Z |   Option 2   |   1
Cat P |   Option 3   |   2
Cat Q |   Option 2   |   9
Cat R |   Option 1   |   4
Cat S |   Option 4   |   0
Cat T |   Option 1   |   5
Cat E |   Option 4   |   1
Cat F |   Option 3   |   10
</code>```

Output

```<code> Option      |     Cat                                |     Found_cat    |     Score
 Option 1    |     Cat A, Cat B, Cat C                |     Cat C        |     2
 Option 2    |     Cat X, Cat Y, Cat Z, Cat B          |     Cat Z        |     1
 Option 3    |     Cat P, Cat Q, Cat R, Cat S, Cat T  |     Cat P        |     2
 Option 1    |     Cat T                              |     Cat T        |     5
 Option 3    |     Cat E, Cat F                       |     Cat F        |     10
</code>```

R Code for creating dataframe

```<code>Table <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                 Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y,Cat Z, Cat B", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"))

lookup <-data.frame(Cat = c("Cat A", "Cat B", "Cat C", "Cat X", "Cat Y", "Cat Z", "Cat P", "Cat Q", "Cat R", "Cat S", "Cat T", "Cat E", "Cat F"),
                    Options = c("Option 2", "Option 3", "Option 1", "Option 3", "Option 1", "Option 2", "Option 3", "Option 2", "Option 1", "Option 4", "Option 1", "Option 4", "Option 3"),
                    Score = c(8, 3, 2, 9, 1, 1, 2, 9, 4, 0, 5, 1, 10))

output <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                     Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y, Cat Z, Cat B,", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"),
                     Found_cat = c("Cat C", "Cat Z", "Cat P", "Cat T", "Cat F"),
                     Score = c(2, 1, 2, 5, 10))
</code>```

答:
I just give a quick try using loop:</p>

```<code>Table <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y, Cat Z, Cat B", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"),
                stringsAsFactors = F)

lookup <-data.frame(Cat = c("Cat A", "Cat B", "Cat C", "Cat X", "Cat Y", "Cat Z", "Cat P", "Cat Q", "Cat R", "Cat S", "Cat T", "Cat E", "Cat F"),
                Options = c("Option 2", "Option 3", "Option 1", "Option 3", "Option 1", "Option 2", "Option 3", "Option 2", "Option 1", "Option 4", "Option 1", "Option 4", "Option 3"),
                Score = c(8, 3, 2, 9, 1, 1, 2, 9, 4, 0, 5, 1, 10),
                stringsAsFactors = F)
app = matrix(nrow = nrow(Table), ncol = 2)
for (i in 1:nrow(Table)) {
lookup.cats = lookup$Cat[lookup$Options == Table$Option[i]]
Table.cats = unlist(strsplit(Table$Cat[i], split = ', '))
found.cat = intersect(lookup.cats, Table.cats)
score = lookup$Score[which(lookup$Cat == found.cat &
                               lookup$Options == Table$Option[i])]
app[i, 1] = found.cat
app[i, 2] = score
}
app = as.data.frame(app)
names(app) = c('Found_cat', 'Score')
cbind(Table, app)
</code>```

Body:
I do have 2 tables where in the table data frame consist data with comma separated values.

Need to find out which category present in lookup data frame i.e. in Option 1 out of "Cat A, Cat B, Cat C" which category is present. if found, need to show the score against it.

incase multiple instance found, we need to show the score of first occurrence hence in first case Cat C and Cat Z both comes under Option 1 however we need to show the score for Cat C only which is 2.

Table

Option           | Cat
-----             ------
Option 1         | Cat A, Cat B, Cat C, Cat Z
Option 2         | Cat X, Cat Y, Cat Z, Cat B
Option 3         | Cat P, Cat Q, Cat R, Cat S, Cat T
Option 1         | Cat T
Option 3         | Cat E, Cat F

Lookup

Cat   |   Option    |   Score

Cat A |   Option 2   |   8
Cat B |   Option 3   |   3
Cat C |   Option 1   |   2
Cat X |   Option 3   |   9
Cat Y |   Option 1   |   1
Cat Z |   Option 2   |   1
Cat P |   Option 3   |   2
Cat Q |   Option 2   |   9
Cat R |   Option 1   |   4
Cat S |   Option 4   |   0
Cat T |   Option 1   |   5
Cat E |   Option 4   |   1
Cat F |   Option 3   |   10

Output

 Option      |     Cat                                |     Found_cat    |     Score
 Option 1    |     Cat A, Cat B, Cat C                |     Cat C        |     2
 Option 2    |     Cat X, Cat Y, Cat Z, Cat B          |     Cat Z        |     1
 Option 3    |     Cat P, Cat Q, Cat R, Cat S, Cat T  |     Cat P        |     2
 Option 1    |     Cat T                              |     Cat T        |     5
 Option 3    |     Cat E, Cat F                       |     Cat F        |     10

R Code for creating dataframe

Table <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                 Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y,Cat Z, Cat B", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"))

lookup <-data.frame(Cat = c("Cat A", "Cat B", "Cat C", "Cat X", "Cat Y", "Cat Z", "Cat P", "Cat Q", "Cat R", "Cat S", "Cat T", "Cat E", "Cat F"),
                    Options = c("Option 2", "Option 3", "Option 1", "Option 3", "Option 1", "Option 2", "Option 3", "Option 2", "Option 1", "Option 4", "Option 1", "Option 4", "Option 3"),
                    Score = c(8, 3, 2, 9, 1, 1, 2, 9, 4, 0, 5, 1, 10))

output <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                     Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y, Cat Z, Cat B,", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"),
                     Found_cat = c("Cat C", "Cat Z", "Cat P", "Cat T", "Cat F"),
                     Score = c(2, 1, 2, 5, 10))

Body:
I just give a quick try using loop:

Table <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y, Cat Z, Cat B", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"),
                stringsAsFactors = F)

lookup <-data.frame(Cat = c("Cat A", "Cat B", "Cat C", "Cat X", "Cat Y", "Cat Z", "Cat P", "Cat Q", "Cat R", "Cat S", "Cat T", "Cat E", "Cat F"),
                Options = c("Option 2", "Option 3", "Option 1", "Option 3", "Option 1", "Option 2", "Option 3", "Option 2", "Option 1", "Option 4", "Option 1", "Option 4", "Option 3"),
                Score = c(8, 3, 2, 9, 1, 1, 2, 9, 4, 0, 5, 1, 10),
                stringsAsFactors = F)
app = matrix(nrow = nrow(Table), ncol = 2)
for (i in 1:nrow(Table)) {
lookup.cats = lookup$Cat[lookup$Options == Table$Option[i]]
Table.cats = unlist(strsplit(Table$Cat[i], split = ', '))
found.cat = intersect(lookup.cats, Table.cats)
score = lookup$Score[which(lookup$Cat == found.cat &
                               lookup$Options == Table$Option[i])]
app[i, 1] = found.cat
app[i, 2] = score
}
app = as.data.frame(app)
names(app) = c('Found_cat', 'Score')
cbind(Table, app)


问:
Should JSON-RPC return error upon bad response?
The client request was good, but the server response was bad.  Should the client respond to the server that the response was invalid?

If the reverse was true (i.e. server request is good, client request is bad), should the same approach be taken?

Should the request identifier be included?

```<code>--> {"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}
<-- {"jsonrpc": "2.0", "id": 3} /* Note that results property is missing */

--> {"jsonrpc": "2.0", "error": {"code": -123, "message": "Results property is missing"}}
</code>```

答:
The JSON-RPC protocol doesn't specify responses from the client. In the same way, the server doesn't send requests.

Client sends Request objects and server returns Response objects.

You may create a method in server to receive such notifications, but it is at the application level, not related to the JSON-RPC protocol.

```<code>--> {"jsonrpc": "2.0", "method": "reportError", "params": {"method": "subtract", "error": "Results property is missing" } }
</code>```

Body:
The client request was good, but the server response was bad.  Should the client respond to the server that the response was invalid?

If the reverse was true (i.e. server request is good, client request is bad), should the same approach be taken?

Should the request identifier be included?

--> {"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}
<-- {"jsonrpc": "2.0", "id": 3} /* Note that results property is missing */

--> {"jsonrpc": "2.0", "error": {"code": -123, "message": "Results property is missing"}}

Body:
The JSON-RPC protocol doesn't specify responses from the client. In the same way, the server doesn't send requests.

Client sends Request objects and server returns Response objects.

You may create a method in server to receive such notifications, but it is at the application level, not related to the JSON-RPC protocol.

--> {"jsonrpc": "2.0", "method": "reportError", "params": {"method": "subtract", "error": "Results property is missing" } }


问:
Use data binding to set View visibility
Trying to set visibility of View using custom variable, but error occurs: Identifiers must have user defined types from the XML file. visible is missing it. Is it possible to set view visibility using data binding? Thanks.

```<code><data>
    <variable
        name="sale"
        type="java.lang.Boolean"/>
</data>

<FrameLayout android:visibility="@{sale ? visible : gone}"/>
</code>```

答:
As stated in the Android Developer Guide, you need to do it like this:</p>

```<code><data>
    <import type="android.view.View"/>
    <variable
        name="sale"
        type="java.lang.Boolean"/>
</data>

<FrameLayout android:visibility="@{sale ? View.GONE : View.VISIBLE}"/>
</code>```

Title: Use data binding to set View visibility

Body:
Trying to set visibility of View using custom variable, but error occurs: Identifiers must have user defined types from the XML file. visible is missing it. Is it possible to set view visibility using data binding? Thanks.

<data>
    <variable
        name="sale"
        type="java.lang.Boolean"/>
</data>

<FrameLayout android:visibility="@{sale ? visible : gone}"/>

Body:
As stated in the Android Developer Guide, you need to do it like this:

<data>
    <import type="android.view.View"/>
    <variable
        name="sale"
        type="java.lang.Boolean"/>
</data>

<FrameLayout android:visibility="@{sale ? View.GONE : View.VISIBLE}"/>


答:
Depending on your file structure I don't believe you are referencing the image like you'd want to.

Instead of:

```<code>background-image: url('/css/searchicon.png');
</code>```

Do:

```<code>background-image: url('css/searchicon.png');
</code>```

OR

```<code>background-image: url('https://www.w3schools.com/css/searchicon.png');
</code>```

Title: Search icon not working in css

Body:
Depending on your file structure I don't believe you are referencing the image like you'd want to.

Instead of:

background-image: url('/css/searchicon.png');

Do:

background-image: url('css/searchicon.png');

OR

background-image: url('https://www.w3schools.com/css/searchicon.png');


问:
Download file using POST method using webview android
I am downloading .pdf file using chrome, firefox browser and It successfully download file. But when same file url are used in web view It won't download file.
I am using Request Method : POST. Is there any way to download this type of file?

I have seen this link: Android WebView download not working

Can Any one solve my issue to use other way of downloading?

Thank you

答:
Use  MultiThreadDownloader plugin for android , so you can get direct link of files in webview by below codes :

```<code>mWebView.setDownloadListener(new DownloadListener() {
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
       // download(Uri.parse(url));
    }
});
</code>```

When you get a direct link from webview , you can pass it to MultiThreadDownloader , for download it.

Body:
Use  MultiThreadDownloader plugin for android , so you can get direct link of files in webview by below codes :

mWebView.setDownloadListener(new DownloadListener() {
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
       // download(Uri.parse(url));
    }
});

When you get a direct link from webview , you can pass it to MultiThreadDownloader , for download it.


问:
How to append the hex color code
Im using jquery-ui to make a color picker and im almost done with it.
But i was wondering how i could append the hex color code.

HTML

```<code> <div id="slider-horizontal"></div>
 <div class="pin"></div>
</code>```

JQUERY

```<code>$(function() {
    var box = $('.pin')[0];

    $("#slider-horizontal").slider({
        orientation: "horizontal",
        min: 0,
        max: 360,
        value: 0,
        slide: function(event, ui) {
            box.style.background = 'hsl(' + ui.value + ', 100%, 50%)';
        }
    });
});
</code>```

Any guidance would be appreciated. Thanks very much.

答:
This page has many functions for converting from HSL to RGB. Using this function, you could have a div that has the RGB value in it, updated with the slide event along with the background color. Here is a snippet of the function:

```<code>/**
 * Converts an HSL color value to RGB. Conversion formula
 * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
 * Assumes h, s, and l are contained in the set [0, 1] and
 * returns r, g, and b in the set [0, 255].
 *
 * @param   Number  h       The hue
 * @param   Number  s       The saturation
 * @param   Number  l       The lightness
 * @return  Array           The RGB representation
 */
function hslToRgb(h, s, l){
    var r, g, b;

    if(s == 0){
        r = g = b = l; // achromatic
    }else{
        function hue2rgb(p, q, t){
            if(t < 0) t += 1;
            if(t > 1) t -= 1;
            if(t < 1/6) return p + (q - p) * 6 * t;
            if(t < 1/2) return q;
            if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        }

        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return [r * 255, g * 255, b * 255];
}
</code>```

Going from RGB to HEX is much simpler, and can be achieved with the following functions from this SO answer:

```<code>function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
    return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
</code>```

Title: How to append the hex color code

Body:
Im using jquery-ui to make a color picker and im almost done with it.
But i was wondering how i could append the hex color code.

HTML

JQUERY

$(function() {
    var box = $('.pin')[0];

    $("#slider-horizontal").slider({
        orientation: "horizontal",
        min: 0,
        max: 360,
        value: 0,
        slide: function(event, ui) {
            box.style.background = 'hsl(' + ui.value + ', 100%, 50%)';
        }
    });
});

Any guidance would be appreciated. Thanks very much.

Body:
This page has many functions for converting from HSL to RGB. Using this function, you could have a div that has the RGB value in it, updated with the slide event along with the background color. Here is a snippet of the function:

/**
 * Converts an HSL color value to RGB. Conversion formula
 * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
 * Assumes h, s, and l are contained in the set [0, 1] and
 * returns r, g, and b in the set [0, 255].
 *
 * @param   Number  h       The hue
 * @param   Number  s       The saturation
 * @param   Number  l       The lightness
 * @return  Array           The RGB representation
 */
function hslToRgb(h, s, l){
    var r, g, b;

    if(s == 0){
        r = g = b = l; // achromatic
    }else{
        function hue2rgb(p, q, t){
            if(t < 0) t += 1;
            if(t > 1) t -= 1;
            if(t < 1/6) return p + (q - p) * 6 * t;
            if(t < 1/2) return q;
            if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        }

        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return [r * 255, g * 255, b * 255];
}

Going from RGB to HEX is much simpler, and can be achieved with the following functions from this SO answer:

function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
    return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}


问:
With Auto Layout, how do I make a UIImageView's size dynamic depending on the image?
I want my UIImageView to grow or shrink depending on the size of what the actual image it's displaying is. But I want it to stay vertically centered and 10pts from the leading edge of the superview.

However, if I set these two constraints it complains I haven't set up enough constraints to satisfy Auto Layout. To me it seems to perfectly describe what I want. What am I missing?

答:
Here is an AspectFit UIImageView-derived implementation that works with Auto Layout when only one dimension is constrained. The other one will be set automatically. It will keep image aspect ratio and doesn't add any margins around the image.

It's tweaked Objective-C implementation of @algal idea with the following differences:

Expression priority = (UILayoutPriorityDefaultLow +
UILayoutPriorityFittingSizeLevel) / 2.0 which evaluates to 150
isn't enough to beat the priority of 1000 of the default image
content size constraint. So aspect constraint priority was increased
to 1000 as well.

it removes\re-adds the aspect ratio constraint only if necessary.
Keep in mind that this is heavy operation so there is no need to do
so if aspect ratio is the same. Moreover, image setter could be called multiple times, so it's a good idea to not cause extra layout calculations here.

not sure why we need to override required public init?(coder
aDecoder: NSCoder) and public override init(frame:CGRect), so
these two are taken out. They aren't overridden by UIImageView,
that's why there is no point of adding the aspect constraint until an image is set.

AspectKeepUIImageView.h:

```<code>NS_ASSUME_NONNULL_BEGIN

@interface AspectKeepUIImageView : UIImageView

- (instancetype)initWithImage:(nullable UIImage *)image;
- (instancetype)initWithImage:(nullable UIImage *)image highlightedImage:(nullable UIImage *)highlightedImage;

@end

NS_ASSUME_NONNULL_END
</code>```

AspectKeepUIImageView.m:

```<code>#import "AspectKeepUIImageView.h"

@implementation AspectKeepUIImageView
{
    NSLayoutConstraint *_aspectContraint;
}

- (instancetype)initWithImage:(nullable UIImage *)image
{
    self = [super initWithImage:image];

    [self initInternal];

    return self;
}

- (instancetype)initWithImage:(nullable UIImage *)image highlightedImage:(nullable UIImage *)highlightedImage
{
    self = [super initWithImage:image highlightedImage:highlightedImage];

    [self initInternal];

    return self;
}

- (void)initInternal
{
    self.contentMode = UIViewContentModeScaleAspectFit;
    [self updateAspectConstraint];
}

- (void)setImage:(UIImage *)image
{
    [super setImage:image];
    [self updateAspectConstraint];
}

- (void)updateAspectConstraint
{
    CGSize imageSize = self.image.size;
    CGFloat aspectRatio = imageSize.height > 0.0f
        ? imageSize.width / imageSize.height
        : 0.0f;
    if (_aspectContraint.multiplier != aspectRatio)
    {
        [self removeConstraint:_aspectContraint];

        _aspectContraint =
        [NSLayoutConstraint constraintWithItem:self
                                     attribute:NSLayoutAttributeWidth
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:self
                                     attribute:NSLayoutAttributeHeight
                                    multiplier:aspectRatio
                                      constant:0.f];

        _aspectContraint.priority = UILayoutPriorityRequired;

        [self addConstraint:_aspectContraint];
    }
}

@end
</code>```

Body:
Here is an AspectFit UIImageView-derived implementation that works with Auto Layout when only one dimension is constrained. The other one will be set automatically. It will keep image aspect ratio and doesn't add any margins around the image.

It's tweaked Objective-C implementation of @algal idea with the following differences:

Expression priority = (UILayoutPriorityDefaultLow +
UILayoutPriorityFittingSizeLevel) / 2.0 which evaluates to 150
isn't enough to beat the priority of 1000 of the default image
content size constraint. So aspect constraint priority was increased
to 1000 as well.

it removes\re-adds the aspect ratio constraint only if necessary.
Keep in mind that this is heavy operation so there is no need to do
so if aspect ratio is the same. Moreover, image setter could be called multiple times, so it's a good idea to not cause extra layout calculations here.

not sure why we need to override required public init?(coder
aDecoder: NSCoder) and public override init(frame:CGRect), so
these two are taken out. They aren't overridden by UIImageView,
that's why there is no point of adding the aspect constraint until an image is set.

AspectKeepUIImageView.h:

NS_ASSUME_NONNULL_BEGIN

@interface AspectKeepUIImageView : UIImageView

- (instancetype)initWithImage:(nullable UIImage *)image;
- (instancetype)initWithImage:(nullable UIImage *)image highlightedImage:(nullable UIImage *)highlightedImage;

@end

NS_ASSUME_NONNULL_END

AspectKeepUIImageView.m:

#import "AspectKeepUIImageView.h"

@implementation AspectKeepUIImageView
{
    NSLayoutConstraint *_aspectContraint;
}

- (instancetype)initWithImage:(nullable UIImage *)image
{
    self = [super initWithImage:image];

    [self initInternal];

    return self;
}

- (instancetype)initWithImage:(nullable UIImage *)image highlightedImage:(nullable UIImage *)highlightedImage
{
    self = [super initWithImage:image highlightedImage:highlightedImage];

    [self initInternal];

    return self;
}

- (void)initInternal
{
    self.contentMode = UIViewContentModeScaleAspectFit;
    [self updateAspectConstraint];
}

- (void)setImage:(UIImage *)image
{
    [super setImage:image];
    [self updateAspectConstraint];
}

- (void)updateAspectConstraint
{
    CGSize imageSize = self.image.size;
    CGFloat aspectRatio = imageSize.height > 0.0f
        ? imageSize.width / imageSize.height
        : 0.0f;
    if (_aspectContraint.multiplier != aspectRatio)
    {
        [self removeConstraint:_aspectContraint];

        _aspectContraint =
        [NSLayoutConstraint constraintWithItem:self
                                     attribute:NSLayoutAttributeWidth
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:self
                                     attribute:NSLayoutAttributeHeight
                                    multiplier:aspectRatio
                                      constant:0.f];

        _aspectContraint.priority = UILayoutPriorityRequired;

        [self addConstraint:_aspectContraint];
    }
}

@end


问:
How to paste mulple excel range as picture to outlook at the same time
please help me fix this. I'm new to this area and I would like to paste multiple set of range from excel and paste it onto an outlook email with modified size. Please help me. Thanks in advance!

Here's my current code:

```<code>Sub EmailSend()

    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    Dim StrBody As String

    StrBody = "Please see our current Report"

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    'Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want
    Set rng = Range("C4:D8").SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next

    With OutMail
        .To = "x"
        .CC = "x"
        .BCC = "x"
        .Subject = "RRF for Vendor Sourcing - " & Cells(3, 2)
        .HTMLBody = StrBody & RangetoHTML(rng)
        .Display   'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub
</code>```

答:
This line of code is what defines your range.

```<code> Set rng = Range("C4:D8").SpecialCells(xlCellTypeVisible)
</code>```

You can simply define another range :

```<code>Dim rng2 As Range
Set rng2 = Range("J4:N8").SpecialCells(xlCellTypeVisible)
</code>```

and then make another call to RangetoHTML() using that second range:

```<code>RangetoHTML(rng2)
</code>```

which will return another string of html which you can then concatenate like this:

```<code> .HTMLBody = StrBody & RangetoHTML(rng) & "<br>" & RangetoHTML(rng2)
</code>```

Body:
please help me fix this. I'm new to this area and I would like to paste multiple set of range from excel and paste it onto an outlook email with modified size. Please help me. Thanks in advance!

Here's my current code:

Sub EmailSend()

    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    Dim StrBody As String

    StrBody = "Please see our current Report"

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    'Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want
    Set rng = Range("C4:D8").SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next

    With OutMail
        .To = "x"
        .CC = "x"
        .BCC = "x"
        .Subject = "RRF for Vendor Sourcing - " & Cells(3, 2)
        .HTMLBody = StrBody & RangetoHTML(rng)
        .Display   'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Body:
This line of code is what defines your range.

 Set rng = Range("C4:D8").SpecialCells(xlCellTypeVisible)

You can simply define another range :

Dim rng2 As Range
Set rng2 = Range("J4:N8").SpecialCells(xlCellTypeVisible)

and then make another call to RangetoHTML() using that second range:

RangetoHTML(rng2)

which will return another string of html which you can then concatenate like this:

 .HTMLBody = StrBody & RangetoHTML(rng) & "<br>" & RangetoHTML(rng2)


问:
CompileError: WebAssembly.compile()
I am trying to execute basic C code of calculating factorial in WebAssembly and when I am loading WASM file in Google Chrome ( 57.0.2987.98) I am getting

CompileError: WebAssembly.compile():

  Wasm decoding failedResult = expected magic word 00 61 73 6d,

  found 30 30 36 31 @+0`

C Code :

```<code>double fact(int i) {
  long long n = 1;
  for (;i > 0; i--) {
    n *= i;
  }
  return (double)n;
}
</code>```

WAST :

```<code>(module
  (table 0 anyfunc)
  (memory $0 1)
  (export "memory" (memory $0))
  (export "_Z4facti" (func $_Z4facti))
  (func $_Z4facti (param $0 i32) (result f64)
    (local $1 i64)
    (local $2 i64)
    (block $label$0
      (br_if $label$0
        (i32.lt_s
          (get_local $0)
          (i32.const 1)
        )
      )
      (set_local $1
        (i64.add
          (i64.extend_s/i32
            (get_local $0)
          )
          (i64.const 1)
        )
      )
      (set_local $2
        (i64.const 1)
      )
      (loop $label$1
        (set_local $2
          (i64.mul
            (get_local $2)
            (tee_local $1
              (i64.add
                (get_local $1)
                (i64.const -1)
              )
            )
          )
        )
        (br_if $label$1
          (i64.gt_s
            (get_local $1)
            (i64.const 1)
          )
        )
      )
      (return
        (f64.convert_s/i64
          (get_local $2)
        )
      )
    )
    (f64.const 1)
  )
)
</code>```

WASM Compiled Code :

```<code>0061 736d 0100 0000 0186 8080 8000 0160
017f 017c 0382 8080 8000 0100 0484 8080
8000 0170 0000 0583 8080 8000 0100 0106
8180 8080 0000 0795 8080 8000 0206 6d65
6d6f 7279 0200 085f 5a34 6661 6374 6900
000a c380 8080 0001 bd80 8080 0001 027e
0240 2000 4101 480d 0020 00ac 4201 7c21
0142 0121 0203 4020 0220 0142 7f7c 2201
7e21 0220 0142 0155 0d00 0b20 02b9 0f0b
4400 0000 0000 00f0 3f0b
`
</code>```

Code executed in Chrome :

```<code> async function load(){
        let binary = await fetch('https://flinkhub.com/t.wasm');
        let bytes = await binary.arrayBuffer();
        console.log(bytes);

        let module = await WebAssembly.compile(bytes);
        let instance = await WebAssembly.Instance(module);
    }
    load().then(instance => console.log(instance.exports.fact(3)));
</code>```

Can anyone help me out, I have been stuck on this for a whole day and not able to understand what is going wrong.
I used WebAssembly Explorer to to get the WAST and WASM code.

答: In general, this error means that instead of the binary .wasm file your browser received something else. That can be a error page generated by the web server or the same .wasm but corrupted somehow. I recommend to open your browser Developer Tools, go to Network tab, Refresh the page and look at the .wasm resource request and response.</p>

Title: CompileError: WebAssembly.compile()

Body:
I am trying to execute basic C code of calculating factorial in WebAssembly and when I am loading WASM file in Google Chrome ( 57.0.2987.98) I am getting

CompileError: WebAssembly.compile():

  Wasm decoding failedResult = expected magic word 00 61 73 6d,

  found 30 30 36 31 @+0`

C Code :

double fact(int i) {
  long long n = 1;
  for (;i > 0; i--) {
    n *= i;
  }
  return (double)n;
}

WAST :

(module
  (table 0 anyfunc)
  (memory $0 1)
  (export "memory" (memory $0))
  (export "_Z4facti" (func $_Z4facti))
  (func $_Z4facti (param $0 i32) (result f64)
    (local $1 i64)
    (local $2 i64)
    (block $label$0
      (br_if $label$0
        (i32.lt_s
          (get_local $0)
          (i32.const 1)
        )
      )
      (set_local $1
        (i64.add
          (i64.extend_s/i32
            (get_local $0)
          )
          (i64.const 1)
        )
      )
      (set_local $2
        (i64.const 1)
      )
      (loop $label$1
        (set_local $2
          (i64.mul
            (get_local $2)
            (tee_local $1
              (i64.add
                (get_local $1)
                (i64.const -1)
              )
            )
          )
        )
        (br_if $label$1
          (i64.gt_s
            (get_local $1)
            (i64.const 1)
          )
        )
      )
      (return
        (f64.convert_s/i64
          (get_local $2)
        )
      )
    )
    (f64.const 1)
  )
)

WASM Compiled Code :

0061 736d 0100 0000 0186 8080 8000 0160
017f 017c 0382 8080 8000 0100 0484 8080
8000 0170 0000 0583 8080 8000 0100 0106
8180 8080 0000 0795 8080 8000 0206 6d65
6d6f 7279 0200 085f 5a34 6661 6374 6900
000a c380 8080 0001 bd80 8080 0001 027e
0240 2000 4101 480d 0020 00ac 4201 7c21
0142 0121 0203 4020 0220 0142 7f7c 2201
7e21 0220 0142 0155 0d00 0b20 02b9 0f0b
4400 0000 0000 00f0 3f0b
`

Code executed in Chrome :

 async function load(){
        let binary = await fetch('https://flinkhub.com/t.wasm');
        let bytes = await binary.arrayBuffer();
        console.log(bytes);

        let module = await WebAssembly.compile(bytes);
        let instance = await WebAssembly.Instance(module);
    }
    load().then(instance => console.log(instance.exports.fact(3)));

Can anyone help me out, I have been stuck on this for a whole day and not able to understand what is going wrong.
I used WebAssembly Explorer to to get the WAST and WASM code.


问:
Java/Android Regex expression to allow names that may have apostrophe and/or hyphen
My user name validation currently only allows upper and/or lower case letters , however I want to support:

Regular names like "James Bond" OR  Montagu-Stuart-Wortley-Mackenzie OR De'wayne OR De' wayne (notice the space after apostrophe) OR M'ontagu-S'tuart-W'ortley-M' ackenzie (space,apostrophe and hyphen allowed)

Here is current code:

```<code> private void checkFirstNameInput(){
        String firstName = edtFirstName.getText().toString();
        Pattern p = Pattern.compile("[^A-Za-z]");
        Matcher matcherFirstName = p.matcher(firstName);
        boolean firstNameValid = firstName.trim().length() >= 1 && !matcherFirstName.find();

        if(firstNameValid){
            edtFirstName.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context, R.drawable.check_icon), null);
            edtFirstName.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_gray));
            APrefs.registeringUser.setFirstName(edtFirstName.getText().toString().trim());

        }else{
            edtFirstName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            edtFirstName.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_gray));

        }
        txtError.setVisibility(View.GONE);
        checkNextButton();

    }
</code>```

I tried ^[a-zA-Z'-]$ and also search other posts, but no success.

Thanks & much appreciated.

答:
Use this:

```<code>^[a-zA-Z'\\-\\s]+$
</code>```

I've tested it now and it works (already escaped for Java, don't add more slashes)

```<code>Pattern pattern = Pattern.compile("^[a-zA-Z'\\-\\s]+$");
Matcher matcherFirstName = pattern.matcher("M'ontagu-S'tuart-W'ortley-M' ackenzie");
matcherFirstName.find(); //true
</code>```

Body:
My user name validation currently only allows upper and/or lower case letters , however I want to support:

Regular names like "James Bond" OR  Montagu-Stuart-Wortley-Mackenzie OR De'wayne OR De' wayne (notice the space after apostrophe) OR M'ontagu-S'tuart-W'ortley-M' ackenzie (space,apostrophe and hyphen allowed)

Here is current code:

 private void checkFirstNameInput(){
        String firstName = edtFirstName.getText().toString();
        Pattern p = Pattern.compile("[^A-Za-z]");
        Matcher matcherFirstName = p.matcher(firstName);
        boolean firstNameValid = firstName.trim().length() >= 1 && !matcherFirstName.find();

        if(firstNameValid){
            edtFirstName.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context, R.drawable.check_icon), null);
            edtFirstName.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_gray));
            APrefs.registeringUser.setFirstName(edtFirstName.getText().toString().trim());

        }else{
            edtFirstName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            edtFirstName.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_gray));

        }
        txtError.setVisibility(View.GONE);
        checkNextButton();

    }

I tried ^[a-zA-Z'-]$ and also search other posts, but no success.

Thanks & much appreciated.

Body:
Use this:

^[a-zA-Z'\\-\\s]+$

I've tested it now and it works (already escaped for Java, don't add more slashes)

Pattern pattern = Pattern.compile("^[a-zA-Z'\\-\\s]+$");
Matcher matcherFirstName = pattern.matcher("M'ontagu-S'tuart-W'ortley-M' ackenzie");
matcherFirstName.find(); //true


答: Maybe your image url is not correct, check it and answer me if it was a problem. </p>

Title: Search icon not working in css

Body:
I am using the following code for css:

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

Search Box:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

It is looking like this:

However, I want the search box to look like this:

Please note that I have the png file in my css folder. This example is a replication of https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table.


问:
Visual Basic in excel drop down list population based on a key
I have been attempting to create a drop down list on a worksheet that populates based on the entry in a different cell i.e

```<code>ws1-------------------------------
|numbers|dropdowns               |
|123    |->123 associations list |
|456    |->456 associations list |
----------------------------------

ws2----------------------
|123    | tttttt | 9000 |
|123    | kkkkkk | 8000 |
|123    | hhhhhh | 7000 |
|456    | yyyyyy | 6000 |
|456    | uuuuuu | 5000 |
-------------------------
</code>```

so that when 123 or 456 is typed into the numbers cell, the drop down list populates from the associated cells in ws2 i.e

"typed by user"| "auto populates list"

|456           | yyyyyy-6000      |

- uuuuuu-5000

then the user can select yyyyyy or uuuuuu and the cell would populate with the character cell value from the list selection.

答:
Here's a version of my pick list app.

in the change event for the worksheet where you enter the numbers:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("A5")) Is Nothing Then Fill_X_list (Me.Range("A5"))
End Sub
</code>```

In the code module:

```<code>Sub Fill_X_list(myX As String)
Dim locx As Long, YBottom As Long
Dim listcounter As Long
Application.EnableEvents = False
Application.ScreenUpdating = False
listcounter = 2
Sheets("Lists").Range("A:Z").ClearContents
Sheets("Lists").Range("A1") = myX
Sheets("WS1").Range("C5") = "All Values"
YBottom = Sheets("WS2").Cells(Rows.Count, 1).End(xlUp).Row

For locx = 1 To YBottom
    If Sheets("WS2").Cells(locx, 1) = myX Then
        Sheets("lists").Cells(listcounter, 1) = Sheets("WS2").Cells(locx, 2) & "-" & Sheets("WS2").Cells(locx, 3)
        listcounter = listcounter + 1
    End If
Next locx

Sheets("Lists").Range("A2:A" & Sheets("lists").Cells(Rows.Count, 1).End(xlUp).Row).Name = "YList"
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
</code>```

The cell where you enter the '123' should be the range in the on change event (i.e A5).  The range sheets ("lists").cells ("A2:A3") should be named "YList."  the size of the range will change when the sub runs.

The cell where the pick list is, should have validation "list" with source = YList.

I think that's it.  If I missed anything let me know.  I have a working example.

Body:
I have been attempting to create a drop down list on a worksheet that populates based on the entry in a different cell i.e

ws1-------------------------------
|numbers|dropdowns               |
|123    |->123 associations list |
|456    |->456 associations list |
----------------------------------

ws2----------------------
|123    | tttttt | 9000 |
|123    | kkkkkk | 8000 |
|123    | hhhhhh | 7000 |
|456    | yyyyyy | 6000 |
|456    | uuuuuu | 5000 |
-------------------------

so that when 123 or 456 is typed into the numbers cell, the drop down list populates from the associated cells in ws2 i.e

"typed by user"| "auto populates list"

|456           | yyyyyy-6000      |

- uuuuuu-5000

then the user can select yyyyyy or uuuuuu and the cell would populate with the character cell value from the list selection.

Body:
Here's a version of my pick list app.

in the change event for the worksheet where you enter the numbers:

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("A5")) Is Nothing Then Fill_X_list (Me.Range("A5"))
End Sub

In the code module:

Sub Fill_X_list(myX As String)
Dim locx As Long, YBottom As Long
Dim listcounter As Long
Application.EnableEvents = False
Application.ScreenUpdating = False
listcounter = 2
Sheets("Lists").Range("A:Z").ClearContents
Sheets("Lists").Range("A1") = myX
Sheets("WS1").Range("C5") = "All Values"
YBottom = Sheets("WS2").Cells(Rows.Count, 1).End(xlUp).Row

For locx = 1 To YBottom
    If Sheets("WS2").Cells(locx, 1) = myX Then
        Sheets("lists").Cells(listcounter, 1) = Sheets("WS2").Cells(locx, 2) & "-" & Sheets("WS2").Cells(locx, 3)
        listcounter = listcounter + 1
    End If
Next locx

Sheets("Lists").Range("A2:A" & Sheets("lists").Cells(Rows.Count, 1).End(xlUp).Row).Name = "YList"
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

The cell where you enter the '123' should be the range in the on change event (i.e A5).  The range sheets ("lists").cells ("A2:A3") should be named "YList."  the size of the range will change when the sub runs.

The cell where the pick list is, should have validation "list" with source = YList.

I think that's it.  If I missed anything let me know.  I have a working example.


问:
TeamCity : NUnit fails to find dependency of target assembly
```<code>Windows 10
Visual Studio 2017
TeamCity 2017.1.2
GitHub
</code>```

I'm working with a VS solution that locally behaves as expected. Main-project has some package dependencies. Test-project has project-ref to main project. VS local compile succeeds. Main-project refs + dependencies are copied to MyProject/bin/debug; test-project refs + dependencies are copied to MyProject.Tests/bin/debug; ReSharper local run of tests succeeds.

However my TC project has problems running tests.

My build-config steps are : pull from GitHub , run Visual Studio (sln) build , trigger NUnit.ConsoleRunner to run tests vs built assembly - which throws a file not found error (can't find package dependency assembly ) that perhaps indicate the build steps needs to save as artifact the dependent assembly and copy it to the test output dir.

However looking at the agent work dir I find the dependency assembly present in both the main-project and the test-project :

```<code>C:\TeamCity\buildAgent\work\64f706c42d79250c\{main-project}\bin\Debug\{dependency}.dll
</code>```

and

```<code>C:\TeamCity\buildAgent\work\64f706c42d79250c\{tests-project}\bin\Debug\{dependency}.dll
</code>```

which indicates that VS build step copied {dependency}.dll into bin as expected.

So why can't NUnit find it ?

```<code>[19:27:48][Step 5/5] MyProject.dll
[19:27:48][MyProject.dll] MyProject.UnitTests.MyTest
[19:27:49][MyProject.UnitTests.MyTest] System.IO.FileNotFoundException : Could not load file or assembly 'MyProjectDependency, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
[19:27:49]
[MyProject.UnitTests.MyTest]    at ReferencingCode()
   at MyProject.MyClass.Answer() in C:\TeamCity\buildAgent\work\64f706c42d79250c\MyProject\MyClass.cs:line 9
   at MyProject.UnitTests.MyTest() in C:\TeamCity\buildAgent\work\64f706c42d79250c\MyProject\UnitTests.cs:line 10
[19:27:51][Step 5/5] Failed tests detected
</code>```

I'm wondering if the output dirs are different for the VS Build and NUnit steps ?  But my agent work dir is identical to my local VS solution dir - so where would TC be locating the NUnit work dir ?

答:
For your tests to run, locally or in TeamCity, your test project must have a project reference to the project you are testing. It does not work any other way. How else would it know what to test? So check your references in the test project, and make sure the output is the same place when the build runs as "Debug" and "Release".

On a side note, letting TC do the actual build and test is fine for simple stuff but it's very hard to troubleshoot. I recommend you build a PowerShell script with PSake and create a "Test" task. That way you can run the script locally and TeamCity can use the same script you are running locally.

Body:
Windows 10
Visual Studio 2017
TeamCity 2017.1.2
GitHub

I'm working with a VS solution that locally behaves as expected. Main-project has some package dependencies. Test-project has project-ref to main project. VS local compile succeeds. Main-project refs + dependencies are copied to MyProject/bin/debug; test-project refs + dependencies are copied to MyProject.Tests/bin/debug; ReSharper local run of tests succeeds.

However my TC project has problems running tests.

My build-config steps are : pull from GitHub , run Visual Studio (sln) build , trigger NUnit.ConsoleRunner to run tests vs built assembly - which throws a file not found error (can't find package dependency assembly ) that perhaps indicate the build steps needs to save as artifact the dependent assembly and copy it to the test output dir.

However looking at the agent work dir I find the dependency assembly present in both the main-project and the test-project :

C:\TeamCity\buildAgent\work\64f706c42d79250c\{main-project}\bin\Debug\{dependency}.dll

and

C:\TeamCity\buildAgent\work\64f706c42d79250c\{tests-project}\bin\Debug\{dependency}.dll

which indicates that VS build step copied {dependency}.dll into bin as expected.

So why can't NUnit find it ?

[19:27:48][Step 5/5] MyProject.dll
[19:27:48][MyProject.dll] MyProject.UnitTests.MyTest
[19:27:49][MyProject.UnitTests.MyTest] System.IO.FileNotFoundException : Could not load file or assembly 'MyProjectDependency, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
[19:27:49]
[MyProject.UnitTests.MyTest]    at ReferencingCode()
   at MyProject.MyClass.Answer() in C:\TeamCity\buildAgent\work\64f706c42d79250c\MyProject\MyClass.cs:line 9
   at MyProject.UnitTests.MyTest() in C:\TeamCity\buildAgent\work\64f706c42d79250c\MyProject\UnitTests.cs:line 10
[19:27:51][Step 5/5] Failed tests detected

I'm wondering if the output dirs are different for the VS Build and NUnit steps ?  But my agent work dir is identical to my local VS solution dir - so where would TC be locating the NUnit work dir ?


问:
XML file or database in this particular case (file updated frequently)
I have a list of URL and I should loop over them every minute or so and save the last successful access time into an XML file or database. Obviously, the URL and some short description will be saved in file as well.

I'm wondering whether XML files are reliable enough or I'm better with a database? If I must go with the database option, which one?

Please advise. Thanks.

答: I would not use XML. To modify an XML file you have to rewrite it, XML is not good at random read and writes, unless you can modify it only in memory and then write it when needed. Well, every minute is not a problem, unless the XML gets very large. An XML file is reliable as much as your application is in writing it. If you need more, you should consider a database. For local access something alike SQLite or Firebird embedded could be your choice.</p>

ContentLicense: CC BY-SA 2.5


问:
Get data from odk Aggregate
I want to get form data using api's.

http://localhost:8080/ODKAggregate/view/submissionList?formId=abcd returns me a list of uuid's like:

    <id>uuid:52af4a39-bf13-4305-b1a6-2b02d839dd7c</id>
<id>uuid:2e988c5b-8160-4d59-b2ee-6fe0728416bf</id>
<id>uuid:02c67418-8922-491d-a345-d41d223db949</id>
<id>uuid:4e06eb89-3f2c-4cef-b82b-38b725080c95</id>
<id>uuid:a3e2da91-719d-458d-bf9a-f15f4406eee7</id>
<id>uuid:19ff4408-0f6c-4e37-9d48-ecfb6d74b4e1</id>```

Now I want to download each submission individually using downloadSubmission api described here https://github.com/opendatakit/opendatakit/wiki/Briefcase-Aggregate-API

Can anybody tell what will be the exact format to call downloadSubmission?

Thanks in advance!

答:
../view/downloadSubmission?formId=YOURFORMID[@version=null@uiVersion=null]/YOURFORMID2*[@key=uuid:xyz]

*Look this up prefixed with each question in your form's XML

Title: Get data from odk Aggregate

Body:
I want to get form data using api's.

http://localhost:8080/ODKAggregate/view/submissionList?formId=abcd returns me a list of uuid's like:

    <id>uuid:52af4a39-bf13-4305-b1a6-2b02d839dd7c</id>
<id>uuid:2e988c5b-8160-4d59-b2ee-6fe0728416bf</id>
<id>uuid:02c67418-8922-491d-a345-d41d223db949</id>
<id>uuid:4e06eb89-3f2c-4cef-b82b-38b725080c95</id>
<id>uuid:a3e2da91-719d-458d-bf9a-f15f4406eee7</id>
<id>uuid:19ff4408-0f6c-4e37-9d48-ecfb6d74b4e1</id>

Now I want to download each submission individually using downloadSubmission api described here https://github.com/opendatakit/opendatakit/wiki/Briefcase-Aggregate-API

Can anybody tell what will be the exact format to call downloadSubmission?

Thanks in advance!


问:
How to proper design a REST API response?
We have a case where we have a rest endpoint and the response will be different depending on the application flow. The properties inside the json will differ, so the question is whether we want a response containing a json that will have different structure depending on application flow.

We basically have three options as I see it now. Either we could have two properties and one of them will always be null (customer or businessCustomer):

```<code>{
  "data": {
    "target": "Business",
    "customer": null,
    "businessCustomer": {
        ....
    }
}

{
  "data": {
    "target": "Customer",
    "customer": {
        ....
    },
    "businessCustomer": null,
}
</code>```

Or we will have only one property where the the contents of that json object will differ (customer always populated):

```<code>{
  "data": {
    "target": "Customer or business",
    "customer": {
        ....
    }
}
</code>```

I'm thinking it might be hard to consume the data with only one property. How would you serialize that in a smooth way in strongly typed langauges...

Which way is best? Thanks in advance!

答:
We faced similar scenario in our development and solved it using the resource type and created a base class for all it's sub-types. It is a generic implementation and the client side code is responsible for checking the @type and creating respective object from their side.

```<code>CustomerResource (Considering this as Base Class)
    BusinessCustomerResource (Extended from Customer Resource)
</code>```

For Business Customer Resource:

```<code>{
    "someOtherElement": "value",
    "customer" : {
                    "@type" : "BusinessCustomerResource",
                    "faxNumber" : "35635636",
                    "email" : "test@gmail.com",
                    "phone" : "2503334444",
                    "contactName" : "name",
                    "firstName" : "Owner",
                    "lastName" : "lastName"
                    ...
                    "address" : {
                      "@type" : "InternationalAddressResource",
                      "province" : "AB",
                      "country" : "Canada",
                      ...
                    }
                }
}
</code>```

For Customer Resource:

```<code>{
    "someOtherElement": "value",
    "customer" : {
                    "@type" : "CustomerResource",
                    "email" : "test@gmail.com",
                    "phone" : "2503334444",
                    "firstName" : "Owner",
                    "lastName" : "lastName"
                    ...
                    "address" : {
                      "@type" : "PostalAddressResource",
                      "province" : "AB",
                      "country" : "Canada",
                      ...
                    }
                }
}
</code>```

Body:
We have a case where we have a rest endpoint and the response will be different depending on the application flow. The properties inside the json will differ, so the question is whether we want a response containing a json that will have different structure depending on application flow.

We basically have three options as I see it now. Either we could have two properties and one of them will always be null (customer or businessCustomer):

{
  "data": {
    "target": "Business",
    "customer": null,
    "businessCustomer": {
        ....
    }
}

{
  "data": {
    "target": "Customer",
    "customer": {
        ....
    },
    "businessCustomer": null,
}

Or we will have only one property where the the contents of that json object will differ (customer always populated):

{
  "data": {
    "target": "Customer or business",
    "customer": {
        ....
    }
}

I'm thinking it might be hard to consume the data with only one property. How would you serialize that in a smooth way in strongly typed langauges...

Which way is best? Thanks in advance!

Body:
We faced similar scenario in our development and solved it using the resource type and created a base class for all it's sub-types. It is a generic implementation and the client side code is responsible for checking the @type and creating respective object from their side.

CustomerResource (Considering this as Base Class)
    BusinessCustomerResource (Extended from Customer Resource)

For Business Customer Resource:

{
    "someOtherElement": "value",
    "customer" : {
                    "@type" : "BusinessCustomerResource",
                    "faxNumber" : "35635636",
                    "email" : "test@gmail.com",
                    "phone" : "2503334444",
                    "contactName" : "name",
                    "firstName" : "Owner",
                    "lastName" : "lastName"
                    ...
                    "address" : {
                      "@type" : "InternationalAddressResource",
                      "province" : "AB",
                      "country" : "Canada",
                      ...
                    }
                }
}

For Customer Resource:

{
    "someOtherElement": "value",
    "customer" : {
                    "@type" : "CustomerResource",
                    "email" : "test@gmail.com",
                    "phone" : "2503334444",
                    "firstName" : "Owner",
                    "lastName" : "lastName"
                    ...
                    "address" : {
                      "@type" : "PostalAddressResource",
                      "province" : "AB",
                      "country" : "Canada",
                      ...
                    }
                }
}


问:
No unique service maching interface error in Spring Boot Cloud Foundry error
I am trying to follow this tutorial https://github.com/cf-platform-eng/spring-boot-cities/tree/master/cities-service to run my spring boot application in Cloud Foundry. I have local bosh-lite installation

My Spring Boot application connects to postgresql as database. I am trying to connect to the Postgresql instance running on my local (host machine )

My application works fine locally if deployed to a local tomcat.
But when i deploy the app to bosh-lite it fails with the following error "No unique service maching interface error ". My code is excatly the same as what is mentioned in the tutorial except i am using Maven to build my code.

```<code>    2017-06-07T22:29:54.44+0530 [App/0] OUT Caused by: org.springframework.cloud.CloudException: No unique service matching interface javax.sql.DataSource found. Expected 1, found 0
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.cloud.Cloud.getSingletonServiceConnector(Cloud.java:149) ~[spring-cloud-core-1.2.3.RELEASE.jar!/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration.dataSource(DataSourceConfiguration.java:20) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e.CGLIB$dataSource$0(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e$$FastClassBySpringCGLIB$$2ad81e2b.invoke(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.8.RELEASE.jar!/:4.3.8.RELEASE]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e.dataSource(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
</code>```

My connection to postgres works fine. And the same app works fine if i don't use spring cloud connector and read the value normally from application.properties.

My pom.xml`(Has dependencies for spring boot cloud connector and postgrsql driver )

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.saurav.cf.casestudy</groupId>
    <artifactId>employeerest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>employeerest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!--  <start-class>org.saurav.cf.casestudy.employee.EmployeerestApplication</start-class> -->
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cloud-connectors</artifactId>

</dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

<dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
      </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

`

[UPDATE]
as per Scott's answers below i had a look at the requirements for a UPS to be picked up cloud connector.Since mine is an user provided provided service so i cannot have tags and label. But i added the jdbc urls.
Now my app is failing with the below error

```<code> Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
</code>```

For this i have set "spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect"  in my application.properties but still it does not work

I have also checked that my DB is running and db settings in my service instance is correct.

Below is my service instance content`

```<code>"VCAP_SERVICES": {
  "user-provided": [
   {
    "credentials": {
     "jdbcUrl": "jdbc:postgresql://10.0.2.2:5432/employee",
     "username": "postgres",
     "password": "admin",
     "postgresUri": "postgresql://10.0.2.2:5432/employee",
     "uri": "postgresql://10.0.2.2:5432/employee"
    },
    "label": "user-provided",
    "name": "postgresql-cf-service",
    "syslog_drain_url": "",
    "tags": [],
    "volume_mounts": []
   }
  ]
 }
</code>```

`
Best Regards,
Saurav

答:
If you include spring-boot-starter-cloud-connectors as a dependency, then Spring Cloud Connectors will attempt to create the java.sql.DataSource bean necessary to connect to the database. Connectors does this by looking for a service binding that has certain characteristics. The No unique service matching interface javax.sql.DataSource found message means that Connectors couldn't find a service binding of the appropriate type.

If you want to use Connectors as in that sample app then you will need to create a user-provided service instance with the details of the Postgres connection and bind that service instance to the app.

Alternatively, you could remove the spring-boot-starter-cloud-connectors dependency and instead configure the database connection using spring.datasource properties in application.yml.

These options are explained in more detail in a blog post.

Body:
I am trying to follow this tutorial https://github.com/cf-platform-eng/spring-boot-cities/tree/master/cities-service to run my spring boot application in Cloud Foundry. I have local bosh-lite installation

My Spring Boot application connects to postgresql as database. I am trying to connect to the Postgresql instance running on my local (host machine )

My application works fine locally if deployed to a local tomcat.
But when i deploy the app to bosh-lite it fails with the following error "No unique service maching interface error ". My code is excatly the same as what is mentioned in the tutorial except i am using Maven to build my code.

    2017-06-07T22:29:54.44+0530 [App/0] OUT Caused by: org.springframework.cloud.CloudException: No unique service matching interface javax.sql.DataSource found. Expected 1, found 0
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.cloud.Cloud.getSingletonServiceConnector(Cloud.java:149) ~[spring-cloud-core-1.2.3.RELEASE.jar!/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration.dataSource(DataSourceConfiguration.java:20) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e.CGLIB$dataSource$0(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e$$FastClassBySpringCGLIB$$2ad81e2b.invoke(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.8.RELEASE.jar!/:4.3.8.RELEASE]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e.dataSource(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]

My connection to postgres works fine. And the same app works fine if i don't use spring cloud connector and read the value normally from application.properties.

My pom.xml`(Has dependencies for spring boot cloud connector and postgrsql driver )

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.saurav.cf.casestudy</groupId>
    <artifactId>employeerest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>employeerest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cloud-connectors</artifactId>

</dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

<dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
      </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

`

[UPDATE]
as per Scott's answers below i had a look at the requirements for a UPS to be picked up cloud connector.Since mine is an user provided provided service so i cannot have tags and label. But i added the jdbc urls.
Now my app is failing with the below error

 Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

For this i have set "spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect"  in my application.properties but still it does not work

I have also checked that my DB is running and db settings in my service instance is correct.

Below is my service instance content`

"VCAP_SERVICES": {
  "user-provided": [
   {
    "credentials": {
     "jdbcUrl": "jdbc:postgresql://10.0.2.2:5432/employee",
     "username": "postgres",
     "password": "admin",
     "postgresUri": "postgresql://10.0.2.2:5432/employee",
     "uri": "postgresql://10.0.2.2:5432/employee"
    },
    "label": "user-provided",
    "name": "postgresql-cf-service",
    "syslog_drain_url": "",
    "tags": [],
    "volume_mounts": []
   }
  ]
 }

`
Best Regards,
Saurav


问:
track text in switch button
Please, somebody knows how I can set text in track part of switch button, I need to do this whith java code not with xml code.
enter image description here</p>

答:
Assuming this is for Android switch buttons you may use the following:</p>

```<code>//sets text on creation
toggleButton.setText(textOff);

// Sets the text for when the button off.
toggleButton.setTextOff(textOff);

// Sets the text for when the button is on.
toggleButton.setTextOn(textOn);
</code>```

Title: track text in switch button

Body:
Assuming this is for Android switch buttons you may use the following:

//sets text on creation
toggleButton.setText(textOff);

// Sets the text for when the button off.
toggleButton.setTextOff(textOff);

// Sets the text for when the button is on.
toggleButton.setTextOn(textOn);


问:
xray-rails not working with rails 5.1
I installed xray-rails on a Rails 5.1 app but pressing the keyboard shortcut does nothing. I already cleared cached assets rails tmp:clear. Any ideas?

答:
Rails 5.1 dropped jQuery as a dependency. Add it to the Gemfile explicitly:

```<code>group :development do
  gem 'xray-rails'
  gem 'jquery-rails' # add it outside the group if you need it globally
end
</code>```

Then import it in application.js:

```<code>//= require jquery
</code>```

And you can Cmd + Shift + X again.

Title: xray-rails not working with rails 5.1

Body:
Rails 5.1 dropped jQuery as a dependency. Add it to the Gemfile explicitly:

group :development do
  gem 'xray-rails'
  gem 'jquery-rails' # add it outside the group if you need it globally
end

Then import it in application.js:

//= require jquery

And you can Cmd + Shift + X again.


问:
Pull text from .txt file and display php
I am trying to create some canvases which pulls some text from a .txt file. My .txt contains on every line name, surname, gender and role separated by space. I want to create a new canvas for each row from my .txt file.
This is how i thought to extract the values from my file:

```<code>$source = fopen('datas.txt', 'r') or die("Problem open file");
while (($data = fgets($source, 1000, " ")) !== FALSE)
{
    $name = $data[0];
    $surname = $data[1];
    $gender = $data[2];
    $role = $data[3];

}
fclose($source);
</code>```

But i don't really know how to put them in a canvas. Can i make a loop or something to create a canvas for each row? I want some suggestions if someone can help me.

答:
Use the data with a function  </p>

```<code><script type="text/javascript">
   function canvasSmth( i ) {
     var canvas = document.getElementById('mycanvas');
     var drawtext = canvas.getContext('2d');
     drawtext.font = "30px Arial";
     drawtext.fillText(i,10,50);
}
</script>

$source = fopen('datas.txt', 'r') or die("Problem open file");
while (($data = fgets($source, 1000, " ")) !== FALSE)
{
    $name = $data[0];
    $surname = $data[1];
    $gender = $data[2];
    $role = $data[3];
    echo '<script type="text/javascript"> canvasSmth( <?php echo $name ; ?> )';
}
fclose($source);
</code>```

Body:
I am trying to create some canvases which pulls some text from a .txt file. My .txt contains on every line name, surname, gender and role separated by space. I want to create a new canvas for each row from my .txt file.
This is how i thought to extract the values from my file:

$source = fopen('datas.txt', 'r') or die("Problem open file");
while (($data = fgets($source, 1000, " ")) !== FALSE)
{
    $name = $data[0];
    $surname = $data[1];
    $gender = $data[2];
    $role = $data[3];

}
fclose($source);

But i don't really know how to put them in a canvas. Can i make a loop or something to create a canvas for each row? I want some suggestions if someone can help me.

Body:
Use the data with a function

<script type="text/javascript">
   function canvasSmth( i ) {
     var canvas = document.getElementById('mycanvas');
     var drawtext = canvas.getContext('2d');
     drawtext.font = "30px Arial";
     drawtext.fillText(i,10,50);
}
</script>

$source = fopen('datas.txt', 'r') or die("Problem open file");
while (($data = fgets($source, 1000, " ")) !== FALSE)
{
    $name = $data[0];
    $surname = $data[1];
    $gender = $data[2];
    $role = $data[3];
    echo '<script type="text/javascript"> canvasSmth( <?php echo $name ; ?> )';
}
fclose($source);