问:
Capturing real time video with opencv in c++?
I'am developing a plate number detection application using opencv and c++.

For the detection trial, I want to capture real time video from my webcam using VideoCapture() function like this:

```<code>int main(void)
{
  // input image
  cv::Mat imgOriginalScene;

  cv::VideoCapture cap = cv::VideoCapture(0);

  for (;;) {
    cv::Mat frame;
    cap.read(frame);
    double timestamp = cap.get(CV_CAP_PROP_POS_MSEC);

    if (cap.read(frame)) {
      imgOriginalScene = frame;
      cv::Size size(1000, 600);
      resize(imgOriginalScene, imgOriginalScene, size);

      if (imgOriginalScene.empty()) {
        std::cout << "error: image not read from file\n\n";
        return(0);
      }

      std::vector<PossiblePlate> vectorOfPossiblePlates =
          detectPlatesInScene(imgOriginalScene);
      vectorOfPossiblePlates = detectCharsInPlates(vectorOfPossiblePlates);

      cv::imshow("imgOriginalScene", imgOriginalScene);

      if (vectorOfPossiblePlates.empty()) {
        std::cout << std::endl << "no license plates were detected" << std::endl;
      }
      else {
        std::sort(vectorOfPossiblePlates.begin(), vectorOfPossiblePlates.end(),
            PossiblePlate::sortDescendingByNumberOfChars);

        // suppose the plate with the most recognized chars
        // (the first plate in sorted by string length descending order)
        // is the actual plate
        PossiblePlate licPlate = vectorOfPossiblePlates.front();

        cv::imshow("imgPlate", licPlate.imgPlate);
        cv::imshow("imgThresh", licPlate.imgThresh);

        // if no chars were found in the plate
        if (licPlate.strChars.length() == 0) {
          // show message
          std::cout << std::endl << "no characters were detected" << std::endl << std::endl;
        }

        // draw red rectangle around plate
        drawRedRectangleAroundPlate(imgOriginalScene, licPlate);

        // write license plate text to std out
        std::cout << std::endl << "license plate read from image = " << licPlate.strChars << std::endl;
        std::cout << std::endl << "-----------------------------------------" << std::endl;
        outfile << licPlate.strChars << "  " << timestamp / 1000 << " Detik" << std::endl;

        // write license plate text on the image
        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate);

        // re-show scene image
        cv::imshow("imgOriginalScene", imgOriginalScene);

        // write image out to file
        cv::imwrite("imgOriginalScene.png", imgOriginalScene);
      }
      cvWaitKey(34);
    }
    else {
      cap.set(CV_CAP_PROP_POS_FRAMES, 1.0);
      cvWaitKey(1000);
    }
    if (cap.get(CV_CAP_PROP_POS_FRAMES) == cap.get(CV_CAP_PROP_FRAME_COUNT)) {
      break;
    }
  }

  outfile.close();

  // hold windows open until user presses a key
  cv::waitKey(0);

  return(0);
}
</code>```

But after running the code, the video shown from my webcam is stuck, like it just showing the very first frame and then stop.
So I can't detect anything because the video is stuck.

Anyone facing the same problem?

答:
Generally, when reading from a camera the steps are as follows:

Open the cv::VideoCapture object and call isOpened() to verify successful open.  I generally prefer declaring the capture object separately and then using open(0) to open it, but test what works for you.

Read a frame into a cv::Mat object.  You can use read() or you could implement an approaching using the << operator

Verify that the frame is not empty using empty().

Process the image in your loop.

Using waitKey()

Remember that waitKey(0) will halt your program until the user presses a key.  Placing waitKey(30) once at then end of your loop will display the images in the processed and queued up using imshow().  You do not need to use waitKey() multiple times throughout the loop and may want to you some other timer for timing purposes.

Possible Error Points

Your code may be hanging on your first if statement.  You are calling cap.read(frame) back to back which may be too fast for the webcam to process... causing it to return false after the first iteration.  Instead, try an implementation that uses frame.empty() instead to check if you have an image to process after calling cap.read(frame).

```<code>cv::Mat imgOriginalScene;           // input image

cv::VideoCapture cap = cv::VideoCapture(0);

if(!cap.isOpened()){
    cerr << "Error Opening Capture Device" << endl; //Use cerr for basic debugging statements
    return -1;
}

for (;;) {
    cv::Mat frame;
    cap.read(frame);
    double timestamp = cap.get(CV_CAP_PROP_POS_MSEC);

    if (frame.empty()) {
         /*... do something ...*/
    }
    else {
        cap.set(CV_CAP_PROP_POS_FRAMES, 1.0);
        cvWaitKey(1000);
    }
     //Try removing this for debug...
/*
    if (cap.get(CV_CAP_PROP_POS_FRAMES) == cap.get(CV_CAP_PROP_FRAME_COUNT)) {
        //break;

    }
*/
    cv::waitKey(0);                 // hold windows open until user presses a key
}

outfile.close();
cv::waitKey(0);                 // hold windows open until user presses a key

return(0);
</code>```

Update Log:

Per @api55's comment, added the isOpened() check for completeness

Added discussion for waitkey()

Suggested commenting out sections that break the loop for now

Body:
I'am developing a plate number detection application using opencv and c++.

For the detection trial, I want to capture real time video from my webcam using VideoCapture() function like this:

int main(void)
{
  // input image
  cv::Mat imgOriginalScene;

  cv::VideoCapture cap = cv::VideoCapture(0);

  for (;;) {
    cv::Mat frame;
    cap.read(frame);
    double timestamp = cap.get(CV_CAP_PROP_POS_MSEC);

    if (cap.read(frame)) {
      imgOriginalScene = frame;
      cv::Size size(1000, 600);
      resize(imgOriginalScene, imgOriginalScene, size);

      if (imgOriginalScene.empty()) {
        std::cout << "error: image not read from file\n\n";
        return(0);
      }

      std::vector<PossiblePlate> vectorOfPossiblePlates =
          detectPlatesInScene(imgOriginalScene);
      vectorOfPossiblePlates = detectCharsInPlates(vectorOfPossiblePlates);

      cv::imshow("imgOriginalScene", imgOriginalScene);

      if (vectorOfPossiblePlates.empty()) {
        std::cout << std::endl << "no license plates were detected" << std::endl;
      }
      else {
        std::sort(vectorOfPossiblePlates.begin(), vectorOfPossiblePlates.end(),
            PossiblePlate::sortDescendingByNumberOfChars);

        // suppose the plate with the most recognized chars
        // (the first plate in sorted by string length descending order)
        // is the actual plate
        PossiblePlate licPlate = vectorOfPossiblePlates.front();

        cv::imshow("imgPlate", licPlate.imgPlate);
        cv::imshow("imgThresh", licPlate.imgThresh);

        // if no chars were found in the plate
        if (licPlate.strChars.length() == 0) {
          // show message
          std::cout << std::endl << "no characters were detected" << std::endl << std::endl;
        }

        // draw red rectangle around plate
        drawRedRectangleAroundPlate(imgOriginalScene, licPlate);

        // write license plate text to std out
        std::cout << std::endl << "license plate read from image = " << licPlate.strChars << std::endl;
        std::cout << std::endl << "-----------------------------------------" << std::endl;
        outfile << licPlate.strChars << "  " << timestamp / 1000 << " Detik" << std::endl;

        // write license plate text on the image
        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate);

        // re-show scene image
        cv::imshow("imgOriginalScene", imgOriginalScene);

        // write image out to file
        cv::imwrite("imgOriginalScene.png", imgOriginalScene);
      }
      cvWaitKey(34);
    }
    else {
      cap.set(CV_CAP_PROP_POS_FRAMES, 1.0);
      cvWaitKey(1000);
    }
    if (cap.get(CV_CAP_PROP_POS_FRAMES) == cap.get(CV_CAP_PROP_FRAME_COUNT)) {
      break;
    }
  }

  outfile.close();

  // hold windows open until user presses a key
  cv::waitKey(0);

  return(0);
}

But after running the code, the video shown from my webcam is stuck, like it just showing the very first frame and then stop.
So I can't detect anything because the video is stuck.

Anyone facing the same problem?

Body:
Generally, when reading from a camera the steps are as follows:

Open the cv::VideoCapture object and call isOpened() to verify successful open.  I generally prefer declaring the capture object separately and then using open(0) to open it, but test what works for you.

Read a frame into a cv::Mat object.  You can use read() or you could implement an approaching using the << operator

Verify that the frame is not empty using empty().

Process the image in your loop.

Using waitKey()

Remember that waitKey(0) will halt your program until the user presses a key.  Placing waitKey(30) once at then end of your loop will display the images in the processed and queued up using imshow().  You do not need to use waitKey() multiple times throughout the loop and may want to you some other timer for timing purposes.

Possible Error Points

Your code may be hanging on your first if statement.  You are calling cap.read(frame) back to back which may be too fast for the webcam to process... causing it to return false after the first iteration.  Instead, try an implementation that uses frame.empty() instead to check if you have an image to process after calling cap.read(frame).

cv::Mat imgOriginalScene;           // input image

cv::VideoCapture cap = cv::VideoCapture(0);

if(!cap.isOpened()){
    cerr << "Error Opening Capture Device" << endl; //Use cerr for basic debugging statements
    return -1;
}

for (;;) {
    cv::Mat frame;
    cap.read(frame);
    double timestamp = cap.get(CV_CAP_PROP_POS_MSEC);

    if (frame.empty()) {
         /*... do something ...*/
    }
    else {
        cap.set(CV_CAP_PROP_POS_FRAMES, 1.0);
        cvWaitKey(1000);
    }
     //Try removing this for debug...
/*
    if (cap.get(CV_CAP_PROP_POS_FRAMES) == cap.get(CV_CAP_PROP_FRAME_COUNT)) {
        //break;

    }
*/
    cv::waitKey(0);                 // hold windows open until user presses a key
}

outfile.close();
cv::waitKey(0);                 // hold windows open until user presses a key

return(0);

Update Log:

Per @api55's comment, added the isOpened() check for completeness

Added discussion for waitkey()

Suggested commenting out sections that break the loop for now


来源: stackexchange

问:
How to make Flexbox items the same size
I want to use Flexbox that has some number of items that are all the same width. I've noticed that Flexbox distributes the space around evenly, rather than the space itself.

For example:

.header {
  display: flex;
}

.item {
  flex-grow: 1;
  text-align: center;
  border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div class="item">asdfasdfasdfasdfasdfasdf</div>
  <div class="item">z</div>
</div></code>```

The first item is a lot bigger than the second. If I have three items, four items, or n items, I want them all to appear on the same line with an equal amount of space per item.

Any ideas?

http://codepen.io/anon/pen/gbJBqM

答:
You need to add width: 0 to make columns equal if contents of the items make it grow bigger.

```<code>.item {
  flex: 1 1 0;
  width: 0;
}
</code>```

Detail:
flex: 1 1 0 is the same as
 flex-grow: 1; flex-shrink: 1; flex-basis: 0;
and if the parent container can not provide enough space for the native-size added together of every item (no space to grow), we need to make the width: 0 to give every item the same start point to grow.

ContentLicense: CC BY-SA 4.0

Title: How to make Flexbox items the same size

Body:
I want to use Flexbox that has some number of items that are all the same width. I've noticed that Flexbox distributes the space around evenly, rather than the space itself.

For example:

.header {
  display: flex;
}

.item {
  flex-grow: 1;
  text-align: center;
  border: 1px solid black;
}

asdfasdfasdfasdfasdfasdf

z

The first item is a lot bigger than the second. If I have three items, four items, or n items, I want them all to appear on the same line with an equal amount of space per item.

Any ideas?

http://codepen.io/anon/pen/gbJBqM

Body:
You need to add width: 0 to make columns equal if contents of the items make it grow bigger.

.item {
  flex: 1 1 0;
  width: 0;
}

Detail:
flex: 1 1 0 is the same as
 flex-grow: 1; flex-shrink: 1; flex-basis: 0;
and if the parent container can not provide enough space for the native-size added together of every item (no space to grow), we need to make the width: 0 to give every item the same start point to grow.


问:
How to access Galaxy S5 heart rate sensor?
In the Samsung's programming guide (pages 77 - 81) there is a reference on how to set and get the heart rate information using the S Health Service SDK. However, I was looking to directly access the Galaxy S5's heart rate sensor, the same way you are able to access the accelerometer, gyroscope, light sensor, among other sensors.
I found this example for the samsung gear live, but I cannot find any example for Galaxy S5.

Is it possible to directly access the Galaxy S5's heart rate sensor? Does anyone has a code example on how to do it?

Thank you.

答:
You cannot get raw heart rate monitor data from Samsung Galaxy S5.

Sensors Extension SDK is required to get raw data from sensors not supported by Google Android and this page states that:

Sensor Extension SDK has the following restrictions:

HRM Sensor IR/RED Signal

Devices with Android 5.0 (Lollipop API level 21) or higher is required.

Galaxy S5 and Galaxy S5mini are excluded.

Only supported by Samsung device with HRM sensor.

ContentLicense: CC BY-SA 3.0


问:
Why is " '2019-02-01'.to_date - Date.today" "442/1"?
I did this:

```<code>'2019-02-01'.to_date - Date.today # => 442/1
</code>```

Why is the return value not 442?

答:
It give the difference of days
Try this

```<code>pry(main)> ('2019-02-01'.to_date - Date.today).to_i
=> 442
pry(main)> (Date.today + 2.days) - Date.today)
=> (2/1)
pry(main)> ((Date.today + 2.days) - Date.today)).to_i
=> 2
</code>```

So, 442 is days difference.

Body:
I did this:

'2019-02-01'.to_date - Date.today # => 442/1

Why is the return value not 442?

Body:
It give the difference of days
Try this

pry(main)> ('2019-02-01'.to_date - Date.today).to_i
=> 442
pry(main)> (Date.today + 2.days) - Date.today)
=> (2/1)
pry(main)> ((Date.today + 2.days) - Date.today)).to_i
=> 2

So, 442 is days difference.


问:
How can i get Client Webpage cookie information through javascript
I want to get the browser cookies information like email or name.

pls help me

答:
You can use the document.cookie object to read the available cookies using javascript.

You can find more details here.

One thing you need to keep in mind is you cannot get a cookie which has a different domain than yours.

ContentLicense: CC BY-SA 2.5


问:
Silent mode on Android 7
Is there any way to set ringer mode to silent on android 7

```<code>if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
    amanager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
</code>```

setRingerMode works on Android 6 and lower versions.
From doc:

"From N onward, ringer mode adjustments that would toggle Do Not
  Disturb are not allowed unless the app has been granted Do Not Disturb
  Access."

Is there any way to achieve this without opening "Do Not Disturb access settings" via intent such being system app or allow when building platform code like this app has do not disturb permission etc?

答:
Here's my gist to help you with the problem

I wanted to switch the phone between silent and normal modes using AudioManager but it did not work on android N and above. More details in the comments. NOTE: I'm a beginner myself so this is by no means an expert level code. I'm sharing it because I found very little help on for this.

```<code>    package com.junaidaziz.keepitsilent;

import android.app.NotificationManager;
import android.content.*;
import android.media.AudioManager;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

/*
 * Created by junaidaziz on 11/13/17.
 */

public class ToggleSoundMode extends android.content.BroadcastReceiver {

    Context context;
    static AudioManager audio;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        Log.d("BroadCast: ", " Recieved");

        toggleSoundMode();

//        Intent background = new Intent(context, BackgroundService.class);
//        context.startService(background);
    }

    public void toggleSoundMode(){
        Log.d("BroadCast: ", "toggleSoundMode");

        //if the OS version is lower than Nougat
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            handleAudioManager();
        }

        //if the OS version is Nougat or above
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){

            //first we need to get the current Notification Interruption Filter
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            int currentMode = notificationManager.getCurrentInterruptionFilter();

            //Just for debugging
            Log.d("BroadCast: ", "currentmode " + currentMode);
            Log.d("BroadCast: ", "case 1: " + NotificationManager.INTERRUPTION_FILTER_ALARMS);
            Log.d("BroadCast: ", "case 2: " + NotificationManager.INTERRUPTION_FILTER_ALL);
            Log.d("BroadCast: ", "case 3: " + NotificationManager.INTERRUPTION_FILTER_NONE);
            Log.d("BroadCast: ", "case 4: " + NotificationManager.INTERRUPTION_FILTER_PRIORITY);
            Log.d("BroadCast: ", "case 5: " + NotificationManager.INTERRUPTION_FILTER_UNKNOWN);

            //Make the change to the notification Interruption filter First....then change the Audio Settings
            switch (currentMode){
                case NotificationManager.INTERRUPTION_FILTER_ALL: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);  //Toggle On the Do not disturb Mode
                    break;
                }
                case NotificationManager.INTERRUPTION_FILTER_UNKNOWN: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);  //Toggle the normal mode
                    handleRingVolume(); //With the normal interruption filter tuned on, we only need to handle the volumes.
                    break;
                }
                case NotificationManager.INTERRUPTION_FILTER_ALARMS: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
                    handleRingVolume();
                    break;
                }
                case NotificationManager.INTERRUPTION_FILTER_NONE: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
                    handleRingVolume();
                    break;
                }
                case NotificationManager.INTERRUPTION_FILTER_PRIORITY: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
                    handleRingVolume();
                    break;
                }
            }
        }
    }

    public void handleAudioManager(){

        //This part of code is pretty self explanatory.

        int currentMode = audio.getRingerMode();

        Log.d("BroadCast: ", "currentmode " + currentMode);
        Log.d("BroadCast: ", "case 1: " + AudioManager.RINGER_MODE_NORMAL);
        Log.d("BroadCast: ", "case 2: " + AudioManager.RINGER_MODE_VIBRATE);

        switch (currentMode) {
            case AudioManager.RINGER_MODE_NORMAL: {
                audio.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                Log.d("BroadCast: ", "case: RINGER MODE NORMAL");
                Toast.makeText(context, "Vibration Activated", Toast.LENGTH_LONG).show();
                break;
            }
            case AudioManager.RINGER_MODE_VIBRATE: {
                Log.d("BroadCast: ", "case; RINGER MODE VIBRATE");
                audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                handleRingVolume();
                Toast.makeText(context, "Normal mode Activated", Toast.LENGTH_LONG).show();
                break;
            }
            case AudioManager.RINGER_MODE_SILENT: {
                Log.d("BroadCast: ", "case; RINGER MODE SILENT");
                audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                handleRingVolume();
                Toast.makeText(context, "Normal mode Activated", Toast.LENGTH_LONG).show();
                break;
            }
        }
    }

    public void handleRingVolume(){
        audio.setStreamVolume(AudioManager.STREAM_RING, audio.getStreamMaxVolume(AudioManager.STREAM_RING), 0);
        audio.setStreamVolume(AudioManager.STREAM_NOTIFICATION, audio.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION), 0);
        audio.setStreamVolume(AudioManager.STREAM_SYSTEM, audio.getStreamMaxVolume(AudioManager.STREAM_SYSTEM), 0);
        audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
        audio.setStreamVolume(AudioManager.STREAM_ALARM, audio.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);
        Toast.makeText(context, "Max volume", Toast.LENGTH_LONG).show();
    }}
</code>```

After reading through many resources and testing different ways, I concluded that on Android Nougat and above, the Notification Manager's Do Not Disturb Mode somehow overrides everything related to Audio and notification.

So if the phone is in Do Not Disturb mode, you cannot change the sound settings or make any change that would violate the Do Not Disturb mode. So if you want to put the phone back into the ringing mode, you would first need to change the Notification InterruptionFiler. once that's changed, then you can change the volume settings as well. This is also demonstrated by the fact that if Do Not Disturb mode is turned on, Android will not let you change the Volume on the phone even using the physical volume buttons.

To get this code working, you'd need to have the following two permissions as well.

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

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

Title: Silent mode on Android 7

Body:
Is there any way to set ringer mode to silent on android 7

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
    amanager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}

setRingerMode works on Android 6 and lower versions.
From doc:

"From N onward, ringer mode adjustments that would toggle Do Not
  Disturb are not allowed unless the app has been granted Do Not Disturb
  Access."

Is there any way to achieve this without opening "Do Not Disturb access settings" via intent such being system app or allow when building platform code like this app has do not disturb permission etc?

Body:
Here's my gist to help you with the problem

I wanted to switch the phone between silent and normal modes using AudioManager but it did not work on android N and above. More details in the comments. NOTE: I'm a beginner myself so this is by no means an expert level code. I'm sharing it because I found very little help on for this.

    package com.junaidaziz.keepitsilent;

import android.app.NotificationManager;
import android.content.*;
import android.media.AudioManager;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

/*
 * Created by junaidaziz on 11/13/17.
 */

public class ToggleSoundMode extends android.content.BroadcastReceiver {

    Context context;
    static AudioManager audio;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        Log.d("BroadCast: ", " Recieved");

        toggleSoundMode();

//        Intent background = new Intent(context, BackgroundService.class);
//        context.startService(background);
    }

    public void toggleSoundMode(){
        Log.d("BroadCast: ", "toggleSoundMode");

        //if the OS version is lower than Nougat
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            handleAudioManager();
        }

        //if the OS version is Nougat or above
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){

            //first we need to get the current Notification Interruption Filter
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            int currentMode = notificationManager.getCurrentInterruptionFilter();

            //Just for debugging
            Log.d("BroadCast: ", "currentmode " + currentMode);
            Log.d("BroadCast: ", "case 1: " + NotificationManager.INTERRUPTION_FILTER_ALARMS);
            Log.d("BroadCast: ", "case 2: " + NotificationManager.INTERRUPTION_FILTER_ALL);
            Log.d("BroadCast: ", "case 3: " + NotificationManager.INTERRUPTION_FILTER_NONE);
            Log.d("BroadCast: ", "case 4: " + NotificationManager.INTERRUPTION_FILTER_PRIORITY);
            Log.d("BroadCast: ", "case 5: " + NotificationManager.INTERRUPTION_FILTER_UNKNOWN);

            //Make the change to the notification Interruption filter First....then change the Audio Settings
            switch (currentMode){
                case NotificationManager.INTERRUPTION_FILTER_ALL: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);  //Toggle On the Do not disturb Mode
                    break;
                }
                case NotificationManager.INTERRUPTION_FILTER_UNKNOWN: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);  //Toggle the normal mode
                    handleRingVolume(); //With the normal interruption filter tuned on, we only need to handle the volumes.
                    break;
                }
                case NotificationManager.INTERRUPTION_FILTER_ALARMS: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
                    handleRingVolume();
                    break;
                }
                case NotificationManager.INTERRUPTION_FILTER_NONE: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
                    handleRingVolume();
                    break;
                }
                case NotificationManager.INTERRUPTION_FILTER_PRIORITY: {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
                    handleRingVolume();
                    break;
                }
            }
        }
    }

    public void handleAudioManager(){

        //This part of code is pretty self explanatory.

        int currentMode = audio.getRingerMode();

        Log.d("BroadCast: ", "currentmode " + currentMode);
        Log.d("BroadCast: ", "case 1: " + AudioManager.RINGER_MODE_NORMAL);
        Log.d("BroadCast: ", "case 2: " + AudioManager.RINGER_MODE_VIBRATE);

        switch (currentMode) {
            case AudioManager.RINGER_MODE_NORMAL: {
                audio.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                Log.d("BroadCast: ", "case: RINGER MODE NORMAL");
                Toast.makeText(context, "Vibration Activated", Toast.LENGTH_LONG).show();
                break;
            }
            case AudioManager.RINGER_MODE_VIBRATE: {
                Log.d("BroadCast: ", "case; RINGER MODE VIBRATE");
                audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                handleRingVolume();
                Toast.makeText(context, "Normal mode Activated", Toast.LENGTH_LONG).show();
                break;
            }
            case AudioManager.RINGER_MODE_SILENT: {
                Log.d("BroadCast: ", "case; RINGER MODE SILENT");
                audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                handleRingVolume();
                Toast.makeText(context, "Normal mode Activated", Toast.LENGTH_LONG).show();
                break;
            }
        }
    }

    public void handleRingVolume(){
        audio.setStreamVolume(AudioManager.STREAM_RING, audio.getStreamMaxVolume(AudioManager.STREAM_RING), 0);
        audio.setStreamVolume(AudioManager.STREAM_NOTIFICATION, audio.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION), 0);
        audio.setStreamVolume(AudioManager.STREAM_SYSTEM, audio.getStreamMaxVolume(AudioManager.STREAM_SYSTEM), 0);
        audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
        audio.setStreamVolume(AudioManager.STREAM_ALARM, audio.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);
        Toast.makeText(context, "Max volume", Toast.LENGTH_LONG).show();
    }}

After reading through many resources and testing different ways, I concluded that on Android Nougat and above, the Notification Manager's Do Not Disturb Mode somehow overrides everything related to Audio and notification.

So if the phone is in Do Not Disturb mode, you cannot change the sound settings or make any change that would violate the Do Not Disturb mode. So if you want to put the phone back into the ringing mode, you would first need to change the Notification InterruptionFiler. once that's changed, then you can change the volume settings as well. This is also demonstrated by the fact that if Do Not Disturb mode is turned on, Android will not let you change the Volume on the phone even using the physical volume buttons.

To get this code working, you'd need to have the following two permissions as well.

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

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


问:
How to stop scrolling as half item can be visible in HorizontalScrollView
Can you plz share any suggestion or library to achieve below,

e.g. If you see in Google Play Store, when you scroll HorizontalScrollView, your scrolling will stop as half of the next item user can able to see. App forcefully stops scroll like this so the user gets to know, there are more items available.

I do not have any code to share. I just want your hints/libs.

Thank you!

答: You can achieve this task via using Horizontal recycler view and by adding pull to refresh technique. Set limited amount of items to be displayed by default and load on demand. Hope that answers your question.</p>


问:
Making sticky javascript
I have a javascript form where I am using innerHTML to set some text.

When the form submits that information is lost.Is there anyway I can make it "sticky".I was thinking a cookie but that's about all I know.

Thanks

```<code><form "action="" name="myform">
<input type="text" name='name">
<div id="theName"></div>
</form>
</code>```

Quick example I am capturing the name and need the div to show the name after the form submits.

答:
You will need to persist the data somehow. There are several options:

Store it on the server. When the form is submitted, your server-side script will receive the data; it can persist it in a database, session variable, or some other form of storage that's appropriate for your application. Whenever the client re-visits the page with the form, have the server generate the form's HTML with the persisted data.

Use HTML5's local storage. While not supported in legacy browsers, all modern ones provide the local storage API. When the user submits the form (attach an event listener to the form's "submit" event), you can store the form data by making calls to localStorage[key] = value and retrieving it with localStorage[key].

Store it in a cookie. Although I don't recommend this approach, you can create a cookie with the form data. The only restriction is that the data needs to be represented as a string, but I recommend JSON. However, you probably should not use this approach since cookies are sent to the server for each request; if the form fields contain a lot of data, then you're also unnecessarily sending a lot of data to the server.

Using HTML5's local storage gives you a self-encapsulated approach that requires no server-side configuration:

```<code><form action="" name="myform">
  <input type="text" name="name">
  <div id="theName"></div>
</form>
<script type="text/javascript">
  (function() {
    var form = document.getElementsByName('myform')[0];
    if (localStorage['name'] !== undefined) {
      var displayArea = document.getElementById('theName');
      displayArea.textContent = localStorage['name'];
    }
    form.addEventListener('submit', function() {
      var nameField = document.getElementsByName('name')[0];
      localStorage['name'] = nameField.value;
    }, false);
  })();
</script>
</code>```

Title: Making sticky javascript

Body:
I have a javascript form where I am using innerHTML to set some text.

When the form submits that information is lost.Is there anyway I can make it "sticky".I was thinking a cookie but that's about all I know.

Thanks

<form "action="" name="myform">
<input type="text" name='name">

</form>

Quick example I am capturing the name and need the div to show the name after the form submits.

Body:
You will need to persist the data somehow. There are several options:

Store it on the server. When the form is submitted, your server-side script will receive the data; it can persist it in a database, session variable, or some other form of storage that's appropriate for your application. Whenever the client re-visits the page with the form, have the server generate the form's HTML with the persisted data.

Use HTML5's local storage. While not supported in legacy browsers, all modern ones provide the local storage API. When the user submits the form (attach an event listener to the form's "submit" event), you can store the form data by making calls to localStorage[key] = value and retrieving it with localStorage[key].

Store it in a cookie. Although I don't recommend this approach, you can create a cookie with the form data. The only restriction is that the data needs to be represented as a string, but I recommend JSON. However, you probably should not use this approach since cookies are sent to the server for each request; if the form fields contain a lot of data, then you're also unnecessarily sending a lot of data to the server.

Using HTML5's local storage gives you a self-encapsulated approach that requires no server-side configuration:

<form action="" name="myform">
  <input type="text" name="name">
  <div id="theName"></div>
</form>
<script type="text/javascript">
  (function() {
    var form = document.getElementsByName('myform')[0];
    if (localStorage['name'] !== undefined) {
      var displayArea = document.getElementById('theName');
      displayArea.textContent = localStorage['name'];
    }
    form.addEventListener('submit', function() {
      var nameField = document.getElementsByName('name')[0];
      localStorage['name'] = nameField.value;
    }, false);
  })();
</script>


问:
Where does YAST store NTP settings
I'm using SLES 12.2 and recently had some trouble with NTP configuration.
The default settings for NTP in YAST were "Synchronize without Daemon" in the Start NTP Daemon section and "Manual" for "Runtime Configuration Policy". I changed those to "Now and on Boot" and "Auto", respectively. This fixed my problem, as expected.
However, I now need to apply this to a couple hundred machines and need to figure out how to do it from the console.

For the first option, I thought the obvious thing is to enable ntpd.service:

$ systemctl enable ntpd.service

But when I do that and open up YAST, it's still saying "Manual". At the same time if ntpd is disabled and I change it in YAST, it sets it to enabled. So apparently YAST enables the service AND does something else.

The second option I'm not sure about. It has manual, auto, and custom as options in YAST. At first I thought this might be related to the specifics in /etc/ntp.conf, but making changes in YAST doesn't change anything there.

There are of course a number of resources online, but they all get into the specifics of how to configure NTP either in the console or in YAST. What I'm looking for is what each setting in YAST does on the file system specifically.

I'm fairly new to SLES, so there might be something obvious I'm missing. Perhaps there's a setting similar to NM_CONTROLLED for network interfaces where I can simply turn off YAST for NTP and just do it the old-fashioned way?

答:
Usually all SuSE system configuration stuff is stored under
/etc/sysconfig

More Info in documentation

Title: Where does YAST store NTP settings


问:
PowerMock Mockito ignore junit FixMethodOrder
I have a little problem here, and I don't know how to solve it.

I have a class which have to make tests for some JSF beans.
In order to achieve that, I used PowerMock with Mockito for mocking the FacesContext, RequestContext and another static methods which are used inside the JSF beans.

```<code>@PrepareForTest(ClassWithStaticMethods.class)
@RunWith(PowerMockRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyTestingClass extends SomeTestBaseClass{

    @BeforeClass
    public static void init() throws Exception{
        //mocking the FacesContext and others
    }

    @Test
    public void test0001Create(){}

    @Test
    public void test0002Edit(){}

    @Test
    public void test0003Delete(){}
}
</code>```

The SomeTestBaseClass, nothing complicated.

```<code>public abstract class SomeTestBaseClass {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        //...
    }
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        //...
    }
}
</code>```

The problem is that the order of tests is ignored (even with the FixMethodOrder annotation). If I remove PowerMockRunner (and the RunWith annotation), the order is kept but the mocking for static (and void) methods doesn't work.
But leaving the class with PowerMockRunner, the annotation @FixMethodOrder is ignored, totally.

I even tried with MockitoJUnitRunner, and here the order of tests is kept, but the mocking for static (and void) methods isn't done.

Does anyone have any idea why it is happening?

Thanks

答:
Please try to change sequence:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)

@RunWith(PowerMockRunner.class)

@PrepareForTest(ClassWithStaticMethods.class)

Body:
I have a little problem here, and I don't know how to solve it.

I have a class which have to make tests for some JSF beans.
In order to achieve that, I used PowerMock with Mockito for mocking the FacesContext, RequestContext and another static methods which are used inside the JSF beans.

@PrepareForTest(ClassWithStaticMethods.class)
@RunWith(PowerMockRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyTestingClass extends SomeTestBaseClass{

    @BeforeClass
    public static void init() throws Exception{
        //mocking the FacesContext and others
    }

    @Test
    public void test0001Create(){}

    @Test
    public void test0002Edit(){}

    @Test
    public void test0003Delete(){}
}

The SomeTestBaseClass, nothing complicated.

public abstract class SomeTestBaseClass {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        //...
    }
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        //...
    }
}

The problem is that the order of tests is ignored (even with the FixMethodOrder annotation). If I remove PowerMockRunner (and the RunWith annotation), the order is kept but the mocking for static (and void) methods doesn't work.
But leaving the class with PowerMockRunner, the annotation @FixMethodOrder is ignored, totally.

I even tried with MockitoJUnitRunner, and here the order of tests is kept, but the mocking for static (and void) methods isn't done.

Does anyone have any idea why it is happening?

Thanks


问:
directly quoting %~dp0 does not ignore spaces in file path
i have a script which 3 arguments, two of which are paths. I would like to call it from a .bat file.

```<code>python myscript.py "%~dp0inputs/" "%~dp0outputs/" "foo"
</code>```

If i call a dummy script that simply prints argv using the above line, i get the expected results, even for paths containing spaces:

```<code>myscript.py
C:\path\containing spaces\inputs/
C:\path\containing spaces\outputs/
foo
</code>```

however if i use this (ie %~dp0 for argument 1 with nothing else between the quotes):

```<code>python myscript.py "%~dp0" "%~dp0outputs/" "foo"
</code>```

then it behaves oddly when the path contains spaces:

```<code>myscript.py
C:\path\containing spaces" C:\path\containing
spaces\outputs/ foo
</code>```

it seems that the quotes have not been processed properly - what have i done wrong?

答:
try to use Set to call your paths within batch. (example below)

```<code>@echo off

set myscrpt="C:\path\containing spaces\mypythonscript.py"
set mypath1="C:\path\containing spaces\inputs"
set mypath2="C:\path\containing spaces\outputs"

pushd C:\Python27
Python %myscrpt% %mypath1% %mypath2%
pause>NUL
exit
</code>```

Body:
i have a script which 3 arguments, two of which are paths. I would like to call it from a .bat file.

python myscript.py "%~dp0inputs/" "%~dp0outputs/" "foo"

If i call a dummy script that simply prints argv using the above line, i get the expected results, even for paths containing spaces:

myscript.py
C:\path\containing spaces\inputs/
C:\path\containing spaces\outputs/
foo

however if i use this (ie %~dp0 for argument 1 with nothing else between the quotes):

python myscript.py "%~dp0" "%~dp0outputs/" "foo"

then it behaves oddly when the path contains spaces:

myscript.py
C:\path\containing spaces" C:\path\containing
spaces\outputs/ foo

it seems that the quotes have not been processed properly - what have i done wrong?

Body:
try to use Set to call your paths within batch. (example below)

@echo off

set myscrpt="C:\path\containing spaces\mypythonscript.py"
set mypath1="C:\path\containing spaces\inputs"
set mypath2="C:\path\containing spaces\outputs"

pushd C:\Python27
Python %myscrpt% %mypath1% %mypath2%
pause>NUL
exit


问:
laravel eloquent mark objects with relation
```<code>class PaymentMethod extends Model
{
     ....

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    ...
}

class User extends Authenticatable
{
    ...

    public function payment_methods()
    {
        return $this->hasMany(PaymentMethod::class, $this->getForeignKey())->orderBy('created_at', 'desc');
    }

    public function default_payment_method()
    {
        return $this->hasOne(PaymentMethod::class, 'id', 'default_payment_method_id');
    }

    ...
}
</code>```

In the views

```<code>@if($user -> getDefautPaymentMethod()->type == PaymentMethod::PAYPAL_ACCOUNT)
    <div><strong>Paypal: </strong> {{$user -> getDefautPaymentMethod()-> paypal_email}}</div>
@else
    <div><strong>Card: </strong>{{$user -> getDefautPaymentMethod()-> card_brand}} **** **** **** {{$user -> getDefautPaymentMethod()-> card_last_four}}</div>
@endif
</code>```

This work fine. And outputs default payment method for user.

But i want't output all payments method for user. And for each method output label if this is default for user.

I don't want't DB::RAW or sub queries in cicle

```<code>    @foreach($user->payment_methods()->get() as $payment_method)
        @if($payment_method ->type == PaymentMethod::PAYPAL_ACCOUNT)
            <div><strong>Paypal: </strong> {{$payment_method -> paypal_email}}</div>
        @else
            <div><strong>Card: </strong>{{ $payment_method -> card_brand }} **** **** **** {{$payment_method -> card_last_four}}</div>
        @endif
    @endforeach
</code>```

How affect this cicle and model code for output if method default?

答:
I found solution:</p>

```<code>public function defaultForUser()
{
    return $this->belongsTo(User::class, 'id', 'default_payment_method_id');
}

<h3>Payment methods</h3>
<table border="1">
<tr><th></th><th></th><th></th></tr>
@foreach($user->payment_methods()->withCount('defaultForUser')->get() as $payment_method)
    <tr>
    <td>
        <div><strong>id:</strong> {{$payment_method->id }}</div>
        <div><strong>gateway id:</strong> {{ $payment_method->braintree_id }}</div>
    </td>
    <td>
        @if($payment_method ->type == PaymentMethod::PAYPAL_ACCOUNT)
            <div><strong>Paypal: </strong> {{$payment_method -> paypal_email}}</div>
        @else
            <div><strong>Card: </strong>{{ $payment_method -> card_brand }} **** **** **** {{$payment_method -> card_last_four}}</div>
        @endif

    <td>
        @if ($payment_method -> default_for_user_count)
            <strong style = "color:green">Default</strong>
        @endif
    </td>
    </td>
    </tr>
@endforeach
</table>
</code>```

Body:
class PaymentMethod extends Model
{
     ....

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    ...
}

class User extends Authenticatable
{
    ...

    public function payment_methods()
    {
        return $this->hasMany(PaymentMethod::class, $this->getForeignKey())->orderBy('created_at', 'desc');
    }

    public function default_payment_method()
    {
        return $this->hasOne(PaymentMethod::class, 'id', 'default_payment_method_id');
    }

    ...
}

In the views

@if($user -> getDefautPaymentMethod()->type == PaymentMethod::PAYPAL_ACCOUNT)

Paypal:  {{$user -> getDefautPaymentMethod()-> paypal_email}}

@else

Card: {{$user -> getDefautPaymentMethod()-> card_brand}} **** **** **** {{$user -> getDefautPaymentMethod()-> card_last_four}}

@endif

This work fine. And outputs default payment method for user.

But i want't output all payments method for user. And for each method output label if this is default for user.

I don't want't DB::RAW or sub queries in cicle

    @foreach($user->payment_methods()->get() as $payment_method)
        @if($payment_method ->type == PaymentMethod::PAYPAL_ACCOUNT)

Paypal:  {{$payment_method -> paypal_email}}

        @else

Card: {{ $payment_method -> card_brand }} **** **** **** {{$payment_method -> card_last_four}}

        @endif
    @endforeach

How affect this cicle and model code for output if method default?

Body:
I found solution:

public function defaultForUser()
{
    return $this->belongsTo(User::class, 'id', 'default_payment_method_id');
}

<h3>Payment methods</h3>
<table border="1">
<tr><th></th><th></th><th></th></tr>
@foreach($user->payment_methods()->withCount('defaultForUser')->get() as $payment_method)
    <tr>
    <td>
        <div><strong>id:</strong> {{$payment_method->id }}</div>
        <div><strong>gateway id:</strong> {{ $payment_method->braintree_id }}</div>
    </td>
    <td>
        @if($payment_method ->type == PaymentMethod::PAYPAL_ACCOUNT)
            <div><strong>Paypal: </strong> {{$payment_method -> paypal_email}}</div>
        @else
            <div><strong>Card: </strong>{{ $payment_method -> card_brand }} **** **** **** {{$payment_method -> card_last_four}}</div>
        @endif

    <td>
        @if ($payment_method -> default_for_user_count)
            <strong style = "color:green">Default</strong>
        @endif
    </td>
    </td>
    </tr>
@endforeach
</table>


问:
How do I write a "formula" in the Google Sheets filter widget?
I know I can do this with formulas, but I'd like to understand how to do it using the popup filter tool (since I'm constantly changing it).

This thing, for reference:

Ordinarily, I can get away with entering the string I want in the "Value or formula" window, like so...

The above works AS LONG AS the exact string I type matches a sub-string in the cell. However, every now and then I want to do something like this...

But that doesn't work.

I've tried all sorts of "formulas", like "foo" && "bar" or ="foo" + "bar"

But of course those don't work either... It doesn't seem to make sense to use the =filter(...) formula, as that requires a range that is already defined by the filter widget itself. I haven't had any luck with that either.

Can anyone give me an example of (or a link to) an AND search 'formula' I can type into that window that would actually include all of the following 'cells':

```<code>foo bar
foo banana bar
bar foo
this foo that bar
</code>```

And in case others find this question, it might be nice to see an OR search formula as well

答:
OR Logic

Hardcode the list

You may try custom formula:

=ISNA(MATCH(A2,{"foo", "bar", "banana"},))=false

You may add any number of items inside array { } in double quotes: "that", "boo", ...

Add the list into separate column

I've added a list in column G:

```<code>foo
bar
banana
</code>```

and then applied the formula:

=ISNA(MATCH(A2, G:G ,))=false

The filter did not adjust when I added values in col G, I needed to click on the filter and OK button to refresh it.

AND Logic

For and logic regex may be handy, as @i-i has suggested.

Body:
I know I can do this with formulas, but I'd like to understand how to do it using the popup filter tool (since I'm constantly changing it).

This thing, for reference:

Ordinarily, I can get away with entering the string I want in the "Value or formula" window, like so...

The above works AS LONG AS the exact string I type matches a sub-string in the cell. However, every now and then I want to do something like this...

But that doesn't work.

I've tried all sorts of "formulas", like "foo" && "bar" or ="foo" + "bar"

But of course those don't work either... It doesn't seem to make sense to use the =filter(...) formula, as that requires a range that is already defined by the filter widget itself. I haven't had any luck with that either.

Can anyone give me an example of (or a link to) an AND search 'formula' I can type into that window that would actually include all of the following 'cells':

foo bar
foo banana bar
bar foo
this foo that bar

And in case others find this question, it might be nice to see an OR search formula as well

Body:
OR Logic

Hardcode the list

You may try custom formula:

=ISNA(MATCH(A2,{"foo", "bar", "banana"},))=false

You may add any number of items inside array { } in double quotes: "that", "boo", ...

Add the list into separate column

I've added a list in column G:

foo
bar
banana

and then applied the formula:

=ISNA(MATCH(A2, G:G ,))=false

The filter did not adjust when I added values in col G, I needed to click on the filter and OK button to refresh it.

AND Logic

For and logic regex may be handy, as @i-i has suggested.


问:
Custom View add SubView layout issue
There is a tableView with 2 sections, which have a customized section header view for each.

I want UI of this effect, and header view of section 0 works fine.

While header view of section 1 has an issue.

I don't know what's wrong.

What Apple mechanism do I miss,

convert rect/point?

Here is the code:
the customized view of section 1

```<code>@interface ZBWithDrawHeaderView()
     @property (nonatomic, strong ) UIView *renderView;
 @end
@implementation ZBWithDrawHeaderView

- (instancetype)initWithFrame:(CGRect)frame{

    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor grayColor ];

        _renderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, -17)];
       //it works OK, I don't know the logic.

      //  _renderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 17)];
      //it works Wrong ,what mechanism do I miss

        [self addSubview: _renderView];
        _renderView.backgroundColor = [UIColor redColor ];
    }
    return self;
}
@end
</code>```

Where I put it into use?

```<code>- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   if(section == 0){
         ......
         return view;
   }
    else if (section == 1) {
        ZBWithDrawHeaderView * secondHeaderView = [[ZBWithDrawHeaderView alloc] initWithFrame: CGRectMake(0, 0, KScreenWidth, 25)];
        return secondHeaderView;
    }
    return nil;
 }
</code>```

答:
```<code>- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
     return [UIView new ];
}
</code>```

The two UITableViewDelegate methods added, no strange layout happens. Seems like section header and footer must come in pair.

Title: Custom View add SubView layout issue

Body:
There is a tableView with 2 sections, which have a customized section header view for each.

I want UI of this effect, and header view of section 0 works fine.

While header view of section 1 has an issue.

I don't know what's wrong.

What Apple mechanism do I miss,

convert rect/point?

Here is the code:
the customized view of section 1

@interface ZBWithDrawHeaderView()
     @property (nonatomic, strong ) UIView *renderView;
 @end
@implementation ZBWithDrawHeaderView

- (instancetype)initWithFrame:(CGRect)frame{

    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor grayColor ];

        _renderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, -17)];
       //it works OK, I don't know the logic.

      //  _renderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 17)];
      //it works Wrong ,what mechanism do I miss

        [self addSubview: _renderView];
        _renderView.backgroundColor = [UIColor redColor ];
    }
    return self;
}
@end

Where I put it into use?

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   if(section == 0){
         ......
         return view;
   }
    else if (section == 1) {
        ZBWithDrawHeaderView * secondHeaderView = [[ZBWithDrawHeaderView alloc] initWithFrame: CGRectMake(0, 0, KScreenWidth, 25)];
        return secondHeaderView;
    }
    return nil;
 }

Body:
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
     return [UIView new ];
}

The two UITableViewDelegate methods added, no strange layout happens. Seems like section header and footer must come in pair.


问:
When a function returns, how to close resource handles in C?
If I open a file handle, but the function encounters other error which is not file error,  before closing the handle, would the file handle be leaked?

```<code>FILE* fp = fopen("test.txt", "r");
if (other_condition) {
    perror("other error occurred!");
    return EXIT_FAILURE;
}
</code>```

How to use C to implement RAII template?

答:
For a single resource like a file handle, consider:

```<code>int rc = EXIT_FAILURE;
FILE *fp = fopen(file, "r");
if (fp != NULL)
{
    rc = function_using_resource(fp /* , … */);
    fclose(fp);
}
else
{
    perror(file);
}
return rc;
</code>```

This only uses the resource if it was successfully allocated, and returns the status from the function that uses the allocated resource.  This function opened the file; it is responsible for closing it.  It does close it if it was opened.

The perceived downside to this is that you end up with a lot of functions which are individually not very big.  However, extending this to multiple resources is hard.  You probably end up using a goto, but it is a carefully structured use.  For example, consider code that opens a file stream, and allocates two blocks of memory.  You might end up with code like:

```<code>int function_example(int num_items)
{
    int rc = EXIT_FAILURE;
    struct WotNot *wotsit = NULL;
    struct Havoc  *wreaker = NULL;
    FILE *fp = fopen(file, "r");

    if (fp == NULL)
    {
        err_remark("failed to open file '%s' for reading\n", file);
        goto cleanup;
    }

    if ((wotsit = malloc(num_items * sizeof(*wotsit))) == NULL)
    {
        err_remark("failed to allocated %zu bytes of memory\n",
                   num_items * sizeof(*wotsit));
        goto cleanup;
    }

    if ((rc = function_using_file(fp, num_items, wotsit)) != EXIT_SUCCESS)
    {
        err_remark("processing of wotsits failed\n");
        goto cleanup;
    }

    if ((wreaker = malloc(num_items * 2 * sizeof(*wreaker)) == NULL)
    {
        err_remark("failed to allocated %zu bytes of memory\n",
                   num_items * 2 * sizeof(*wreaker));
        goto cleanup;
    }

    if ((rc = function_wreaking_havoc(num_items, wotsit, wreaker) != EXIT_SUCCESS)
    {
        err_remark("failed to wreak appropriate havoc\n");
        goto cleanup;
    }

    if ((rc = other_function(fp, num_items * 2, wreaker)) != EXIT_SUCCESS)
    {
        err_remark("failed to process the wotsits — not enough havoc?\n");
        goto cleanup;  // Systematic, but nominally superfluous
    }

cleanup:
    free(wreaker);
    free(wotsit);
    if (fp != NULL)
        fclose(fp);
    return rc;
}
</code>```

Note how the resources are initialized to a harmless state (null pointers).  If there's a problem, the code jumps to the cleanup block.  The free() function accepts a null pointer gracefully and does nothing, so those calls don't need a check, but fclose() does not necessarily work cleanly given a null pointer, so the file stream is checked before calling fclose().

This is a fairly common idiom.  Variations include multiple labels for different amounts of cleanup work.  This still tends to be clearest when you don't put too much activity in this function in place of the function calls shown doing the work.  However, it is not uncommon to see work done in the function other than resource allocation — the computation part of the workload is often included, especially if there's work involved such as dynamically growing one or more of the allocated arrays.  It still isn't a particularly good idea to mix things up like that, but that doesn't stop people doing it anyway.

You should have a convention for whether the called function reports the errors or the calling function reports errors, or neither.  You can also use various mechanisms for structuring error reporting.  Making sure that handling errors is as painless as possible is important — it means people are less likely to skimp on the error reporting.

Other questions of some relevance include:

Valid use of goto for error management in C

Avoid repetition in C error handling

Error handling in C

Is assert() evil?

Should we use exit() in C?

Are do-while-false loops common?

How to avoid if chains?

Etc.

Body:
If I open a file handle, but the function encounters other error which is not file error,  before closing the handle, would the file handle be leaked?

FILE* fp = fopen("test.txt", "r");
if (other_condition) {
    perror("other error occurred!");
    return EXIT_FAILURE;
}

How to use C to implement RAII template?

Body:
For a single resource like a file handle, consider:

int rc = EXIT_FAILURE;
FILE *fp = fopen(file, "r");
if (fp != NULL)
{
    rc = function_using_resource(fp /* , … */);
    fclose(fp);
}
else
{
    perror(file);
}
return rc;

This only uses the resource if it was successfully allocated, and returns the status from the function that uses the allocated resource.  This function opened the file; it is responsible for closing it.  It does close it if it was opened.

The perceived downside to this is that you end up with a lot of functions which are individually not very big.  However, extending this to multiple resources is hard.  You probably end up using a goto, but it is a carefully structured use.  For example, consider code that opens a file stream, and allocates two blocks of memory.  You might end up with code like:

int function_example(int num_items)
{
    int rc = EXIT_FAILURE;
    struct WotNot *wotsit = NULL;
    struct Havoc  *wreaker = NULL;
    FILE *fp = fopen(file, "r");

    if (fp == NULL)
    {
        err_remark("failed to open file '%s' for reading\n", file);
        goto cleanup;
    }

    if ((wotsit = malloc(num_items * sizeof(*wotsit))) == NULL)
    {
        err_remark("failed to allocated %zu bytes of memory\n",
                   num_items * sizeof(*wotsit));
        goto cleanup;
    }

    if ((rc = function_using_file(fp, num_items, wotsit)) != EXIT_SUCCESS)
    {
        err_remark("processing of wotsits failed\n");
        goto cleanup;
    }

    if ((wreaker = malloc(num_items * 2 * sizeof(*wreaker)) == NULL)
    {
        err_remark("failed to allocated %zu bytes of memory\n",
                   num_items * 2 * sizeof(*wreaker));
        goto cleanup;
    }

    if ((rc = function_wreaking_havoc(num_items, wotsit, wreaker) != EXIT_SUCCESS)
    {
        err_remark("failed to wreak appropriate havoc\n");
        goto cleanup;
    }

    if ((rc = other_function(fp, num_items * 2, wreaker)) != EXIT_SUCCESS)
    {
        err_remark("failed to process the wotsits — not enough havoc?\n");
        goto cleanup;  // Systematic, but nominally superfluous
    }

cleanup:
    free(wreaker);
    free(wotsit);
    if (fp != NULL)
        fclose(fp);
    return rc;
}

Note how the resources are initialized to a harmless state (null pointers).  If there's a problem, the code jumps to the cleanup block.  The free() function accepts a null pointer gracefully and does nothing, so those calls don't need a check, but fclose() does not necessarily work cleanly given a null pointer, so the file stream is checked before calling fclose().

This is a fairly common idiom.  Variations include multiple labels for different amounts of cleanup work.  This still tends to be clearest when you don't put too much activity in this function in place of the function calls shown doing the work.  However, it is not uncommon to see work done in the function other than resource allocation — the computation part of the workload is often included, especially if there's work involved such as dynamically growing one or more of the allocated arrays.  It still isn't a particularly good idea to mix things up like that, but that doesn't stop people doing it anyway.

You should have a convention for whether the called function reports the errors or the calling function reports errors, or neither.  You can also use various mechanisms for structuring error reporting.  Making sure that handling errors is as painless as possible is important — it means people are less likely to skimp on the error reporting.

Other questions of some relevance include:

Valid use of goto for error management in C

Avoid repetition in C error handling

Error handling in C

Is assert() evil?

Should we use exit() in C?

Are do-while-false loops common?

How to avoid if chains?

Etc.


问:
How to Filter ng-repeat list values Onclicking of Radio Button in Angularjs?
How can i filter category values in list, when clicking on a radio button?

My Plunker

Actually I want to filter category values in list of questions.

we have user data's and question data's in plunker.

user has two categories like "categories": ["Religion & Culture","Social Psychology"],.

question has various of categoryin list.

I am exactly looking to filter user categories values only, in that question category lists.

For Example :- in plunker we have displayed category values using of ng-repeat. the user categories array values are displayed using of two radio buttons, 1.Religion & Culture 2. Social Psychology. if we click the first radio button of Religion & Culture it's should filter only the Religion & Culture in question lists and if we click the second radio button of Social Psychology it's should filter only the religon & Culture values in question lists.  .

My HTML radio button:-

```<code>    <ul>
 <li ng-repeat="mani in users" ><input type="radio" name="myquestion" data-ng-model="myquestion" ng-value="{{mani.categories[0]}}"    id="{{mani.categories[0]}}"><label for="{{mani.categories[0]}" >{{mani.categories[0]}}</label>
 </li>

   <li ng-repeat="mani in users" ><input type="radio" name="myquestion" data-ng-model="myquestion" ng-value="{{mani.categories[1]}}"    id="{{mani.categories[1]}}"><label for="{{mani.categories[1]}" >{{mani.categories[1]}}</label>
      </li>

   </ul>
</code>```

My HTML Filter:-

```<code> ng-repeat="question in questions | filter:myquestion"
</code>```

My Html Data:-

```<code><div ng-repeat="question in questions | filter:myquestion">
  <small>
                <span >{{$index + 1}}.</span>
                  <span >{{question.category}}</span>
              </small>

 </div>
</code>```

My Controller User Data:-

```<code>    $scope.users=[
    {
"_id": "58e73c5c9e2f3f1421e241be",
"displayName": "sarawana kumar",
"provider": "local",
"location": "chennai",
"username": "sarawana",
"dob": "1991-10-04T18:30:00.000Z",
"phone": 7299345250,
"religion": "hindu",
"__v": 0,
"created": "2017-04-07T07:14:36.773Z",
"roles": [
"user"
],
"category": [],
"profileImageURL": "modules/users/client/img/profile/default.png",
"email": "sarawana@gmail.com",
"categories": [
"Religion & Culture",
"Social Psychology"
],
"lastName": "kumar",
"firstName": "sarawana"
}]
</code>```

My Question Data:-

```<code>    $scope.questions = [
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Religion & Culture",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},

{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Moral Ethics",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Social Psychology",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Environment & Health",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Religion & Culture",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Religion & Culture",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Social Psychology",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
}
]
</code>```

Plunker for reference.

We don't know where i did a mistake so please look my plunker for reference and help me.. please update the plunker as well to know the exact solution...thanks.

i have created similar answer please check this plunker http://plnkr.co/edit/1Zzc6nRylgETOvQp3SI2?p=preview i am exactly looking for the same answer in this plunker filtering the values but i want to filter user categories array values.....

答:
angular.module('myApp', []).controller('candidateCtrl', function($scope) {
    $scope.candidates = [
        {name:'Goutam',role:'Engineer',country:'India'},
        {name:'Carl',role:'Engineer',country:'Sweden'},
        {name:'Margareth',role:'Doctor',country:'England'},
        {name:'Hege',role:'Engineer',country:'Norway'},
        {name:'Joe',role:'Engineer',country:'Denmark'},
        {name:'Rathin',role:'Doctor',country:'India'},
        {name:'Birgit',role:'Teacher',country:'Denmark'},
        {name:'Mary',role:'Engineer',country:'England'},
        {name:'Kai',role:'Teacher',country:'Norway'}
        ];

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <body ng-app="myApp">

<div class="container" ng-controller="candidateCtrl">
<h2>Bootstrap inline Radio Buttons</h2>
<div class="row">
<div class="col-lg-4">
  <p>Angular JS Filter by Radio Button</p>
  <form>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Engineer">Engineer
    </label>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Doctor">Doctor
    </label>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Teacher">Teacher
    </label>
  </form>

</div>
</div>

<div class="row">
<div class="col-lg-4">

  <table class="table table-hover">
    <thead>
      <tr>
        <th>Name</th>
        <th>Profession</th>
        <th>Country</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="candidate in candidates | filter:searchText:strict">
        <td>{{candidate.name}}</td>
        <td>{{candidate.role}}</td>
        <td>{{candidate.country}}</td>
      </tr>
    </tbody>
  </table>

</div>
</div>

</div>
</body> </code>```

Body:
How can i filter category values in list, when clicking on a radio button?

My Plunker

Actually I want to filter category values in list of questions.

we have user data's and question data's in plunker.

user has two categories like "categories": ["Religion & Culture","Social Psychology"],.

question has various of categoryin list.

I am exactly looking to filter user categories values only, in that question category lists.

For Example :- in plunker we have displayed category values using of ng-repeat. the user categories array values are displayed using of two radio buttons, 1.Religion & Culture 2. Social Psychology. if we click the first radio button of Religion & Culture it's should filter only the Religion & Culture in question lists and if we click the second radio button of Social Psychology it's should filter only the religon & Culture values in question lists.  .

My HTML radio button:-

<input type="radio" name="myquestion" data-ng-model="myquestion" ng-value="{{mani.categories[0]}}"    id="{{mani.categories[0]}}">{{mani.categories[0]}}

<input type="radio" name="myquestion" data-ng-model="myquestion" ng-value="{{mani.categories[1]}}"    id="{{mani.categories[1]}}">{{mani.categories[1]}}

My HTML Filter:-

 ng-repeat="question in questions | filter:myquestion"

My Html Data:-

                {{$index + 1}}.
                  {{question.category}}

My Controller User Data:-

    $scope.users=[
    {
"_id": "58e73c5c9e2f3f1421e241be",
"displayName": "sarawana kumar",
"provider": "local",
"location": "chennai",
"username": "sarawana",
"dob": "1991-10-04T18:30:00.000Z",
"phone": 7299345250,
"religion": "hindu",
"__v": 0,
"created": "2017-04-07T07:14:36.773Z",
"roles": [
"user"
],
"category": [],
"profileImageURL": "modules/users/client/img/profile/default.png",
"email": "sarawana@gmail.com",
"categories": [
"Religion & Culture",
"Social Psychology"
],
"lastName": "kumar",
"firstName": "sarawana"
}]

My Question Data:-

    $scope.questions = [
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Religion & Culture",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},

{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Moral Ethics",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Social Psychology",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Environment & Health",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Religion & Culture",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Religion & Culture",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
},
{
"_id": "5863d3aaacaeddc00663bc07",
"user": {
"_id": "58072aba0f82a61823c434df",
"displayName": "Table 1",
"dob": "2016-12-22T18:30:00.000Z",
"location": "chennai",
"religion": "hindu",
"roles": [
"admin"
],
"profileImageURL": "./modules/users/client/img/profile/uploads/ac4fbab396c2f725ed5211524f171136"
},

"friend_tag": [],
"emotion": "Confused",
"category": "Social Psychology",
"content": "mani",
"title": "Who Is the best Player?",
"created": "2016-12-28T15:00:58.777Z"
}
]

Plunker for reference.

We don't know where i did a mistake so please look my plunker for reference and help me.. please update the plunker as well to know the exact solution...thanks.

i have created similar answer please check this plunker http://plnkr.co/edit/1Zzc6nRylgETOvQp3SI2?p=preview i am exactly looking for the same answer in this plunker filtering the values but i want to filter user categories array values.....

Body:
angular.module('myApp', []).controller('candidateCtrl', function($scope) {
    $scope.candidates = [
        {name:'Goutam',role:'Engineer',country:'India'},
        {name:'Carl',role:'Engineer',country:'Sweden'},
        {name:'Margareth',role:'Doctor',country:'England'},
        {name:'Hege',role:'Engineer',country:'Norway'},
        {name:'Joe',role:'Engineer',country:'Denmark'},
        {name:'Rathin',role:'Doctor',country:'India'},
        {name:'Birgit',role:'Teacher',country:'Denmark'},
        {name:'Mary',role:'Engineer',country:'England'},
        {name:'Kai',role:'Teacher',country:'Norway'}
        ];

});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <body ng-app="myApp">

<div class="container" ng-controller="candidateCtrl">
<h2>Bootstrap inline Radio Buttons</h2>
<div class="row">
<div class="col-lg-4">
  <p>Angular JS Filter by Radio Button</p>
  <form>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Engineer">Engineer
    </label>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Doctor">Doctor
    </label>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Teacher">Teacher
    </label>
  </form>

</div>
</div>

<div class="row">
<div class="col-lg-4">

  <table class="table table-hover">
    <thead>
      <tr>
        <th>Name</th>
        <th>Profession</th>
        <th>Country</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="candidate in candidates | filter:searchText:strict">
        <td>{{candidate.name}}</td>
        <td>{{candidate.role}}</td>
        <td>{{candidate.country}}</td>
      </tr>
    </tbody>
  </table>

</div>
</div>

</div>
</body>


问:
Background applied to the controller not getting applied to table view cells in storyboard swift
I have a storyboard consisting of a background image on top of which rests a table. My issue is that the background image gets applied to the table but not to the cells of the table, they still remain white.

What is it that I am doing wrong?
Please help

答: You need to set background color as clear color of tableview cell as well as it's content view.          </p>


问:
blank "DOMNodeList" reading XML via Xpath
I am trying to read the value of "SIM" via the below PHP code via the XML given below, but for some reason it gives me a blank "DOMNodeList" Any idea what i am doing wrong here ? I wanted to set that element as

```<code><ns1:SIM old="8902"> 000000 </SIM>
</code>```

How do i do that, because I am trying with below code to find it but it seems output is "DOMNodeList" empty.

```<code>$xpath = new DOMXPath($doc);
$xpath->registerNamespace('ns1', 'http://www.example.com/WSG/ec/');
$result = $xpath->query("/ns1:ModifySIMRequest/ns1:ServiceProfile/ns1:Primary/ns1:SIM");
        foreach ($result AS $node) {
            var_dump($node);
            echo $node->nodeValue;
        }
</code>```

XML in $doc is

```<code><?xml version="1.0"?>
<ns1:ModifySIMRequest xmlns:ns1="http://www.example.com/WSG/ec/">
  <ns1:ServiceProfile>
    <ns1:Speech>
      <ns1:MSN>33808089</ns1:MSN>
      <ns1:AccountNumber>8989895</ns1:AccountNumber>
    </ns1:Speech>
    <ns1:Primary action="mod">
      <ns1:BillingOption>dsdsd</ns1:BillingOption>
      <ns1:SIM old="8902"/>
    </ns1:Primary>
  </ns1:ServiceProfile>
</ns1:ModifySIMRequest>
</code>```

答:
To get attribute

```<code>        echo $node->getAttribute('old');  // 8902
</code>```

To set value

```<code>        $node->nodeValue = '000000';
        echo $doc->saveXML(); // <ns1:SIM old="8902">000000</ns1:SIM>
</code>```

Body:
I am trying to read the value of "SIM" via the below PHP code via the XML given below, but for some reason it gives me a blank "DOMNodeList" Any idea what i am doing wrong here ? I wanted to set that element as

<ns1:SIM old="8902"> 000000 </SIM>

How do i do that, because I am trying with below code to find it but it seems output is "DOMNodeList" empty.

$xpath = new DOMXPath($doc);
$xpath->registerNamespace('ns1', 'http://www.example.com/WSG/ec/');
$result = $xpath->query("/ns1:ModifySIMRequest/ns1:ServiceProfile/ns1:Primary/ns1:SIM");
        foreach ($result AS $node) {
            var_dump($node);
            echo $node->nodeValue;
        }

XML in $doc is

<?xml version="1.0"?>
<ns1:ModifySIMRequest xmlns:ns1="http://www.example.com/WSG/ec/">
  <ns1:ServiceProfile>
    <ns1:Speech>
      <ns1:MSN>33808089</ns1:MSN>
      <ns1:AccountNumber>8989895</ns1:AccountNumber>
    </ns1:Speech>
    <ns1:Primary action="mod">
      <ns1:BillingOption>dsdsd</ns1:BillingOption>
      <ns1:SIM old="8902"/>
    </ns1:Primary>
  </ns1:ServiceProfile>
</ns1:ModifySIMRequest>

Body:
To get attribute

        echo $node->getAttribute('old');  // 8902

To set value

        $node->nodeValue = '000000';
        echo $doc->saveXML(); // <ns1:SIM old="8902">000000</ns1:SIM>


问:
"An unexpected error has occurred" error on accessing PWA (Project Web Access)
I installed Microsoft Office Sharepoint 2007 SP1 using SQL Server 2008 R2 for DB and then installed Microsoft Office Project Server 2007.

I made a web application to host the SSP and another one to host the PWA (Project Web Access) and the PWA was provisioned as: "http://server/pwa"

when i click on this link it gives me an error "An unexpected error has occurred"

i tried to restart the project service and to iisreset but it wasn't solved..

I need to finish this ASAP for our administration :-/

Thanks in advance..

答:
I found the solution:

I had to change the following in web.config :

```<code><configuration>
<system.web>
<customErrors mode="off" />
</code>```

and:

```<code><configuration>
<SharePoint>
<SafeMode CallStack="true"
</code>```

Then the problem appeared to be about the Proxy authentication and i solved it by adding the following inside System.Net

```<code> <defaultProxy>
      <proxy usesystemdefault = "true" bypassonlocal = "true" />
 </defaultProxy>
</code>```

and make sure ur IE proxy settings are correct ..

Body:
I found the solution:

I had to change the following in web.config :

<configuration>
<system.web>
<customErrors mode="off" />

and:

<configuration>
<SharePoint>
<SafeMode CallStack="true"

Then the problem appeared to be about the Proxy authentication and i solved it by adding the following inside System.Net

 <defaultProxy>
      <proxy usesystemdefault = "true" bypassonlocal = "true" />
 </defaultProxy>

and make sure ur IE proxy settings are correct ..


答:
Because Date#- returns a date or a rational. From the docs:

d - other → date or rational

Returns the difference between the two dates if the other is a date object. If the other is a numeric value, returns a date object pointing other days before self. If the other is a fractional number, assumes its precision is at most nanosecond.

Title: Why is " '2019-02-01'.to_date - Date.today" "442/1"?

Body:
I did this:

'2019-02-01'.to_date - Date.today # => 442/1

Why is the return value not 442?


问:
Can spring Sleuth be used with Scala?
I'm developing event-driven Microservices which I use Java and Scala. I used Spring Sleuth and Zipkin for request tracing with Java services, can I use Spring Sleuth with Scala? if not how can I generate trace id and span id in Scala to be sent to Zipkin. </p>

答: I have no knowledge of it being impossible. Maybe you should first try doing it and then asking a question? Also, if for some reason it turns out you can't use it, then if you just google zipkin scala you'll see things like https://github.com/lloydmeta/zipkin-futures , https://github.com/bizreach/play-zipkin-tracing etc.

Title: Can spring Sleuth be used with Scala?


问:
How to make responsive table and header fixed both on same html table
Here is the code pen https://codepen.io/shaswat/pen/EbwPNK

I have made an html table responsive by making all the columns getting repeated and show the correspondent row value up when its mobile display -- so the responsive part is done

Now having trouble to make the header fixed in this html table while scrolling the tbody - so tbody can have fixed height and that time scrolling header should be fixed -- applicable only for the resolutions greater than mobile display
--need help in this

HTML

```<code><h1>Some more Header information</h1>
<h2>Some more Header information</h2>
<h3>Header</h3>

<div class='rg-container'>
    <div class='rg-content'>
        <table class='rg-table'>
            <thead>
                <tr>
                    <th class='text '>id </th>
                    <th class='text '>somcol</th>
                    <th class='text '>biggger id</th>
                    <th class='text '>another id</th>
                    <th class='text '>med col</th>
                    <th class='text '>med col</th>
                    <th class='text '>sheet</th>
                    <th class='text '>sheet</th>
                    <th class='text '>anotherbigcoloumn</th>
                    <th class='text '>small</th>
                    <th class='text '>anotherbigcoloumn</th>
                    <th class='text '>dateformat</th>
                    <th class='text '>dateformat</th>
                    <th class='text '>small col</th>
                    <th class='text '>dateformat</th>
                    <th class='text '>averybigcolumnssssss</th>
                    <th class='text '>mediumclolumnss</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class='text' data-title='id'>id</td>
                    <td class='text' data-title='somcol'>somcol</td>
                    <td class='text' data-title='biggger id'>biggger id</td>
                    <td class='text' data-title='another id'>another id</td>
                    <td class='text' data-title='med col'>med col</td>
                    <td class='text' data-title='med col'>med col</td>
                    <td class='text' data-title='sheet'>sheet</td>
                    <td class='text' data-title='sheet'>sheet</td>
                    <td class='text' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text' data-title='small'>small</td>
                    <td class='text' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text' data-title='dateformat'>date format</td>
                    <td class='text' data-title='dateformat'>date format</td>
                    <td class='text' data-title='small col'>small col</td>
                    <td class='text' data-title='dateformat'>date format</td>
                    <td class='text' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</code>```

CSS

```<code>.rg-container {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.4;
    margin: 0;
    padding: 1em 0.5em;
    color: #222;
}
.rg-header {
    margin-bottom: 1em;
    text-align: left;
}

.rg-header > * {
    display: block;
}

/* table */
table.rg-table {
    width: 100%;
    margin-bottom: 0.5em;
    font-size: 1em;
    border-collapse: collapse;
    border-spacing: 0;
  overflow:scroll;
}
table.rg-table tr {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    text-align: left;
    color: #333;
}
table.rg-table thead {
    border-bottom: 3px solid #ddd;
  background:black;
}

table.rg-table tr {
    border-bottom: 1px solid #ddd;
    color: #222;
}
table.rg-table tr.highlight {
    background-color: #dcf1f0 !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table th {
    font-weight: bold;
    padding: 0.35em;
    font-size: 0.9em;
  color:white;
}
table.rg-table td {
    padding: 0.35em;
    font-size: 0.9em;
}
table.rg-table .highlight td {
    font-weight: bold;
}
table.rg-table th.number, td.number {
    text-align: right;
}

/* media queries */
@media screen and (max-width: 800px) {
.rg-container {
    max-width: 800px;
    margin: 0 auto;
}
table.rg-table {
    width: 100%;
}
table.rg-table tr.hide-mobile, table.rg-table th.hide-mobile, table.rg-table td.hide-mobile {
    display: none;
}
table.rg-table thead {
    display: none;
}
table.rg-table tbody {
    width: 100%;

}
table.rg-table tr, table.rg-table th, table.rg-table td {
    display: block;
    padding: 0;
}
table.rg-table tr {
    border-bottom: none;
    margin: 0 0 1em 0;
    padding: 0.5em;
}
table.rg-table tr.highlight {
    background-color: inherit !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: none;
}
table.rg-table.zebra td:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table tr:nth-child(even) {
    background-color: none;
}
table.rg-table td {
    padding: 0.5em 0 0.25em 0;
    border-bottom: 1px dotted #ccc;
    text-align: right;
}
table.rg-table td[data-title]:before {
    content: attr(data-title);
    font-weight: bold;
    display: inline-block;
    content: attr(data-title);
    float: left;
    margin-right: 0.5em;
    font-size: 0.95em;
}
table.rg-table td:last-child {
    padding-right: 0;
    border-bottom: 2px solid #ccc;
}
table.rg-table td:empty {
    display: none;
}
table.rg-table .highlight td {
    background-color: inherit;
    font-weight: normal;
}
</code>```

答:
If you're looking for pure CSS (No JS) solution + and table cells have dynamic width + and you want to have a fixed header = not possible (unfortunately).

Either make the width of the cells fixed, or use Javascript/jQuery to change the width of the header on window resize, or give up on having fixed header.

Body:
Here is the code pen https://codepen.io/shaswat/pen/EbwPNK

I have made an html table responsive by making all the columns getting repeated and show the correspondent row value up when its mobile display -- so the responsive part is done

Now having trouble to make the header fixed in this html table while scrolling the tbody - so tbody can have fixed height and that time scrolling header should be fixed -- applicable only for the resolutions greater than mobile display
--need help in this

HTML

Some more Header information

Some more Header information

Header

                    id
                    somcol
                    biggger id
                    another id
                    med col
                    med col
                    sheet
                    sheet
                    anotherbigcoloumn
                    small
                    anotherbigcoloumn
                    dateformat
                    dateformat
                    small col
                    dateformat
                    averybigcolumnssssss
                    mediumclolumnss

                    id
                    somcol
                    biggger id
                    another id
                    med col
                    med col
                    sheet
                    sheet
                    another big coloumn
                    small
                    another big coloumn
                    date format
                    date format
                    small col
                    date format
                    a very big columnssssss
                    medium clolumnss

CSS

.rg-container {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.4;
    margin: 0;
    padding: 1em 0.5em;
    color: #222;
}
.rg-header {
    margin-bottom: 1em;
    text-align: left;
}

.rg-header > * {
    display: block;
}

/* table */
table.rg-table {
    width: 100%;
    margin-bottom: 0.5em;
    font-size: 1em;
    border-collapse: collapse;
    border-spacing: 0;
  overflow:scroll;
}
table.rg-table tr {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    text-align: left;
    color: #333;
}
table.rg-table thead {
    border-bottom: 3px solid #ddd;
  background:black;
}

table.rg-table tr {
    border-bottom: 1px solid #ddd;
    color: #222;
}
table.rg-table tr.highlight {
    background-color: #dcf1f0 !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table th {
    font-weight: bold;
    padding: 0.35em;
    font-size: 0.9em;
  color:white;
}
table.rg-table td {
    padding: 0.35em;
    font-size: 0.9em;
}
table.rg-table .highlight td {
    font-weight: bold;
}
table.rg-table th.number, td.number {
    text-align: right;
}

/* media queries */
@media screen and (max-width: 800px) {
.rg-container {
    max-width: 800px;
    margin: 0 auto;
}
table.rg-table {
    width: 100%;
}
table.rg-table tr.hide-mobile, table.rg-table th.hide-mobile, table.rg-table td.hide-mobile {
    display: none;
}
table.rg-table thead {
    display: none;
}
table.rg-table tbody {
    width: 100%;

}
table.rg-table tr, table.rg-table th, table.rg-table td {
    display: block;
    padding: 0;
}
table.rg-table tr {
    border-bottom: none;
    margin: 0 0 1em 0;
    padding: 0.5em;
}
table.rg-table tr.highlight {
    background-color: inherit !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: none;
}
table.rg-table.zebra td:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table tr:nth-child(even) {
    background-color: none;
}
table.rg-table td {
    padding: 0.5em 0 0.25em 0;
    border-bottom: 1px dotted #ccc;
    text-align: right;
}
table.rg-table td[data-title]:before {
    content: attr(data-title);
    font-weight: bold;
    display: inline-block;
    content: attr(data-title);
    float: left;
    margin-right: 0.5em;
    font-size: 0.95em;
}
table.rg-table td:last-child {
    padding-right: 0;
    border-bottom: 2px solid #ccc;
}
table.rg-table td:empty {
    display: none;
}
table.rg-table .highlight td {
    background-color: inherit;
    font-weight: normal;
}


问:
cannot import gradle project in oxygen eclipse - error on delombok line
I am getting an error in importing an existing gradle project - which has lombok as well, and the error while importing points to lombok line only.

How can I solve this error - so that importing of the project is successful?

If I comment that line - then it works but then lombok does not work for me.

答:
Check for Java Home Directory shown in the Gradle loading window at the end - if that is shown as unknown then your problem solution is as follows:

In Oxygen-eclipse :
Go to eclipse.ini file and edit above -vmargs as follows:

```<code>-vm
C:\Program Files\Java\jdk1.8.0_65\bin\javaw.exe<YOUR JDK Path>
</code>```

In any other eclipse version - make sure the Java Home Directory is set properly either using .ini file or via the eclipse preferences menu.

Body:
Check for Java Home Directory shown in the Gradle loading window at the end - if that is shown as unknown then your problem solution is as follows:

In Oxygen-eclipse :
Go to eclipse.ini file and edit above -vmargs as follows:

-vm
C:\Program Files\Java\jdk1.8.0_65\bin\javaw.exe<YOUR JDK Path>

In any other eclipse version - make sure the Java Home Directory is set properly either using .ini file or via the eclipse preferences menu.


问:
Can you have a constrained QUERY within an Arrayformula?
I have a query that needs to be INDEPENDENTLY applied to each cell in column A. The Query has where column condition that contains value in "A:A". Is there way to do this inside an arrayformula? I  have tried constraining the return to "limit 1" (there is only one column selected so it will not expand into adjacent cells) or array_constrain the query to 1 row + 1 cell, but it only seems to return the first value of the query selected column.

Example query returns 1 cell of value (without header):

```<code>=query(D:E, "select D where E contains '"&A:A&"' limit 1, 0)
</code>```

Wrap into force 1 cell

```<code>=array_constrain(query above,1,1) constrains to 1 cell as well
</code>```

Wrap in arrayformula but it will only return first value of D

```<code>=arrayformula(if(A:A<>"",apply the constrained query,0)
</code>```

Any ideas?

答:
I think this won't be possible. But, If the condition is just contains, then just use VLOOKUP. If the values in column A are unique. You could use

```
 matches '"JOIN("|", A1:A50)"'
```

Body:
I have a query that needs to be INDEPENDENTLY applied to each cell in column A. The Query has where column condition that contains value in "A:A". Is there way to do this inside an arrayformula? I  have tried constraining the return to "limit 1" (there is only one column selected so it will not expand into adjacent cells) or array_constrain the query to 1 row + 1 cell, but it only seems to return the first value of the query selected column.

Example query returns 1 cell of value (without header):

=query(D:E, "select D where E contains '"&A:A&"' limit 1, 0)

Wrap into force 1 cell

=array_constrain(query above,1,1) constrains to 1 cell as well

Wrap in arrayformula but it will only return first value of D

=arrayformula(if(A:A<>"",apply the constrained query,0)

Any ideas?

Body:
I think this won't be possible. But, If the condition is just contains, then just use VLOOKUP. If the values in column A are unique. You could use

 matches '"JOIN("|", A1:A50)"'