问:
ActivityNotFoundException despite the activity being registered in the manifest file
I am developing an android application that has multiple packages and for a particular activity it throws the ActivityNotFoundException....Can someone point out what is wrong with my code......
the package of the activity is com.example.neo.smsapp.IFTT

The logcat produces following lines

```<code>*FATAL EXCEPTION: main

Process: com.example.neo.smsapp, PID: 7320
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.neo.smsapp/com.example.neo.smsapp.IFTT.CancelAnAlarmActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
at android.app.Activity.startActivityForResult(Activity.java:3917)
at android.app.Activity.startActivityForResult(Activity.java:3877)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
at android.app.Activity.startActivity(Activity.java:4200)
at android.app.Activity.startActivity(Activity.java:4168)
at com.example.neo.smsapp.SetuppageActivity.onOptionsItemSelected(SetuppageActivity.java:239)*
</code>```

This is the setuppage activity (Main activity)

```<code>package com.example.neo.smsapp;

/**
 * Created by Neo on 04/02/2017.
 */

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import javax.sql.DataSource;

import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TimePicker;
import android.widget.Toast;
import android.view.View.OnClickListener;

public class SetuppageActivity extends AppCompatActivity implements View.OnClickListener {

    private String mNumber;
    EditText mEditTextNumber;
    EditText mEditTextMessage;
    private String mContactdisplayName;
    private long mInterval;
    private String mMessage;
    private String mFrequency;
    Button mButtonContact;
    Button mDatePickUp;
    Button mTimePickUp;
    Button mConfirm;
    RadioButton mOneTime, mFifteenMinuets, mHalfHour, mHourR, mHalfDay, mDaily, mWeekly, mMonthly, mYearly;
    private int mHour;
    private int mMinutes;
    private int mSeconds;

    private int mYear;
    private int mMonth;
    private int mDay;

    private int mCurrentYear;
    private int mCurrentMonth;
    private int mCurrentDay;
    private int mCurrentHour;
    private int mCurrentMinute;

    DatePickerDialog mDatePickerDialog;
    TimePickerDialog mTimePickerDialog;
    Calendar c;
    private static SetuppageActivity mMainActivity;

    //AlarmManager am;
    //PendingIntent pi;
    private int mId;
    private boolean isOneTime = false;
    private PendingIntentsDataSource mDatasource;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setuppage);
        mMainActivity = this;
        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);
        mButtonContact = (Button) findViewById(R.id.buttonContact);
        mEditTextNumber = (EditText) findViewById(R.id.editTextNumber);
        mDatePickUp = (Button) findViewById(R.id.buttonDatePickup);
        mTimePickUp = (Button) findViewById(R.id.buttonTimePickup);
        mConfirm = (Button) findViewById(R.id.buttonConfirm);
        mEditTextMessage = (EditText) findViewById(R.id.editTextMessage);
        mOneTime = (RadioButton) findViewById(R.id.oneTime);
        mOneTime.setOnClickListener(this);
        mFifteenMinuets = (RadioButton) findViewById(R.id.fifteenMinutes);
        mFifteenMinuets.setOnClickListener(this);
        mHalfHour = (RadioButton) findViewById(R.id.halfHour);
        mHalfHour.setOnClickListener(this);
        mHourR = (RadioButton) findViewById(R.id.hour);
        mHourR.setOnClickListener(this);
        mHalfDay = (RadioButton) findViewById(R.id.halfDay);
        mHalfDay.setOnClickListener(this);
        mDaily = (RadioButton) findViewById(R.id.daily);
        mDaily.setOnClickListener(this);
        mWeekly = (RadioButton) findViewById(R.id.weekly);
        mWeekly.setOnClickListener(this);
        mMonthly = (RadioButton) findViewById(R.id.monthly);
        mMonthly.setOnClickListener(this);
        mYearly = (RadioButton) findViewById(R.id.Yearly);
        mEditTextNumber.setText("");
        mEditTextMessage.setText("");

        //create/open the database
        mDatasource = new PendingIntentsDataSource(this);
        mDatasource.open();

        c = Calendar.getInstance();
        mCurrentYear = c.get(Calendar.YEAR);
        mCurrentMonth = c.get(Calendar.MONTH);
        mCurrentDay = c.get(Calendar.DAY_OF_MONTH);
        mCurrentHour = c.get(Calendar.HOUR_OF_DAY);
        mCurrentMinute = c.get(Calendar.MINUTE);
        mButtonContact.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                startActivityForResult(intent, 1);
            }
        });
        mDatePickerDialog = new DatePickerDialog(this, mDateSetListener, mCurrentYear, mCurrentMonth,
                mCurrentDay);
        mTimePickerDialog = new TimePickerDialog(this, mTimeSetListener, mCurrentHour, mCurrentMinute, true);
        // add a click listener to the button
        mDatePickUp.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                //showDialog(DATE_DIALOG_ID);
                //DialogFragment df = new DialogFragment();
                //FragmentManager fm = getFragmentManager();
                mDatePickerDialog.show();
                //df.show(manager, tag)
            }
        });

        mTimePickUp.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                //showDialog(DATE_DIALOG_ID);
                //DialogFragment df = new DialogFragment();
                //FragmentManager fm = getFragmentManager();
                mTimePickerDialog.show();
                //df.show(manager, tag)
            }
        });

        mConfirm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mMessage = mEditTextMessage.getText().toString();
                mNumber = mEditTextNumber.getText().toString();
                c.set(Calendar.HOUR_OF_DAY, mHour);
                c.set(Calendar.MINUTE, mMinutes);
                c.set(Calendar.SECOND, 0);
                //c.
                //c.set(Calendar.DAY_OF_MONTH, mDay);
                c.set(mYear, mMonth, mDay);
                /*AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(getApplicationContext().ALARM_SERVICE);*/
                Intent i = new Intent(getApplicationContext(), SendSMSAlarmService.class);
                i.putExtra("com.example.neo.smsapp.number", mNumber);
                i.putExtra("com.example.neo.smsapp.message", mMessage);
                i.putExtra("com.example.neo.smsapp.frequency", mFrequency);

                /*final int*/
                mId = (int) System.currentTimeMillis();
                i.putExtra("com.example.neo.smsapp.id", mId);
                AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(getApplicationContext().ALARM_SERVICE);
                PendingIntent pi = PendingIntent.getService(getApplicationContext(), mId, i, PendingIntent.FLAG_UPDATE_CURRENT);

                if (isOneTime == false) {
                    am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), mInterval, pi);
                    addToDatabase(true);
                }
                if (isOneTime == true) {
                    am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
                    addToDatabase(false);
                    /*TimerTask deleteAPendingIntentFromDatabaseForOneTimeAlarm = new TimerTask(){
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            //if(isOneTime == true){
                                mDatasource.deletePendingIntent(mId);
                            //}
                        }

                    };
                    Timer timer = new Timer();
                    timer.schedule(deleteAPendingIntentFromDatabaseForOneTimeAlarm, c.getTimeInMillis());*/
                }

                Toast.makeText(getApplicationContext(), "Your SMS has been scheduled...", Toast.LENGTH_LONG).show();
                //exit the app
                /*Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);*/
                //finish();
                Intent refresh = new Intent();
                refresh.setClassName("com.example.neo.smsapp", "com.example.neo.smsapp.SetuppageActivity");
                startActivity(refresh);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.setuppage, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            /*case R.id.menuCancelAnAlarm:
                Intent i = new Intent();
                //i.setClassName("co", "com.somitsolutions.android.smsscheduler.CancelAnAlarmActivity");
                i.setClassName(getComponentName().getPackageName(),"CancelAnAlarmActivity");
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                finish();
                return true;*/
            case R.id.menuCancelAnAlarm:
                Intent i = new Intent();
                i.setClassName("com.example.neo.smsapp","com.example.neo.smsapp.IFTT.CancelAnAlarmActivity");
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                finish();
                return true;

        }
        return false;
    }

    @Override
    public void onPause() {
        super.onPause();
        mDatasource.close();
        /*mEditTextMessage.setText("");
        mEditTextNumber.setText("");*/
    }

    @Override
    public void onResume() {
        super.onResume();
        mDatasource.open();
        c = Calendar.getInstance();
        mCurrentYear = c.get(Calendar.YEAR);
        mCurrentMonth = c.get(Calendar.MONTH);
        mCurrentDay = c.get(Calendar.DAY_OF_MONTH);
        mCurrentHour = c.get(Calendar.HOUR_OF_DAY);
        mCurrentMinute = c.get(Calendar.MINUTE);
    }

    @Override
    public void onStart() {
        super.onStart();
        /*mEditTextMessage.setText("");
        mEditTextNumber.setText("");    */
        mDatasource.open();
        c = Calendar.getInstance();
        mCurrentYear = c.get(Calendar.YEAR);
        mCurrentMonth = c.get(Calendar.MONTH);
        mCurrentDay = c.get(Calendar.DAY_OF_MONTH);
        mCurrentHour = c.get(Calendar.HOUR_OF_DAY);
        mCurrentMinute = c.get(Calendar.MINUTE);

    }

    @Override
    public void onStop() {
        super.onStop();
        /*mEditTextMessage.setText("");
        mEditTextNumber.setText("");    */
        mDatasource.close();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /*mEditTextMessage.setText("");
        mEditTextNumber.setText("");*/
        mDatasource.close();
    }

    @Override
    public void onBackPressed() {
        //exit the app
        mDatasource.close();
        //finish();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(intent);
        //android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Uri uri = data.getData();

            if (uri != null) {
                Cursor c = null;
                try {
                    c = getContentResolver().query(uri, new String[]{
                                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                                    ContactsContract.CommonDataKinds.Phone.TYPE,
                                    ContactsContract.CommonDataKinds.Identity.DISPLAY_NAME},
                            null, null, null);

                    if (c != null && c.moveToFirst()) {
                        //mNumber = c.getString(0);
                        int type = c.getInt(1);
                        mEditTextNumber.setText(c.getString(0));
                        mContactdisplayName = c.getString(2);
                    }
                } finally {
                    if (c != null) {
                        c.close();
                    }
                }
            }
        }
    }

    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;

                }
            };

    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mHour = hourOfDay;
                    mMinutes = minute;
                    //updateDisplay();
                }
            };

    public static SetuppageActivity getMAinActivity() {
        return mMainActivity;
    }

    public String getNumberToSend() {
        return mNumber;
    }

    public String getSMSMessage() {
        return mMessage;
    }

    public int getDay() {
        return mDay;
    }

    public int getMonth() {
        return mMonth;
    }

    public int getYear() {
        return mYear;
    }

    public int getHour() {
        return mHour;
    }

    public int getMinutes() {
        return mMinutes;
    }

    public int getSeconds() {
        return mSeconds;
    }

    public PendingIntentsDataSource getDataSource() {
        //create/open the database
        return mDatasource;
    }
    //mDatasource = new PendingIntentsDataSource(this);
    //mDatasource.open();

    @Override
    public void onClick(View v) {

        // TODO Auto-generated method stub

        if (v.equals(mOneTime)) {
            isOneTime = true;
            mFrequency = "Once";
        }
        if (v.equals(mFifteenMinuets)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
            mInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
            mFrequency = "15 mins";
            isOneTime = false;
            //c.set(mYear, mMonth, mDay);
        }
        if (v.equals(mHalfHour)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_HALF_HOUR, pi);
            mInterval = AlarmManager.INTERVAL_HALF_HOUR;
            mFrequency = "Half Hour";
            //c.set(mYear, mMonth, mDay);
            isOneTime = false;
        }
        if (v.equals(mHourR)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pi);
            //c.set(mYear, mMonth, mDay);
            mInterval = AlarmManager.INTERVAL_HOUR;
            mFrequency = "Hour";
            isOneTime = false;
        }
        if (v.equals(mHalfDay)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_HALF_DAY, pi);
            //c.set(mYear, mMonth, mDay);
            mInterval = AlarmManager.INTERVAL_HALF_DAY;
            mFrequency = "Half Day";
            isOneTime = false;
        }
        if (v.equals(mDaily)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
            //c.set(mYear, mMonth, mDay);
            mInterval = AlarmManager.INTERVAL_DAY;
            mFrequency = "Daily";
            isOneTime = false;
        }
        if (v.equals(mWeekly)) {
            //int day = c.get(Calendar.DAY_OF_WEEK);
            //c.set(mYear, mMonth, mDay);
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 7*24*60*60*1000, pi);
            mInterval = 7 * 24 * 60 * 60 * 1000;
            mFrequency = "Week";
            isOneTime = false;

        }
        if (v.equals(mMonthly)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);*/
            isOneTime = false;
            mFrequency = "Month";
            int month = c.get(Calendar.MONTH);
            if ((month == Calendar.JANUARY) || (month == Calendar.MARCH) || (month == Calendar.MAY) || (month == Calendar.JULY) || (month == Calendar.AUGUST) || (month == Calendar.OCTOBER) || (month == Calendar.DECEMBER)) {
                mInterval = 31 * 24 * 60 * 60 * 1000;
            }
            if ((month == Calendar.APRIL) || (month == Calendar.JUNE) || (month == Calendar.SEPTEMBER) || (month == Calendar.NOVEMBER)) {
                mInterval = 30 * 24 * 60 * 60 * 1000;
            }
            if (month == Calendar.FEBRUARY) {
                int year = c.get(Calendar.YEAR);
                if ((year % 4) == 0) {
                    mInterval = 29 * 24 * 60 * 60 * 1000;
                }
                if ((year % 4) != 0) {
                    mInterval = 28 * 24 * 60 * 60 * 1000;
                }

            }

        }
        if (v.equals(mYearly)) {
            //c.set(mYear, mMonth, mDay);
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 365*24*60*60*1000, pi);
            mInterval = 365 * 24 * 60 * 60 * 1000;
            mFrequency = "Year";
            isOneTime = false;
        }
        //
    }

    private void addToDatabase(boolean isRepeated) {
        if (isRepeated == true) {

            SMSSchedulerPendingIntent newDatabeseEntry = mDatasource.createPendingIntents(mId, mHour, mMinutes, mSeconds, mYear, mMonth, mDay, mFrequency, mNumber, mContactdisplayName, mMessage);
        }
        if (isRepeated == false) {
            SMSSchedulerPendingIntent newDatabeseEntry = mDatasource.createPendingIntents(mId, mHour, mMinutes, mSeconds, mYear, mMonth, mDay, mFrequency, mNumber, mContactdisplayName, mMessage);
        }
    }
}
</code>```

Manifest file

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

        <activity android:name=".CancelAnAlarmActivity"
            android:label="CancelAlarm"
            android:screenOrientation="landscape">
        </activity>

        <service android:name=".SendSMSAlarmService"/>
    </application>
</code>```

答:
Please define your activity in android manifest file.
Add this code to your android manifest file</p>

```<code><activity android:name=".SetuppageActivity"
            android:label="">
        </activity>
</code>```

Body:
I am developing an android application that has multiple packages and for a particular activity it throws the ActivityNotFoundException....Can someone point out what is wrong with my code......
the package of the activity is com.example.neo.smsapp.IFTT

The logcat produces following lines

*FATAL EXCEPTION: main

Process: com.example.neo.smsapp, PID: 7320
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.neo.smsapp/com.example.neo.smsapp.IFTT.CancelAnAlarmActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
at android.app.Activity.startActivityForResult(Activity.java:3917)
at android.app.Activity.startActivityForResult(Activity.java:3877)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
at android.app.Activity.startActivity(Activity.java:4200)
at android.app.Activity.startActivity(Activity.java:4168)
at com.example.neo.smsapp.SetuppageActivity.onOptionsItemSelected(SetuppageActivity.java:239)*

This is the setuppage activity (Main activity)

package com.example.neo.smsapp;

/**
 * Created by Neo on 04/02/2017.
 */

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import javax.sql.DataSource;

import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TimePicker;
import android.widget.Toast;
import android.view.View.OnClickListener;

public class SetuppageActivity extends AppCompatActivity implements View.OnClickListener {

    private String mNumber;
    EditText mEditTextNumber;
    EditText mEditTextMessage;
    private String mContactdisplayName;
    private long mInterval;
    private String mMessage;
    private String mFrequency;
    Button mButtonContact;
    Button mDatePickUp;
    Button mTimePickUp;
    Button mConfirm;
    RadioButton mOneTime, mFifteenMinuets, mHalfHour, mHourR, mHalfDay, mDaily, mWeekly, mMonthly, mYearly;
    private int mHour;
    private int mMinutes;
    private int mSeconds;

    private int mYear;
    private int mMonth;
    private int mDay;

    private int mCurrentYear;
    private int mCurrentMonth;
    private int mCurrentDay;
    private int mCurrentHour;
    private int mCurrentMinute;

    DatePickerDialog mDatePickerDialog;
    TimePickerDialog mTimePickerDialog;
    Calendar c;
    private static SetuppageActivity mMainActivity;

    //AlarmManager am;
    //PendingIntent pi;
    private int mId;
    private boolean isOneTime = false;
    private PendingIntentsDataSource mDatasource;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setuppage);
        mMainActivity = this;
        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);
        mButtonContact = (Button) findViewById(R.id.buttonContact);
        mEditTextNumber = (EditText) findViewById(R.id.editTextNumber);
        mDatePickUp = (Button) findViewById(R.id.buttonDatePickup);
        mTimePickUp = (Button) findViewById(R.id.buttonTimePickup);
        mConfirm = (Button) findViewById(R.id.buttonConfirm);
        mEditTextMessage = (EditText) findViewById(R.id.editTextMessage);
        mOneTime = (RadioButton) findViewById(R.id.oneTime);
        mOneTime.setOnClickListener(this);
        mFifteenMinuets = (RadioButton) findViewById(R.id.fifteenMinutes);
        mFifteenMinuets.setOnClickListener(this);
        mHalfHour = (RadioButton) findViewById(R.id.halfHour);
        mHalfHour.setOnClickListener(this);
        mHourR = (RadioButton) findViewById(R.id.hour);
        mHourR.setOnClickListener(this);
        mHalfDay = (RadioButton) findViewById(R.id.halfDay);
        mHalfDay.setOnClickListener(this);
        mDaily = (RadioButton) findViewById(R.id.daily);
        mDaily.setOnClickListener(this);
        mWeekly = (RadioButton) findViewById(R.id.weekly);
        mWeekly.setOnClickListener(this);
        mMonthly = (RadioButton) findViewById(R.id.monthly);
        mMonthly.setOnClickListener(this);
        mYearly = (RadioButton) findViewById(R.id.Yearly);
        mEditTextNumber.setText("");
        mEditTextMessage.setText("");

        //create/open the database
        mDatasource = new PendingIntentsDataSource(this);
        mDatasource.open();

        c = Calendar.getInstance();
        mCurrentYear = c.get(Calendar.YEAR);
        mCurrentMonth = c.get(Calendar.MONTH);
        mCurrentDay = c.get(Calendar.DAY_OF_MONTH);
        mCurrentHour = c.get(Calendar.HOUR_OF_DAY);
        mCurrentMinute = c.get(Calendar.MINUTE);
        mButtonContact.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                startActivityForResult(intent, 1);
            }
        });
        mDatePickerDialog = new DatePickerDialog(this, mDateSetListener, mCurrentYear, mCurrentMonth,
                mCurrentDay);
        mTimePickerDialog = new TimePickerDialog(this, mTimeSetListener, mCurrentHour, mCurrentMinute, true);
        // add a click listener to the button
        mDatePickUp.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                //showDialog(DATE_DIALOG_ID);
                //DialogFragment df = new DialogFragment();
                //FragmentManager fm = getFragmentManager();
                mDatePickerDialog.show();
                //df.show(manager, tag)
            }
        });

        mTimePickUp.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                //showDialog(DATE_DIALOG_ID);
                //DialogFragment df = new DialogFragment();
                //FragmentManager fm = getFragmentManager();
                mTimePickerDialog.show();
                //df.show(manager, tag)
            }
        });

        mConfirm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mMessage = mEditTextMessage.getText().toString();
                mNumber = mEditTextNumber.getText().toString();
                c.set(Calendar.HOUR_OF_DAY, mHour);
                c.set(Calendar.MINUTE, mMinutes);
                c.set(Calendar.SECOND, 0);
                //c.
                //c.set(Calendar.DAY_OF_MONTH, mDay);
                c.set(mYear, mMonth, mDay);
                /*AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(getApplicationContext().ALARM_SERVICE);*/
                Intent i = new Intent(getApplicationContext(), SendSMSAlarmService.class);
                i.putExtra("com.example.neo.smsapp.number", mNumber);
                i.putExtra("com.example.neo.smsapp.message", mMessage);
                i.putExtra("com.example.neo.smsapp.frequency", mFrequency);

                /*final int*/
                mId = (int) System.currentTimeMillis();
                i.putExtra("com.example.neo.smsapp.id", mId);
                AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(getApplicationContext().ALARM_SERVICE);
                PendingIntent pi = PendingIntent.getService(getApplicationContext(), mId, i, PendingIntent.FLAG_UPDATE_CURRENT);

                if (isOneTime == false) {
                    am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), mInterval, pi);
                    addToDatabase(true);
                }
                if (isOneTime == true) {
                    am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
                    addToDatabase(false);
                    /*TimerTask deleteAPendingIntentFromDatabaseForOneTimeAlarm = new TimerTask(){
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            //if(isOneTime == true){
                                mDatasource.deletePendingIntent(mId);
                            //}
                        }

                    };
                    Timer timer = new Timer();
                    timer.schedule(deleteAPendingIntentFromDatabaseForOneTimeAlarm, c.getTimeInMillis());*/
                }

                Toast.makeText(getApplicationContext(), "Your SMS has been scheduled...", Toast.LENGTH_LONG).show();
                //exit the app
                /*Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);*/
                //finish();
                Intent refresh = new Intent();
                refresh.setClassName("com.example.neo.smsapp", "com.example.neo.smsapp.SetuppageActivity");
                startActivity(refresh);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.setuppage, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            /*case R.id.menuCancelAnAlarm:
                Intent i = new Intent();
                //i.setClassName("co", "com.somitsolutions.android.smsscheduler.CancelAnAlarmActivity");
                i.setClassName(getComponentName().getPackageName(),"CancelAnAlarmActivity");
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                finish();
                return true;*/
            case R.id.menuCancelAnAlarm:
                Intent i = new Intent();
                i.setClassName("com.example.neo.smsapp","com.example.neo.smsapp.IFTT.CancelAnAlarmActivity");
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                finish();
                return true;

        }
        return false;
    }

    @Override
    public void onPause() {
        super.onPause();
        mDatasource.close();
        /*mEditTextMessage.setText("");
        mEditTextNumber.setText("");*/
    }

    @Override
    public void onResume() {
        super.onResume();
        mDatasource.open();
        c = Calendar.getInstance();
        mCurrentYear = c.get(Calendar.YEAR);
        mCurrentMonth = c.get(Calendar.MONTH);
        mCurrentDay = c.get(Calendar.DAY_OF_MONTH);
        mCurrentHour = c.get(Calendar.HOUR_OF_DAY);
        mCurrentMinute = c.get(Calendar.MINUTE);
    }

    @Override
    public void onStart() {
        super.onStart();
        /*mEditTextMessage.setText("");
        mEditTextNumber.setText("");    */
        mDatasource.open();
        c = Calendar.getInstance();
        mCurrentYear = c.get(Calendar.YEAR);
        mCurrentMonth = c.get(Calendar.MONTH);
        mCurrentDay = c.get(Calendar.DAY_OF_MONTH);
        mCurrentHour = c.get(Calendar.HOUR_OF_DAY);
        mCurrentMinute = c.get(Calendar.MINUTE);

    }

    @Override
    public void onStop() {
        super.onStop();
        /*mEditTextMessage.setText("");
        mEditTextNumber.setText("");    */
        mDatasource.close();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /*mEditTextMessage.setText("");
        mEditTextNumber.setText("");*/
        mDatasource.close();
    }

    @Override
    public void onBackPressed() {
        //exit the app
        mDatasource.close();
        //finish();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(intent);
        //android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Uri uri = data.getData();

            if (uri != null) {
                Cursor c = null;
                try {
                    c = getContentResolver().query(uri, new String[]{
                                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                                    ContactsContract.CommonDataKinds.Phone.TYPE,
                                    ContactsContract.CommonDataKinds.Identity.DISPLAY_NAME},
                            null, null, null);

                    if (c != null && c.moveToFirst()) {
                        //mNumber = c.getString(0);
                        int type = c.getInt(1);
                        mEditTextNumber.setText(c.getString(0));
                        mContactdisplayName = c.getString(2);
                    }
                } finally {
                    if (c != null) {
                        c.close();
                    }
                }
            }
        }
    }

    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;

                }
            };

    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mHour = hourOfDay;
                    mMinutes = minute;
                    //updateDisplay();
                }
            };

    public static SetuppageActivity getMAinActivity() {
        return mMainActivity;
    }

    public String getNumberToSend() {
        return mNumber;
    }

    public String getSMSMessage() {
        return mMessage;
    }

    public int getDay() {
        return mDay;
    }

    public int getMonth() {
        return mMonth;
    }

    public int getYear() {
        return mYear;
    }

    public int getHour() {
        return mHour;
    }

    public int getMinutes() {
        return mMinutes;
    }

    public int getSeconds() {
        return mSeconds;
    }

    public PendingIntentsDataSource getDataSource() {
        //create/open the database
        return mDatasource;
    }
    //mDatasource = new PendingIntentsDataSource(this);
    //mDatasource.open();

    @Override
    public void onClick(View v) {

        // TODO Auto-generated method stub

        if (v.equals(mOneTime)) {
            isOneTime = true;
            mFrequency = "Once";
        }
        if (v.equals(mFifteenMinuets)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
            mInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
            mFrequency = "15 mins";
            isOneTime = false;
            //c.set(mYear, mMonth, mDay);
        }
        if (v.equals(mHalfHour)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_HALF_HOUR, pi);
            mInterval = AlarmManager.INTERVAL_HALF_HOUR;
            mFrequency = "Half Hour";
            //c.set(mYear, mMonth, mDay);
            isOneTime = false;
        }
        if (v.equals(mHourR)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pi);
            //c.set(mYear, mMonth, mDay);
            mInterval = AlarmManager.INTERVAL_HOUR;
            mFrequency = "Hour";
            isOneTime = false;
        }
        if (v.equals(mHalfDay)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_HALF_DAY, pi);
            //c.set(mYear, mMonth, mDay);
            mInterval = AlarmManager.INTERVAL_HALF_DAY;
            mFrequency = "Half Day";
            isOneTime = false;
        }
        if (v.equals(mDaily)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
            //c.set(mYear, mMonth, mDay);
            mInterval = AlarmManager.INTERVAL_DAY;
            mFrequency = "Daily";
            isOneTime = false;
        }
        if (v.equals(mWeekly)) {
            //int day = c.get(Calendar.DAY_OF_WEEK);
            //c.set(mYear, mMonth, mDay);
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 7*24*60*60*1000, pi);
            mInterval = 7 * 24 * 60 * 60 * 1000;
            mFrequency = "Week";
            isOneTime = false;

        }
        if (v.equals(mMonthly)) {
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);*/
            isOneTime = false;
            mFrequency = "Month";
            int month = c.get(Calendar.MONTH);
            if ((month == Calendar.JANUARY) || (month == Calendar.MARCH) || (month == Calendar.MAY) || (month == Calendar.JULY) || (month == Calendar.AUGUST) || (month == Calendar.OCTOBER) || (month == Calendar.DECEMBER)) {
                mInterval = 31 * 24 * 60 * 60 * 1000;
            }
            if ((month == Calendar.APRIL) || (month == Calendar.JUNE) || (month == Calendar.SEPTEMBER) || (month == Calendar.NOVEMBER)) {
                mInterval = 30 * 24 * 60 * 60 * 1000;
            }
            if (month == Calendar.FEBRUARY) {
                int year = c.get(Calendar.YEAR);
                if ((year % 4) == 0) {
                    mInterval = 29 * 24 * 60 * 60 * 1000;
                }
                if ((year % 4) != 0) {
                    mInterval = 28 * 24 * 60 * 60 * 1000;
                }

            }

        }
        if (v.equals(mYearly)) {
            //c.set(mYear, mMonth, mDay);
            //am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 365*24*60*60*1000, pi);
            mInterval = 365 * 24 * 60 * 60 * 1000;
            mFrequency = "Year";
            isOneTime = false;
        }
        //
    }

    private void addToDatabase(boolean isRepeated) {
        if (isRepeated == true) {

            SMSSchedulerPendingIntent newDatabeseEntry = mDatasource.createPendingIntents(mId, mHour, mMinutes, mSeconds, mYear, mMonth, mDay, mFrequency, mNumber, mContactdisplayName, mMessage);
        }
        if (isRepeated == false) {
            SMSSchedulerPendingIntent newDatabeseEntry = mDatasource.createPendingIntents(mId, mHour, mMinutes, mSeconds, mYear, mMonth, mDay, mFrequency, mNumber, mContactdisplayName, mMessage);
        }
    }
}

Manifest file

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

        <activity android:name=".CancelAnAlarmActivity"
            android:label="CancelAlarm"
            android:screenOrientation="landscape">
        </activity>

        <service android:name=".SendSMSAlarmService"/>
    </application>

Body:
Please define your activity in android manifest file.
Add this code to your android manifest file

<activity android:name=".SetuppageActivity"
            android:label="">
        </activity>


来源: stackexchange

问:
python sort strings with digits at the end
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

```<code>>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']
</code>```

should  put the 1234 one on the end. is there an easy way to do this?

答:
is there an easy way to do this?

No

It's perfectly unclear what the real rules are.  The "some have 3 digits and some have 4" isn't really a very precise or complete specification.  All your examples show 4 letters in front of the digits.  Is this always true?

```<code>import re
key_pat = re.compile(r"^(\D+)(\d+)$")
def key(item):
    m = key_pat.match(item)
    return m.group(1), int(m.group(2))
</code>```

That key function might do what you want.  Or it might be too complex.  Or maybe the pattern is really r"^(.*)(\d{3,4})$" or maybe the rules are even more obscure.

```<code>>>> data= ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> data.sort( key=key )
>>> data
['asdf111', 'asdf123', 'asdf124', 'asdf1234']
</code>```

ContentLicense: CC BY-SA 2.5

Body:
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']

should  put the 1234 one on the end. is there an easy way to do this?

Body:
is there an easy way to do this?

No

It's perfectly unclear what the real rules are.  The "some have 3 digits and some have 4" isn't really a very precise or complete specification.  All your examples show 4 letters in front of the digits.  Is this always true?

import re
key_pat = re.compile(r"^(\D+)(\d+)$")
def key(item):
    m = key_pat.match(item)
    return m.group(1), int(m.group(2))

That key function might do what you want.  Or it might be too complex.  Or maybe the pattern is really r"^(.*)(\d{3,4})$" or maybe the rules are even more obscure.

>>> data= ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> data.sort( key=key )
>>> data
['asdf111', 'asdf123', 'asdf124', 'asdf1234']

ContentLicense: CC BY-SA 3.0


问:
NoSuchMethodError org.bouncycastle.asn1.ASN1InputStream.readObject()Lorg/bouncycastle/asn1/ASN1Primitive
I'm getting Exception in thread "main" java.lang.NoSuchMethodError: org.bouncycastle.asn1.ASN1InputStream.readObject()Lorg/bouncycastle/asn1/ASN1Primitive;

This is my TestSign.java

```<code>    package com.test.sign;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Properties;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfAnnotation;
import com.itextpdf.text.pdf.PdfAppearance;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import com.itextpdf.text.pdf.security.MakeSignature;

public class TestSign {

    /** The resulting PDF */
    public static String ORIGINAL = "C://results/xmlworker/test3.pdf";
    /** The resulting PDF */
    public static String SIGNED1 = "results/part3/chapter12/signed_1.pdf";
    /** The resulting PDF */
    public static String SIGNED2 = "C://results/xmlworker/test3yfguhik.pdf";

    /** One of the resources. */
    public static final String RESOURCE
        = "resources/img/1t3xt.gif";

    /**
     * A properties file that is PRIVATE.
     * You should make your own properties file and adapt this line.
     */
    //public static String PATH = "c:/home/blowagie/key.properties";
    /** Some properties used when signing. */
    //public static Properties properties = new Properties();

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph("Hello World!"));
        PdfFormField field = PdfFormField.createSignature(writer);
        field.setWidget(new Rectangle(72, 732, 144, 780), PdfAnnotation.HIGHLIGHT_INVERT);
        field.setFieldName("mySig");
        field.setFlags(PdfAnnotation.FLAGS_PRINT);
        field.setPage();
        field.setMKBorderColor(BaseColor.BLACK);
        field.setMKBackgroundColor(BaseColor.WHITE);
        PdfAppearance tp = PdfAppearance.createAppearance(writer, 72, 48);
        tp.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
        tp.stroke();
        field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
        writer.addAnnotation(field);
        // step 5
        document.close();
    }

    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     * @param dest the resulting PDF
     * @throws GeneralSecurityException
     * @throws IOException
     * @throws DocumentException
     * @throws FileNotFoundException
     * @throws KeyStoreException
     * @throws Exception
     */
    public void signPdf(String src, String dest, boolean certified, boolean graphic) throws GeneralSecurityException, IOException, DocumentException {
        // private key and certificate

        KeyStore ks = KeyStore.getInstance("pkcs12");
        ks.load(new FileInputStream("C://results/xmlworker/Test.pfx"), "10111995".toCharArray());
        String alias = (String)ks.aliases().nextElement();
        PrivateKey pk = (PrivateKey)ks.getKey(alias, "10111995".toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);
        // reader and stamper
        PdfReader reader = new PdfReader(ORIGINAL);
        PdfStamper stamper = PdfStamper.createSignature(reader, new FileOutputStream(dest), '\0');
        // appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setVisibleSignature("mySig");
        appearance.setReason("It's personal.");
        appearance.setLocation("Foobar");
        if (certified)
            appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
        if (graphic) {
            appearance.setSignatureGraphic(Image.getInstance(RESOURCE));
            appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
        }
        // signature
        ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS);
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     */
    public static void main(String[] args)
        throws Exception {
        //Security.addProvider(new BouncyCastleProvider());
        TestSign signatures = new TestSign();
        signatures.createPdf(ORIGINAL);
        //signatures.signPdf(ORIGINAL, SIGNED1, false, false);
        signatures.signPdf(ORIGINAL, SIGNED2, true, false);
    }
}
</code>```

Pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>exemple</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>exemple Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.56</version>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcmail-jdk15on</artifactId>
            <version>1.56</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

I've tried all versions of bcprov-jdk15on and bcmail-jdk15on , Can you help me please , i'm stuck for like a week in this problem?

I've copied the code from this Exemple

答:
You use the wrong version of BouncyCastle for this version of iText.

I recommened that you use a combination of iText 5.5.11 and BouncyCastle 1.49, as you can see in the iText POM: https://github.com/itext/itextpdf/blob/5.5.11/itext/pom.xml

```<code>  <artifactId>itextpdf</artifactId>
  <version>5.5.11</version>

  <dependencies>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>1.49</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcpkix-jdk15on</artifactId>
      <version>1.49</version>
      <optional>true</optional>
    </dependency>
  </dependencies>
</code>```

Also make sure that you only have one version of BouncyCastle.

Body:
I'm getting Exception in thread "main" java.lang.NoSuchMethodError: org.bouncycastle.asn1.ASN1InputStream.readObject()Lorg/bouncycastle/asn1/ASN1Primitive;

This is my TestSign.java

    package com.test.sign;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Properties;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfAnnotation;
import com.itextpdf.text.pdf.PdfAppearance;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import com.itextpdf.text.pdf.security.MakeSignature;

public class TestSign {

    /** The resulting PDF */
    public static String ORIGINAL = "C://results/xmlworker/test3.pdf";
    /** The resulting PDF */
    public static String SIGNED1 = "results/part3/chapter12/signed_1.pdf";
    /** The resulting PDF */
    public static String SIGNED2 = "C://results/xmlworker/test3yfguhik.pdf";

    /** One of the resources. */
    public static final String RESOURCE
        = "resources/img/1t3xt.gif";

    /**
     * A properties file that is PRIVATE.
     * You should make your own properties file and adapt this line.
     */
    //public static String PATH = "c:/home/blowagie/key.properties";
    /** Some properties used when signing. */
    //public static Properties properties = new Properties();

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph("Hello World!"));
        PdfFormField field = PdfFormField.createSignature(writer);
        field.setWidget(new Rectangle(72, 732, 144, 780), PdfAnnotation.HIGHLIGHT_INVERT);
        field.setFieldName("mySig");
        field.setFlags(PdfAnnotation.FLAGS_PRINT);
        field.setPage();
        field.setMKBorderColor(BaseColor.BLACK);
        field.setMKBackgroundColor(BaseColor.WHITE);
        PdfAppearance tp = PdfAppearance.createAppearance(writer, 72, 48);
        tp.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
        tp.stroke();
        field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
        writer.addAnnotation(field);
        // step 5
        document.close();
    }

    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     * @param dest the resulting PDF
     * @throws GeneralSecurityException
     * @throws IOException
     * @throws DocumentException
     * @throws FileNotFoundException
     * @throws KeyStoreException
     * @throws Exception
     */
    public void signPdf(String src, String dest, boolean certified, boolean graphic) throws GeneralSecurityException, IOException, DocumentException {
        // private key and certificate

        KeyStore ks = KeyStore.getInstance("pkcs12");
        ks.load(new FileInputStream("C://results/xmlworker/Test.pfx"), "10111995".toCharArray());
        String alias = (String)ks.aliases().nextElement();
        PrivateKey pk = (PrivateKey)ks.getKey(alias, "10111995".toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);
        // reader and stamper
        PdfReader reader = new PdfReader(ORIGINAL);
        PdfStamper stamper = PdfStamper.createSignature(reader, new FileOutputStream(dest), '\0');
        // appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setVisibleSignature("mySig");
        appearance.setReason("It's personal.");
        appearance.setLocation("Foobar");
        if (certified)
            appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
        if (graphic) {
            appearance.setSignatureGraphic(Image.getInstance(RESOURCE));
            appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
        }
        // signature
        ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS);
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     */
    public static void main(String[] args)
        throws Exception {
        //Security.addProvider(new BouncyCastleProvider());
        TestSign signatures = new TestSign();
        signatures.createPdf(ORIGINAL);
        //signatures.signPdf(ORIGINAL, SIGNED1, false, false);
        signatures.signPdf(ORIGINAL, SIGNED2, true, false);
    }
}

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>exemple</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>exemple Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.56</version>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcmail-jdk15on</artifactId>
            <version>1.56</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

I've tried all versions of bcprov-jdk15on and bcmail-jdk15on , Can you help me please , i'm stuck for like a week in this problem?

I've copied the code from this Exemple

Body:
You use the wrong version of BouncyCastle for this version of iText.

I recommened that you use a combination of iText 5.5.11 and BouncyCastle 1.49, as you can see in the iText POM: https://github.com/itext/itextpdf/blob/5.5.11/itext/pom.xml

  <artifactId>itextpdf</artifactId>
  <version>5.5.11</version>

  <dependencies>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>1.49</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcpkix-jdk15on</artifactId>
      <version>1.49</version>
      <optional>true</optional>
    </dependency>
  </dependencies>

Also make sure that you only have one version of BouncyCastle.


问:
C# bot Framework Replace Luis Dialog with other NLP Service
I have created my own NLP api service using Apache OpenNlp. It will return json data (sample)
{"intent": "Feedback",  "entity": {}, "status": true}

Previously I used LUIS, So Bot framework having inbuilt reference class for processing  LUIS api call and providing us Intent and result. Based on the Intent our method will be like below

```<code>[LuisIntent("Feeback")]
    public async Task Feedback(IDialogContext context, LuisResult result)
    {
</code>```

But, If I'm not using LUIS service. What will be the best way or how can we do the Intent process and remaining Bot Process. Something like

```<code>case "Feeback"
Public async Task Feedback(IDialogContext Context) {
</code>```

in my existing bot framework project.

答:
You can follow the same paradigm.

Here's an example of using Wit.ai instead of LUIS

https://github.com/q3blend/BotBuilder-Wit.ai/

Hope that helps

Body:
I have created my own NLP api service using Apache OpenNlp. It will return json data (sample)
{"intent": "Feedback",  "entity": {}, "status": true}

Previously I used LUIS, So Bot framework having inbuilt reference class for processing  LUIS api call and providing us Intent and result. Based on the Intent our method will be like below

[LuisIntent("Feeback")]
    public async Task Feedback(IDialogContext context, LuisResult result)
    {

But, If I'm not using LUIS service. What will be the best way or how can we do the Intent process and remaining Bot Process. Something like

case "Feeback"
Public async Task Feedback(IDialogContext Context) {

in my existing bot framework project.


问:
Using threads to apply UI changes in android
I ran into a problem and need some help. I want to remove some user's files after a button click and also show the files removing progress (in progressbar) and also show some Fancy UI. First i changed the layout after button click and hide some elements and visible the others. after that i called methods to remove files. The problem is that i can not see any UI changes and system hangs until all user file removed and after that based on my scenario it go to another activity. I've google around and found that i should use thread or UI thread but exactly don't know how. Here is my code :

```<code>new Thread() {
    public void run() {
        try {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ProgressBar spinner;
                    spinner = (ProgressBar) findViewById(R.id.progressBar);
                    listview.setVisibility(View.GONE);
                    spinner.setVisibility(View.VISIBLE);
                    preresult.setVisibility(View.VISIBLE);
                    resulttxt.setVisibility(View.VISIBLE);
                    wv.setVisibility(View.VISIBLE);
                    btnClear.setVisibility(View.GONE);
                    wv.loadUrl("file:///android_asset/rocket.gif");
                    resulttxt.setText("");
                }
            });
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}.start();

Thread b = new Thread() {
    @Override
    public void run() {
        Long TotalJunk = 0L;
        for (Apps social : checkedSocial) {
            if (social.getName() == "Telegram") {
                preresult.setText("Calculating Files :");
                resulttxt.setText("Telegram");
                preresult.setText("Removing Files...");
                clearMediashistory(social.path);
                TotalJunk = TotalJunk + social.junksize;
            }
                                           }
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("FreeUp", formatSize(TotalJunk));
        //commits your edits
        editor.commit();
    }
};
b.start();
</code>```

What is wrong with my code. Is there any better method to do that?

答:
Use AsyncTask instead of Thread
https://developer.android.com/reference/android/os/AsyncTask.html

Android AsyncTask example and explanation

Body:
I ran into a problem and need some help. I want to remove some user's files after a button click and also show the files removing progress (in progressbar) and also show some Fancy UI. First i changed the layout after button click and hide some elements and visible the others. after that i called methods to remove files. The problem is that i can not see any UI changes and system hangs until all user file removed and after that based on my scenario it go to another activity. I've google around and found that i should use thread or UI thread but exactly don't know how. Here is my code :

new Thread() {
    public void run() {
        try {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ProgressBar spinner;
                    spinner = (ProgressBar) findViewById(R.id.progressBar);
                    listview.setVisibility(View.GONE);
                    spinner.setVisibility(View.VISIBLE);
                    preresult.setVisibility(View.VISIBLE);
                    resulttxt.setVisibility(View.VISIBLE);
                    wv.setVisibility(View.VISIBLE);
                    btnClear.setVisibility(View.GONE);
                    wv.loadUrl("file:///android_asset/rocket.gif");
                    resulttxt.setText("");
                }
            });
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}.start();

Thread b = new Thread() {
    @Override
    public void run() {
        Long TotalJunk = 0L;
        for (Apps social : checkedSocial) {
            if (social.getName() == "Telegram") {
                preresult.setText("Calculating Files :");
                resulttxt.setText("Telegram");
                preresult.setText("Removing Files...");
                clearMediashistory(social.path);
                TotalJunk = TotalJunk + social.junksize;
            }
                                           }
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("FreeUp", formatSize(TotalJunk));
        //commits your edits
        editor.commit();
    }
};
b.start();

What is wrong with my code. Is there any better method to do that?


问:
Gnuplot labels in column with different shape
I have a little problem. I try create gnu plot with many lines or shapes but header is in last column . Example data in file

```<code>18:40:03    0.00 K/s    3.65 K/s  0.00 %  0.25 % AA
18:40:03    0.00 K/s   69.44 K/s  0.00 %  0.05 % BB
18:40:03     0.40 K/s    0.00 K/s  0.00 %  0.03 % AA
</code>```

my gnuplot code

```<code>set xlabel "Date\nTime"
set timefmt "%H:%M:%S"
set format x "%H:%M:%S"
set xdata time
set autoscale  xy
set term png
set output "io.png"
plot 'io.log' using 0:8 title 'title', \
     '' using 0:8:10 with labels offset 0,char 1
~
</code>```

But I want create plot where  this same type (AA) have this same color or shape and different  from BB CC .....

in

答:
In order to simplify things, let's assume that the input data is stored in a file test.dat and it has following form:

```<code>1   2   AA
2   4   BB
3   6   AA
</code>```

Then there are several possibilities to distinguish the style based on the value of the label in the third column.

One could for example invoke external processing to filter out records of the "special type" (label "AA" in your case) and specify a particular style:

```<code>unset key
set xr [0:4]
set yr [0:10]

plot \
    '< gawk ''$3=="AA"'' test.dat' using 1:2 w p pt 1, \
    '' u 1:2:3 w labels offset 0,char 1 tc rgb 'red', \
    '< gawk ''$3!="AA"'' test.dat' using 1:2 w p pt 2, \
    '' u 1:2:3 w labels offset 0,char 1 tc rgb 'blue'
</code>```

This produces:

Alternatively, in order to distinguish just the style of the labels, one could filter individual cases directly in Gnuplot as:

```<code>set terminal png enhanced
set output 'fig2.png'

unset key
set xr [0:4]
set yr [0:10]

checkLabel(label)=(label eq 'AA')
filter(label, val, flag)=(((flag && checkLabel(label))||(!flag && !checkLabel(label)))?val:1/0)

plot \
    'test.dat' using 1:2 w p , \
    '' using 1:(filter(stringcolumn(3), $2, 1)):3 w labels offset 0,char 1 tc rgb 'red', \
    '' using 1:(filter(stringcolumn(3), $2, 0)):3 w labels offset 0,char 1 tc rgb 'blue'
</code>```

which yields:

Body:
I have a little problem. I try create gnu plot with many lines or shapes but header is in last column . Example data in file

18:40:03    0.00 K/s    3.65 K/s  0.00 %  0.25 % AA
18:40:03    0.00 K/s   69.44 K/s  0.00 %  0.05 % BB
18:40:03     0.40 K/s    0.00 K/s  0.00 %  0.03 % AA

my gnuplot code

set xlabel "Date\nTime"
set timefmt "%H:%M:%S"
set format x "%H:%M:%S"
set xdata time
set autoscale  xy
set term png
set output "io.png"
plot 'io.log' using 0:8 title 'title', \
     '' using 0:8:10 with labels offset 0,char 1
~

But I want create plot where  this same type (AA) have this same color or shape and different  from BB CC .....

in

Body:
In order to simplify things, let's assume that the input data is stored in a file test.dat and it has following form:

1   2   AA
2   4   BB
3   6   AA

Then there are several possibilities to distinguish the style based on the value of the label in the third column.

One could for example invoke external processing to filter out records of the "special type" (label "AA" in your case) and specify a particular style:

unset key
set xr [0:4]
set yr [0:10]

plot \
    '< gawk ''$3=="AA"'' test.dat' using 1:2 w p pt 1, \
    '' u 1:2:3 w labels offset 0,char 1 tc rgb 'red', \
    '< gawk ''$3!="AA"'' test.dat' using 1:2 w p pt 2, \
    '' u 1:2:3 w labels offset 0,char 1 tc rgb 'blue'

This produces:

Alternatively, in order to distinguish just the style of the labels, one could filter individual cases directly in Gnuplot as:

set terminal png enhanced
set output 'fig2.png'

unset key
set xr [0:4]
set yr [0:10]

checkLabel(label)=(label eq 'AA')
filter(label, val, flag)=(((flag && checkLabel(label))||(!flag && !checkLabel(label)))?val:1/0)

plot \
    'test.dat' using 1:2 w p , \
    '' using 1:(filter(stringcolumn(3), $2, 1)):3 w labels offset 0,char 1 tc rgb 'red', \
    '' using 1:(filter(stringcolumn(3), $2, 0)):3 w labels offset 0,char 1 tc rgb 'blue'

which yields:


问:
ng2-bootstrap progressbar not working
I am using the ng2-bootstrap progress bar component in a Angular 2 app built with angular-cli. As suggested by the ng2-bootstrap team I have declared and used the progress bar component as shown below:

```<code>import { AlertModule, AccordionModule, ModalModule, ProgressbarModule  } from 'ng2-bootstrap';
import { ThreedViewerComponent} from './threed-viewer/threed-viewer.component';

@NgModule({
  declarations: [
    AppComponent,
    ThreedViewerComponent,
  ],
  imports: [
    ...
    AlertModule.forRoot(),
    AccordionModule.forRoot(),
    ModalModule.forRoot(),
    ProgressbarModule.forRoot(),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  public customClass: string = 'customClass';
  public isFirstOpen: boolean = true;
}
</code>```

the following is my HTML:

```<code><progressbar [max]="max" [value]="dynamic">
    <span style="color:white; white-space:nowrap;">{{dynamic}} / {{max}}</span>
</progressbar>
</code>```

and finally my component:

```<code>@Component({
  selector: ...
  templateUrl: ...
})
export class myComponent{
  public max: number = 200;
  public showWarning: boolean;
  public dynamic: number;
  public type: string;

  ...
}
</code>```

when I serve the app, theprogress bar generates following error but all other ng2-bootstrap components work fine:

Unhandled Promise rejection: Template parse errors: Can't bind to
  'max' since it isn't a known property of 'progressbar'. ("

```<code>      <progressbar [ERROR ->][max]="max" [value]="dynamic">
        <span style="color:white; white-space:nowrap;">{{dynamic}"): ThreedViewerComponent@85:23 Can't
</code>```

bind to 'value' since it isn't a known property of 'progressbar'. ("

```<code>      <progressbar [max]="max" [ERROR ->][value]="dynamic">
        <span style="color:white; white-space:nowrap;">{{dynamic}} / {{max}}<"): ThreedViewerComponent@85:35 'progressbar' is not a known
</code>```

element:
  1. If 'progressbar' is an Angular component, then verify that it is part of this module.
  2. If 'progressbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component
  to suppress this message. ("

```<code>      [ERROR ->]<progressbar [max]="max" [value]="dynamic">
        <span style="color:white; white-space:nowrap"): ThreedViewerComponent@85:10 'progressbar' is not a known element:
</code>```

1. If 'progressbar' is an Angular component, then verify that it is part of this module.
  2. If 'progressbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component
  to suppress this message. ("
              [ERROR ->]

                  © 2017 "): ThreedViewerComponent@91:12 ; Zone:  ; Task: Promise.then ; Value: SyntaxError
  {__zone_symbol__error: Error: Template parse errors: Can't bind to
  'max' since it isn't a known property of 'progressbar'. …,
  _nativeError: ZoneAwareError, __zone_symbol__currentTask: ZoneTask, __zone_symbol__stack: "Error: Template parse errors:↵Can't bind to 'max' …ttp://localhost:4200/polyfills.bundle.js:3011:35)",
  __zone_symbol__message: "Template parse errors:↵Can't bind to 'max' since i…     © 2017 ↵"): ThreedViewerComponent@91:12"} Error:
  Template parse errors: Can't bind to 'max' since it isn't a known
  property of 'progressbar'. ("

```<code>      <progressbar [ERROR ->][max]="max" [value]="dynamic">
        <span style="color:white; white-space:nowrap;">{{dynamic}"): ThreedViewerComponent@85:23 Can't
</code>```

bind to 'value' since it isn't a known property of 'progressbar'. ("

```<code>      <progressbar [max]="max" [ERROR ->][value]="dynamic">
        <span style="color:white; white-space:nowrap;">{{dynamic}} / {{max}}<"): ThreedViewerComponent@85:35 'progressbar' is not a known
</code>```

element:
  1. If 'progressbar' is an Angular component, then verify that it is part of this module.
  2. If 'progressbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component
  to suppress this message. ("

```<code>      [ERROR ->]<progressbar [max]="max" [value]="dynamic">
        <span style="color:white; white-space:nowrap"): ThreedViewerComponent@85:10 'progressbar' is not a known element:
</code>```

1. If 'progressbar' is an Angular component, then verify that it is part of this module.
  2. If 'progressbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component
  to suppress this message. ("
              [ERROR ->]

                  © 2017 "): ThreedViewerComponent@91:12
      at SyntaxError.ZoneAwareError (http://localhost:4200/polyfills.bundle.js:3457:33)
      at SyntaxError.BaseError [as constructor] (http://localhost:4200/vendor.bundle.js:86968:16)
      at new SyntaxError (http://localhost:4200/vendor.bundle.js:10223:16)
      at TemplateParser.parse (http://localhost:4200/vendor.bundle.js:22316:19)
      at JitCompiler._compileTemplate (http://localhost:4200/vendor.bundle.js:54413:68)
      at http://localhost:4200/vendor.bundle.js:54296:62
      at Set.forEach (native)
      at JitCompiler._compileComponents (http://localhost:4200/vendor.bundle.js:54296:19)
      at createResult (http://localhost:4200/vendor.bundle.js:54178:19)
      at ZoneDelegate.webpackJsonp.807.ZoneDelegate.invoke (http://localhost:4200/polyfills.bundle.js:2799:26)
      at Zone.webpackJsonp.807.Zone.run (http://localhost:4200/polyfills.bundle.js:2591:43)
      at http://localhost:4200/polyfills.bundle.js:3178:57
      at ZoneDelegate.webpackJsonp.807.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2832:31)
      at Zone.webpackJsonp.807.Zone.runTask (http://localhost:4200/polyfills.bundle.js:2631:47)
      at drainMicroTaskQueue (http://localhost:4200/polyfills.bundle.js:3011:35)

Can you please help?

答:
Will you please change your import to this , and try again :

```<code>imports: [
    AlertModule.forRoot(),
    AccordionModule.forRoot(),
    ModalModule.forRoot(),
    ProgressbarModule.forRoot(),
    ...
  ],
</code>```

Load all bootstrap module first (AlertModule, AccordionModule, ModalModule, ProgressbarModule) and then other modules.

Title: ng2-bootstrap progressbar not working

Body:
I am using the ng2-bootstrap progress bar component in a Angular 2 app built with angular-cli. As suggested by the ng2-bootstrap team I have declared and used the progress bar component as shown below:

import { AlertModule, AccordionModule, ModalModule, ProgressbarModule  } from 'ng2-bootstrap';
import { ThreedViewerComponent} from './threed-viewer/threed-viewer.component';

@NgModule({
  declarations: [
    AppComponent,
    ThreedViewerComponent,
  ],
  imports: [
    ...
    AlertModule.forRoot(),
    AccordionModule.forRoot(),
    ModalModule.forRoot(),
    ProgressbarModule.forRoot(),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  public customClass: string = 'customClass';
  public isFirstOpen: boolean = true;
}

the following is my HTML:

<progressbar [max]="max" [value]="dynamic">
    {{dynamic}} / {{max}}
</progressbar>

and finally my component:

@Component({
  selector: ...
  templateUrl: ...
})
export class myComponent{
  public max: number = 200;
  public showWarning: boolean;
  public dynamic: number;
  public type: string;

  ...
}

when I serve the app, theprogress bar generates following error but all other ng2-bootstrap components work fine:

Unhandled Promise rejection: Template parse errors: Can't bind to
  'max' since it isn't a known property of 'progressbar'. ("

      <progressbar [ERROR ->][max]="max" [value]="dynamic">
        {{dynamic}"): ThreedViewerComponent@85:23 Can't

bind to 'value' since it isn't a known property of 'progressbar'. ("

      <progressbar [max]="max" [ERROR ->][value]="dynamic">
        {{dynamic}} / {{max}}<"): ThreedViewerComponent@85:35 'progressbar' is not a known

element:
  1. If 'progressbar' is an Angular component, then verify that it is part of this module.
  2. If 'progressbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component
  to suppress this message. ("

      [ERROR ->]<progressbar [max]="max" [value]="dynamic">
        <span style="color:white; white-space:nowrap"): ThreedViewerComponent@85:10 'progressbar' is not a known element:

1. If 'progressbar' is an Angular component, then verify that it is part of this module.
  2. If 'progressbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component
  to suppress this message. ("
              [ERROR ->]

                  © 2017 "): ThreedViewerComponent@91:12 ; Zone:  ; Task: Promise.then ; Value: SyntaxError
  {__zone_symbol__error: Error: Template parse errors: Can't bind to
  'max' since it isn't a known property of 'progressbar'. …,
  _nativeError: ZoneAwareError, __zone_symbol__currentTask: ZoneTask, __zone_symbol__stack: "Error: Template parse errors:↵Can't bind to 'max' …ttp://localhost:4200/polyfills.bundle.js:3011:35)",
  __zone_symbol__message: "Template parse errors:↵Can't bind to 'max' since i…     © 2017 ↵"): ThreedViewerComponent@91:12"} Error:
  Template parse errors: Can't bind to 'max' since it isn't a known
  property of 'progressbar'. ("

      <progressbar [ERROR ->][max]="max" [value]="dynamic">
        {{dynamic}"): ThreedViewerComponent@85:23 Can't

bind to 'value' since it isn't a known property of 'progressbar'. ("

      <progressbar [max]="max" [ERROR ->][value]="dynamic">
        {{dynamic}} / {{max}}<"): ThreedViewerComponent@85:35 'progressbar' is not a known

element:
  1. If 'progressbar' is an Angular component, then verify that it is part of this module.
  2. If 'progressbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component
  to suppress this message. ("

      [ERROR ->]<progressbar [max]="max" [value]="dynamic">
        <span style="color:white; white-space:nowrap"): ThreedViewerComponent@85:10 'progressbar' is not a known element:

1. If 'progressbar' is an Angular component, then verify that it is part of this module.
  2. If 'progressbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component
  to suppress this message. ("
              [ERROR ->]

                  © 2017 "): ThreedViewerComponent@91:12
      at SyntaxError.ZoneAwareError (http://localhost:4200/polyfills.bundle.js:3457:33)
      at SyntaxError.BaseError [as constructor] (http://localhost:4200/vendor.bundle.js:86968:16)
      at new SyntaxError (http://localhost:4200/vendor.bundle.js:10223:16)
      at TemplateParser.parse (http://localhost:4200/vendor.bundle.js:22316:19)
      at JitCompiler._compileTemplate (http://localhost:4200/vendor.bundle.js:54413:68)
      at http://localhost:4200/vendor.bundle.js:54296:62
      at Set.forEach (native)
      at JitCompiler._compileComponents (http://localhost:4200/vendor.bundle.js:54296:19)
      at createResult (http://localhost:4200/vendor.bundle.js:54178:19)
      at ZoneDelegate.webpackJsonp.807.ZoneDelegate.invoke (http://localhost:4200/polyfills.bundle.js:2799:26)
      at Zone.webpackJsonp.807.Zone.run (http://localhost:4200/polyfills.bundle.js:2591:43)
      at http://localhost:4200/polyfills.bundle.js:3178:57
      at ZoneDelegate.webpackJsonp.807.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2832:31)
      at Zone.webpackJsonp.807.Zone.runTask (http://localhost:4200/polyfills.bundle.js:2631:47)
      at drainMicroTaskQueue (http://localhost:4200/polyfills.bundle.js:3011:35)

Can you please help?

Body:
Will you please change your import to this , and try again :

imports: [
    AlertModule.forRoot(),
    AccordionModule.forRoot(),
    ModalModule.forRoot(),
    ProgressbarModule.forRoot(),
    ...
  ],

Load all bootstrap module first (AlertModule, AccordionModule, ModalModule, ProgressbarModule) and then other modules.


问:
Facebook SDK 4+ logout not working correctly
I'm using Facebook SDK 4+ and my problem is that when i use

```<code> FacebookSdk.sdkInitialize(getApplicationContext());
 LoginManager.getInstance().logOut();
</code>```

to logout from my app it's not working correct. I return to my target activity with the login button. When i press the button i get in the app again without authorization. I have installed the native Facebook app. Without this app erverything is working fine. So what i'm doing wrong or im missing something.

The Api Key where ok and they are working.

my login implementaion is like:

```<code>private ImageButton loginButton;
private LoginButton fbbtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
}

@Override
protected void onResume() {
    super.onResume();
    callbackManager= CallbackManager.Factory.create();
    fbbtn= (LoginButton)findViewById(R.id.fb_button);
    fbbtn.setReadPermissions("public_profile", "email","user_friends");
    loginButton = (ImageButton) findViewById(R.id.login_btn);
    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressDialog = new ProgressDialog(LoginActivity.this);
            progressDialog.setMessage("Loading...");
            progressDialog.show();
            fbbtn.performClick();
            fbbtn.setPressed(true);
            fbbtn.invalidate();
            fbbtn.registerCallback(callbackManager, mCallBack);
            fbbtn.setPressed(false);
            fbbtn.invalidate();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
}

private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        progressDialog.dismiss();
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        app.setUser(object);
                    }
                });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender");
        request.setParameters(parameters);
        request.executeAsync();
    }

    @Override
    public void onCancel() {
        progressDialog.dismiss();
    }

    @Override
    public void onError(FacebookException e) {
        progressDialog.dismiss();
    }
};
</code>```

答: To change user profile you need logged out from it in your FB app (or in Chrome if you are using Chrome Custom Tabs)</p>

Body:
I'm using Facebook SDK 4+ and my problem is that when i use

 FacebookSdk.sdkInitialize(getApplicationContext());
 LoginManager.getInstance().logOut();

to logout from my app it's not working correct. I return to my target activity with the login button. When i press the button i get in the app again without authorization. I have installed the native Facebook app. Without this app erverything is working fine. So what i'm doing wrong or im missing something.

The Api Key where ok and they are working.

my login implementaion is like:

private ImageButton loginButton;
private LoginButton fbbtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
}

@Override
protected void onResume() {
    super.onResume();
    callbackManager= CallbackManager.Factory.create();
    fbbtn= (LoginButton)findViewById(R.id.fb_button);
    fbbtn.setReadPermissions("public_profile", "email","user_friends");
    loginButton = (ImageButton) findViewById(R.id.login_btn);
    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressDialog = new ProgressDialog(LoginActivity.this);
            progressDialog.setMessage("Loading...");
            progressDialog.show();
            fbbtn.performClick();
            fbbtn.setPressed(true);
            fbbtn.invalidate();
            fbbtn.registerCallback(callbackManager, mCallBack);
            fbbtn.setPressed(false);
            fbbtn.invalidate();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
}

private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        progressDialog.dismiss();
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        app.setUser(object);
                    }
                });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender");
        request.setParameters(parameters);
        request.executeAsync();
    }

    @Override
    public void onCancel() {
        progressDialog.dismiss();
    }

    @Override
    public void onError(FacebookException e) {
        progressDialog.dismiss();
    }
};


问:
Using Maven ClassLoader.getSystemClassLoader().getResource() return null
My project directory structure (in Eclipse):

```<code>MyProject/
    src/main/Java
    src/main/resources
        stories
            file.story
</code>```

In Main class i have return below line which return null while excuting main class through MAVEN

```<code>String folderName = "stories";
URL appURL = ClassLoader.getSystemClassLoader().getResource(folderName);
</code>```

While executing through maven, appURL returns NULL.

By reading one post on Stackoverflow i got to kanow that, i am running the webapp on server but there is no reference to the resources on the server so we need to add some code in POM.xml file. i have added below code in POM.xml file but still its not working :(

```<code><resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>stories</include>
            </includes>
        </resource>

    </resources>
</code>```

Looking for help.

答:
There are two ways you can achieve this

Approach 1)

If it is not inside the main method
URL url = getClass().getClassLoader().getResource("someresource.xxx");
If it is inside main you need to create object of your class and then call getClass on it .

Approach 2)

By extending URLStreamHandler

```<code>import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class YourClass extends URLStreamHandler {
    /** The classloader to find resources from. */
    private final ClassLoader classLoader;

    public YourClass() {
        this.classLoader = getClass().getClassLoader();
    }

    public YourClass(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        final URL resourceUrl = classLoader.getResource(u.getPath());
        return resourceUrl.openConnection();
    }
}
</code>```

Ref:URL to load resources from the classpath in Java

Body:
My project directory structure (in Eclipse):

MyProject/
    src/main/Java
    src/main/resources
        stories
            file.story

In Main class i have return below line which return null while excuting main class through MAVEN

String folderName = "stories";
URL appURL = ClassLoader.getSystemClassLoader().getResource(folderName);

While executing through maven, appURL returns NULL.

By reading one post on Stackoverflow i got to kanow that, i am running the webapp on server but there is no reference to the resources on the server so we need to add some code in POM.xml file. i have added below code in POM.xml file but still its not working :(

<resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>stories</include>
            </includes>
        </resource>

    </resources>

Looking for help.

Body:
There are two ways you can achieve this

Approach 1)

If it is not inside the main method
URL url = getClass().getClassLoader().getResource("someresource.xxx");
If it is inside main you need to create object of your class and then call getClass on it .

Approach 2)

By extending URLStreamHandler

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class YourClass extends URLStreamHandler {
    /** The classloader to find resources from. */
    private final ClassLoader classLoader;

    public YourClass() {
        this.classLoader = getClass().getClassLoader();
    }

    public YourClass(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        final URL resourceUrl = classLoader.getResource(u.getPath());
        return resourceUrl.openConnection();
    }
}

Ref:URL to load resources from the classpath in Java


问:
Who provides the Audio and Video Codec support in case of HTML5 player?
When a video is played on a browser, which supports HTML5, who is actually providing the codec support? Is it the browser or the OS? And how can I find the list of codecs supported?</p>

答:
Regarding to audio playing, if you use <audio> tag, it means the browser uses embedded codecs. List of supported codecs you can see on Media formats supported by the HTML audio and video elements

If you want to use other codecs you should use the <embed> or <object> tags


问:
Docker and local /etc/hosts records
What is best practice to use docker containers with my hosts file?

I have these records:

```<code>test.devel IP of my machine
test2.devel IP of my machine
...
</code>```

How to do to pass request of test.devel to one docker, and test2.devel to another?

Thanks.

答: Assign Docker ip addresses to your records.</p>

Title: Docker and local /etc/hosts records

Body:
What is best practice to use docker containers with my hosts file?

I have these records:

test.devel IP of my machine
test2.devel IP of my machine
...

How to do to pass request of test.devel to one docker, and test2.devel to another?

Thanks.


问:
revert back the branch
I have a master branch and a feature branch.

I have some commits in feature branch, and I cherry-picked them to master branch.

So, now my master branch contains those commits already. I noticed then I shouldn't do those cherry-picks.

Now, how can I revert my master branch back to the status before cherry-pick?

答:
If you didn't push the bad changes to remote yet:

```<code>git checkout master
git reset --hard <commit_before_bad_changes>
</code>```

If you did push the bad changes to remote already:

```<code>git checkout master
git revert <bad_commit_1>
git revert <bad_commit_2>
git revert <bad_commit_3>
</code>```

Revert will not remove the bad commits from the history but create new commits which remove the content of the bad commits.

Title: revert back the branch

Body:
If you didn't push the bad changes to remote yet:

git checkout master
git reset --hard <commit_before_bad_changes>

If you did push the bad changes to remote already:

git checkout master
git revert <bad_commit_1>
git revert <bad_commit_2>
git revert <bad_commit_3>

Revert will not remove the bad commits from the history but create new commits which remove the content of the bad commits.


问:
How to show a thank you message after someone submits a form in Angular?
I have made this snippet in Angular: http://plnkr.co/edit/kQz0fiaXLv7T37N8fzJU?p=preview

```<code>$scope.loadEditForm = function () {
    $scope.checkItem = "yes";
    $modal.open({
        templateUrl: 'modal.html',
        controller: 'modalController',
        scope: $scope
    })
    .result.then(function() {
        alert('closed');
    });
};
</code>```

As you can see, I am prompting a "closed" pop-up, but I want to make this much more stylish and show a message IN the modal, instead of having to show an ugly pop-up screen that says "closed".

How could I do this in Angular? Is there some nifty trick?

答:
You can use a function defined in your $scope to update the value of the modal's state and then close it using a setTimeout.

You can check my updated Plunker.

ModalController

```<code>angular.module('myModule').controller('modalController', function($scope) {
    $scope.state = 'open';

    $scope.closeModal = shouldDismiss => {
      $scope.state = shouldDismiss ? 'canceled' : 'closed';

      setTimeout(() => {
        if (shouldDismiss) {
          return $scope.$dismiss();
        }

        $scope.$close();
      }, 500);
    };
});
</code>```

You can change the duration set in the setTimeout to display the modal longer.

Main Controller

```<code>angular.module('myModule').controller('myController', ["$rootScope", "$scope", "$filter", "$modal", function ($rootScope, $scope, $filter, $modal) {

    $scope.checkItem = "";

    $scope.loadEditForm = function () {
        $scope.checkItem = "yes";
        $modal.open({
            templateUrl: 'modal.html',
            controller: 'modalController',
            scope: $scope
        }).result.then();
    };
}]);
</code>```

Adding the .result.then() triggers the animation when the modal is closing.

Body:
I have made this snippet in Angular: http://plnkr.co/edit/kQz0fiaXLv7T37N8fzJU?p=preview

$scope.loadEditForm = function () {
    $scope.checkItem = "yes";
    $modal.open({
        templateUrl: 'modal.html',
        controller: 'modalController',
        scope: $scope
    })
    .result.then(function() {
        alert('closed');
    });
};

As you can see, I am prompting a "closed" pop-up, but I want to make this much more stylish and show a message IN the modal, instead of having to show an ugly pop-up screen that says "closed".

How could I do this in Angular? Is there some nifty trick?

Body:
You can use a function defined in your $scope to update the value of the modal's state and then close it using a setTimeout.

You can check my updated Plunker.

ModalController

angular.module('myModule').controller('modalController', function($scope) {
    $scope.state = 'open';

    $scope.closeModal = shouldDismiss => {
      $scope.state = shouldDismiss ? 'canceled' : 'closed';

      setTimeout(() => {
        if (shouldDismiss) {
          return $scope.$dismiss();
        }

        $scope.$close();
      }, 500);
    };
});

You can change the duration set in the setTimeout to display the modal longer.

Main Controller

angular.module('myModule').controller('myController', ["$rootScope", "$scope", "$filter", "$modal", function ($rootScope, $scope, $filter, $modal) {

    $scope.checkItem = "";

    $scope.loadEditForm = function () {
        $scope.checkItem = "yes";
        $modal.open({
            templateUrl: 'modal.html',
            controller: 'modalController',
            scope: $scope
        }).result.then();
    };
}]);

Adding the .result.then() triggers the animation when the modal is closing.