问:
Text alignment without using table in html and css
I'm trying to learn HTML and CSS and using the old-school approach by creating a login page with three input controls (two text and one button). However, I'm using

 for the alignment issues of textboxes. But I've read somewhere that using tables is not considered a good approach. This is what I'm doing:

Home.html

```<code><div>
    <table>
        <thead>
            <tr><th><span>Login Page</span></th></tr>
        </thead>
        <tbody>
            <tr>
            <th><label>Username:</label></th>
            <td><input type="text" value="" /></td>
            </tr>
            <tr>
                <th><label>Password:</label></th>
                <td><input type="text" value="" /></td>
            </tr>
            <tr>
                <td><input type="button" value="Submit" /></td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

However, I'm using some beginner stuff of CSS to align input controls without using tables and this is what I'm trying:

Home.html

```<code><div class="box">
    <span>Login Page</span>
    <br />
    <span>
        <label>Username:</label>
        <input type="text" value="" />
        <br />
        <label>Password:</label>
        <input type="text" value="" />
        <br />
        <input type="button" value="Submit" />
    </span>
</div>
</code>```

style.css

```<code>.box {
   margin: 10px 10px 10px 10px;
   border: dotted 2px #fff;
   width: 500px;
}

.box span:first-child {
    border: dotted 1px;
    margin-left: 30%;
    font-family: Arial, sans-serif;
    width: 50%;
}

.box span label:nth-of-type(odd)
{
    color:blue;
    font-family: Arial, sans-serif;
}

.box span label:nth-of-type(even)
{
    color: red;
    font-family: Arial, sans-serif;
    display: inline-block;
}
</code>```

My concern is using css, I'm able to align the input controls but I have to use multiple break tags (
) and also extra code for alignment which is easier by simply using the
 tag. Can someone suggest me the standard approach and either I'm on the right path or not?

答: Tables are not a good approach for many reasons, but tables ARE ideal for forms of the type you are trying to create. </p>

Body:
I'm trying to learn HTML and CSS and using the old-school approach by creating a login page with three input controls (two text and one button). However, I'm using

 for the alignment issues of textboxes. But I've read somewhere that using tables is not considered a good approach. This is what I'm doing:

Home.html

Login Page

            Username:
            <input type="text" value="" />

                Password:
                <input type="text" value="" />

                <input type="button" value="Submit" />

However, I'm using some beginner stuff of CSS to align input controls without using tables and this is what I'm trying:

Home.html

    Login Page

        Username:
        <input type="text" value="" />

        Password:
        <input type="text" value="" />

        <input type="button" value="Submit" />

style.css

.box {
   margin: 10px 10px 10px 10px;
   border: dotted 2px #fff;
   width: 500px;
}

.box span:first-child {
    border: dotted 1px;
    margin-left: 30%;
    font-family: Arial, sans-serif;
    width: 50%;
}

.box span label:nth-of-type(odd)
{
    color:blue;
    font-family: Arial, sans-serif;
}

.box span label:nth-of-type(even)
{
    color: red;
    font-family: Arial, sans-serif;
    display: inline-block;
}

My concern is using css, I'm able to align the input controls but I have to use multiple break tags (
) and also extra code for alignment which is easier by simply using the
 tag. Can someone suggest me the standard approach and either I'm on the right path or not?


来源: stackexchange

问:
Div content to be stretched equal to table width

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

My First Bootstrap Page

Resize this responsive page to see the effect!

Last Payment

                                                View All

                                            Property/ Agreement ID
                                            Property/ Agreement Name
                                            Project ID
                                            Project Name
                                            Check Date
                                            Check Amount
                                            Invoice

```

How to stretch the div tag to be equal to table's width. Please see the screenshot. Currently there is white space showing at the end

Please check the updated code. I see it showing the white space at the end of header lable when we move the horizontal bar. Please test this code on w3c school site.

答:
Try using width:100%; display:block;

This will help you to make your div 100%

ContentLicense: CC BY-SA 3.0

Body:
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

My First Bootstrap Page

Resize this responsive page to see the effect!

Last Payment

                                                View All

                                            Property/ Agreement ID
                                            Property/ Agreement Name
                                            Project ID
                                            Project Name
                                            Check Date
                                            Check Amount
                                            Invoice

How to stretch the div tag to be equal to table's width. Please see the screenshot. Currently there is white space showing at the end

Please check the updated code. I see it showing the white space at the end of header lable when we move the horizontal bar. Please test this code on w3c school site.


问:
How to import TwitterUtils library from scala
I am using DSE 4.8. I am trying to import twitterutils library by using:

```<code>import org.apache.spark.streaming.twitter.TwitterUtils
</code>```

It's showing error:

object twitter is not a member of package org.apache.spark.streaming.

Please let me know how to add package so that I can stream twitter data

答:
I think you have missed to add dependency spark-streaming-twitter.

```<code><!-- https://mvnrepository.com/artifact/org.apache.spark/spark-streaming-twitter_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming-twitter_2.10</artifactId>
    <version>1.6.1</version>
</dependency>
</code>```

You can alternatively use --package option to let spark auto download the jar for you if you have internet connection.

```<code>spark-shell --packages org.apache.bahir:spark-streaming-twitter_2.11:2.1.0
</code>```

** Change version of the library as per your spark(scala) version

Body:
I am using DSE 4.8. I am trying to import twitterutils library by using:

import org.apache.spark.streaming.twitter.TwitterUtils

It's showing error:

object twitter is not a member of package org.apache.spark.streaming.

Please let me know how to add package so that I can stream twitter data

Body:
I think you have missed to add dependency spark-streaming-twitter.

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-streaming-twitter_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming-twitter_2.10</artifactId>
    <version>1.6.1</version>
</dependency>

You can alternatively use --package option to let spark auto download the jar for you if you have internet connection.

spark-shell --packages org.apache.bahir:spark-streaming-twitter_2.11:2.1.0

** Change version of the library as per your spark(scala) version


问:
How to Initialize adapter in RecycleVIew?
Before this i am using ListView and it is working fine. But i want to set the ListView in Horizontal. so i came to know that RecycleView is more reliable then listview.

am trying to work with Recycle View and getting error like

```<code> No adapter attached; skipping layout
</code>```

It means that the problem is in my adapter class i don't know what the code is required in my adapter class i just tried this way.

main.java

```<code>public class DynamicButon extends Fragment {
    public DynamicButon(){};
    JSONObject jsonobject;
    JSONArray ownerObj;
     private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;

    ListViewAdapterDynamic mAdapter;
    ArrayList<HashMap<String, String>> arraylist;
    String uid = "0";
    SessionManager session;
    private static String url_visitor = "";
    JSONParser jParser = new JSONParser();
    ArrayList<String> itemwod = new ArrayList<String>();

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_dynamic_buton, container, false);
        getActivity().setTitle("Complete Order");
        // listview = (ListView) view.findViewById(R.id.lvvisit);

        session = new SessionManager(getActivity());
        HashMap<String, String> user = session.getUserDetails();
        uid = user.get(SessionManager.KEY_ID);
        new DownloadJSON().execute();
        return view;
    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          //  avi.show();
        }

        @Override
        protected Void doInBackground(Void... args) {
            try {
                arraylist = new ArrayList<HashMap<String, String>>();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", uid));
                JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);

                int success1 = Integer.parseInt(json.getString("success4"));
                Log.d("success4", json.toString());

                if (success1 == 0) {
                    Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
                }
                if (success1 == 1) {
                    ownerObj = json.getJSONArray("cy");

                    for (int i = 0; i < ownerObj.length(); i++) {
                        jsonobject = ownerObj.getJSONObject(i);

                        item.add(jsonobject.getString("company"));
                    }
                }
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

 mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.mylist);
        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new ListViewAdapterDynamic(getActivity(), itemwod);
        mRecyclerView.setAdapter(mAdapter);
        }
    }
}
</code>```

ListViewAdapter

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by sachin on 3/15/2017.
 */

public class ListViewAdapterDynamic extends BaseAdapter {
    Context cntx;

    View view;

    ArrayList<String> itemwod = new ArrayList<String>();

    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapterDynamic(Context context,
                                        ArrayList<String> o_parties
    ) {
        // TODO Auto-generated constructor stub
        cntx = context;
        itemwod = o_parties;
    }

    @Override
    public int getCount() {
        return itemwod.size();
    }

    @Override
    public Object getItem(int position) {
        return itemwod.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressWarnings("deprecation")
    public View getView(final int position, View convertView, ViewGroup parent) {

        Button cancel;

        inflater = (LayoutInflater) cntx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LayoutInflater inflater = LayoutInflater.from(cntx);

        convertView = inflater.inflate(R.layout.raw_dynamic, parent,
                false);

         cancel=(Button)convertView.findViewById(R.id.btn) ;
        cancel.setText(itemwod.get(position));
        return convertView;
    }

}
</code>```

Like this way i try but not working in ListViewAdapterDynamic i tried to implement

```<code>  RecyclerView.Adapter<MyViewHolder>
</code>```

then getting errors that's why i just kept extends Baseadapter what i did i listview.

答:
Here you can find tutorial on how to set listview horizontally using recycler view

https://www.codeproject.com/Articles/1152595/Android-Horizontal-ListView-Tutorial

listview doesn't support horizontal scrolling in linear layout

Body:
Before this i am using ListView and it is working fine. But i want to set the ListView in Horizontal. so i came to know that RecycleView is more reliable then listview.

am trying to work with Recycle View and getting error like

 No adapter attached; skipping layout

It means that the problem is in my adapter class i don't know what the code is required in my adapter class i just tried this way.

main.java

public class DynamicButon extends Fragment {
    public DynamicButon(){};
    JSONObject jsonobject;
    JSONArray ownerObj;
     private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;

    ListViewAdapterDynamic mAdapter;
    ArrayList<HashMap<String, String>> arraylist;
    String uid = "0";
    SessionManager session;
    private static String url_visitor = "";
    JSONParser jParser = new JSONParser();
    ArrayList<String> itemwod = new ArrayList<String>();

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_dynamic_buton, container, false);
        getActivity().setTitle("Complete Order");
        // listview = (ListView) view.findViewById(R.id.lvvisit);

        session = new SessionManager(getActivity());
        HashMap<String, String> user = session.getUserDetails();
        uid = user.get(SessionManager.KEY_ID);
        new DownloadJSON().execute();
        return view;
    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          //  avi.show();
        }

        @Override
        protected Void doInBackground(Void... args) {
            try {
                arraylist = new ArrayList<HashMap<String, String>>();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", uid));
                JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);

                int success1 = Integer.parseInt(json.getString("success4"));
                Log.d("success4", json.toString());

                if (success1 == 0) {
                    Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
                }
                if (success1 == 1) {
                    ownerObj = json.getJSONArray("cy");

                    for (int i = 0; i < ownerObj.length(); i++) {
                        jsonobject = ownerObj.getJSONObject(i);

                        item.add(jsonobject.getString("company"));
                    }
                }
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

 mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.mylist);
        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new ListViewAdapterDynamic(getActivity(), itemwod);
        mRecyclerView.setAdapter(mAdapter);
        }
    }
}

ListViewAdapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by sachin on 3/15/2017.
 */

public class ListViewAdapterDynamic extends BaseAdapter {
    Context cntx;

    View view;

    ArrayList<String> itemwod = new ArrayList<String>();

    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapterDynamic(Context context,
                                        ArrayList<String> o_parties
    ) {
        // TODO Auto-generated constructor stub
        cntx = context;
        itemwod = o_parties;
    }

    @Override
    public int getCount() {
        return itemwod.size();
    }

    @Override
    public Object getItem(int position) {
        return itemwod.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressWarnings("deprecation")
    public View getView(final int position, View convertView, ViewGroup parent) {

        Button cancel;

        inflater = (LayoutInflater) cntx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LayoutInflater inflater = LayoutInflater.from(cntx);

        convertView = inflater.inflate(R.layout.raw_dynamic, parent,
                false);

         cancel=(Button)convertView.findViewById(R.id.btn) ;
        cancel.setText(itemwod.get(position));
        return convertView;
    }

}

Like this way i try but not working in ListViewAdapterDynamic i tried to implement

  RecyclerView.Adapter<MyViewHolder>

then getting errors that's why i just kept extends Baseadapter what i did i listview.


问:
Matlab: delete rows based on a sequence of number ine one column
I have a matrix with 2 columns. I would like to delete rows based on a sequence of numbers in column 2.
For example:

```<code>Data = [1 2
        3 4
        5 4
        6 2
        7 0
        8 2]
</code>```

then delete rows if sequence in column 2 is 4 4 2.
so I would end up with:

```<code>Data = [1 2
        7 0
        8 2]
</code>```

答:
Let's add some data to Data, to show this on two [4 4 2] sequences:

```<code>Data =

     1     2
     3     4
     5     4
     6     2
     7     0
     8     2
     9     2
     7     4
     1     4
     0     2
     4     0
     3     2
</code>```

Now, this should do the job and delete the rows that include the sequence [4 4 2] in the second column:

```<code>Seq=[4 4 2];       % sequence to delete rows according to
Data(bsxfun(@plus,findstr(Data(:,2)',Seq)',(0:length(Seq)-1)),:)=[]

Data =

     1     2
     7     0
     8     2
     9     2
     4     0
     3     2
</code>```

Body:
I have a matrix with 2 columns. I would like to delete rows based on a sequence of numbers in column 2.
For example:

Data = [1 2
        3 4
        5 4
        6 2
        7 0
        8 2]

then delete rows if sequence in column 2 is 4 4 2.
so I would end up with:

Data = [1 2
        7 0
        8 2]

Body:
Let's add some data to Data, to show this on two [4 4 2] sequences:

Data =

     1     2
     3     4
     5     4
     6     2
     7     0
     8     2
     9     2
     7     4
     1     4
     0     2
     4     0
     3     2

Now, this should do the job and delete the rows that include the sequence [4 4 2] in the second column:

Seq=[4 4 2];       % sequence to delete rows according to
Data(bsxfun(@plus,findstr(Data(:,2)',Seq)',(0:length(Seq)-1)),:)=[]

Data =

     1     2
     7     0
     8     2
     9     2
     4     0
     3     2


问:
Asp.net Request.Browser.Crawler - Dynamic Crawler List?
I learned Why Request.Browser.Crawler is Always False in C# (http://www.digcode.com/default.aspx?page=ed51cde3-d979-4daf-afae-fa6192562ea9&article=bc3a7a4f-f53e-4f88-8e9c-c9337f6c05a0).

Does anyone uses some method to dynamically update the Crawler's list, so Request.Browser.Crawler will be really useful?

答:
You could check (regex) against Request.UserAgent.

Peter Bromberg wrote a nice article about writing an ASP.NET Request Logger and Crawler Killer in ASP.NET.

Here is the method he uses in his Logger class:

```<code>public static bool IsCrawler(HttpRequest request)
{
   // set next line to "bool isCrawler = false; to use this to deny certain bots
   bool isCrawler = request.Browser.Crawler;
   // Microsoft doesn't properly detect several crawlers
   if (!isCrawler)
   {
       // put any additional known crawlers in the Regex below
       // you can also use this list to deny certain bots instead, if desired:
       // just set bool isCrawler = false; for first line in method
       // and only have the ones you want to deny in the following Regex list
       Regex regEx = new Regex("Slurp|slurp|ask|Ask|Teoma|teoma");
       isCrawler = regEx.Match(request.UserAgent).Success;
   }
   return isCrawler;
}
</code>```

OwnerDisplayName: Click Ok

ContentLicense: CC BY-SA 2.5

Body:
You could check (regex) against Request.UserAgent.

Peter Bromberg wrote a nice article about writing an ASP.NET Request Logger and Crawler Killer in ASP.NET.

Here is the method he uses in his Logger class:

public static bool IsCrawler(HttpRequest request)
{
   // set next line to "bool isCrawler = false; to use this to deny certain bots
   bool isCrawler = request.Browser.Crawler;
   // Microsoft doesn't properly detect several crawlers
   if (!isCrawler)
   {
       // put any additional known crawlers in the Regex below
       // you can also use this list to deny certain bots instead, if desired:
       // just set bool isCrawler = false; for first line in method
       // and only have the ones you want to deny in the following Regex list
       Regex regEx = new Regex("Slurp|slurp|ask|Ask|Teoma|teoma");
       isCrawler = regEx.Match(request.UserAgent).Success;
   }
   return isCrawler;
}

OwnerDisplayName: splattne


问:
Twitter4j crashed when share tweet
I want to post tweet to Twitter but the app crashed upon click the twitter button.
My Twitter version is twitter4j-core-3.0.5.jar. Do I have to change settings in manifest?

I am getting illegalStateException.

```<code>public void onShareTwitter(View v) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
      .setOAuthConsumerKey(CONSUMER_KEY)
      .setOAuthConsumerSecret(CONSUMER_SECRET)
      .setOAuthAccessToken(ACCESS_TOKEN)
      .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    Status status = null;
    try {
        status = twitter.updateStatus("Hello");
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
}
</code>```

ERROR:

```<code>08-24 21:28:14.638: E/AndroidRuntime(11030): FATAL EXCEPTION: main
08-24 21:28:14.638: E/AndroidRuntime(11030): java.lang.IllegalStateException: Could not execute method of the activity
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.view.View$1.onClick(View.java:3724)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.view.View.performClick(View.java:4261)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.view.View$PerformClick.run(View.java:17356)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.os.Handler.handleCallback(Handler.java:615)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.os.Looper.loop(Looper.java:137)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.app.ActivityThread.main(ActivityThread.java:4921)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.lang.reflect.Method.invokeNative(Native Method)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.lang.reflect.Method.invoke(Method.java:511)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at dalvik.system.NativeStart.main(Native Method)
08-24 21:28:14.638: E/AndroidRuntime(11030): Caused by: java.lang.reflect.InvocationTargetException
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.lang.reflect.Method.invokeNative(Native Method)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.lang.reflect.Method.invoke(Method.java:511)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.view.View$1.onClick(View.java:3719)
08-24 21:28:14.638: E/AndroidRuntime(11030):    ... 11 more
08-24 21:28:14.638: E/AndroidRuntime(11030): Caused by: android.os.NetworkOnMainThreadException
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:281)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:135)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:98)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.TwitterImpl.post(TwitterImpl.java:1965)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:264)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at com.dante.sphar.PhotoPreviewActivity.onShareTwitter(PhotoPreviewActivity.java:228)
08-24 21:28:14.638: E/AndroidRuntime(11030):    ... 14 more
</code>```

Updated error after changing on asynctask

```<code>08-24 21:48:56.223: W/System.err(12740): No authentication challenges found
</code>```

08-24 21:48:56.223: W/System.err(12740): Relevant discussions can be found on the Internet at:
08-24 21:48:56.223: W/System.err(12740):    http://www.google.co.jp/search?q=b2b52c28 or
08-24 21:48:56.223: W/System.err(12740):    http://www.google.co.jp/search?q=1206f231
08-24 21:48:56.223: W/System.err(12740): TwitterException{exceptionCode=[b2b52c28-1206f231 4ef6906d-2ed74fb5], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.5}
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:177)
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:98)
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.TwitterImpl.post(TwitterImpl.java:1965)
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:264)
08-24 21:48:56.228: W/System.err(12740):    at com.dante.sphar.PhotoPreviewActivity.postToTwitter(PhotoPreviewActivity.java:247)
08-24 21:48:56.228: W/System.err(12740):    at com.dante.sphar.PhotoPreviewActivity.access$1(PhotoPreviewActivity.java:236)
08-24 21:48:56.228: W/System.err(12740):    at com.dante.sphar.PhotoPreviewActivity$1.run(PhotoPreviewActivity.java:224)
08-24 21:48:56.228: W/System.err(12740):    at java.lang.Thread.run(Thread.java:856)
08-24 21:48:56.228: W/System.err(12740): Caused by: java.io.IOException: No authentication challenges found
08-24 21:48:56.228: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.getAuthorizationCredentials(HttpURLConnectionImpl.java:427)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:407)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:356)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:292)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:486)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:134)
08-24 21:48:56.233: W/System.err(12740):    at twitter4j.internal.http.HttpResponseImpl.(HttpResponseImpl.java:34)
08-24 21:48:56.233: W/System.err(12740):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:141)

答:
Try the following by putting the status calling function in async task. Like the following:

```<code>public ProgressDialog pdProgressCircleSend;

    public class UseTweeter extends AsyncTask<String,String,String>{
    String msg;

    @Override
    protected void onPreExecute() {
        pdProgressCircleSend=new ProgressDialog(getActivity());
        pdProgressCircleSend.setMessage(Constants.POSTING_TWEET);
        pdProgressCircleSend.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        onShareTwitter();
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        if(pdProgressCircleSend!=null && pdProgressCircleSend.isShowing()) {
            pdProgressCircleSend.dismiss();
        }
        Toast.makeText(getContext(), "Tweeted Successfully", Toast.LENGTH_SHORT).show();
    }
}
public void onShareTwitter(View v) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
  .setOAuthConsumerKey(CONSUMER_KEY)
  .setOAuthConsumerSecret(CONSUMER_SECRET)
  .setOAuthAccessToken(ACCESS_TOKEN)
  .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
Status status = null;
try {
    status = twitter.updateStatus("Hello");
} catch (TwitterException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
</code>```

}

Title: Twitter4j crashed when share tweet

Body:
I want to post tweet to Twitter but the app crashed upon click the twitter button.
My Twitter version is twitter4j-core-3.0.5.jar. Do I have to change settings in manifest?

I am getting illegalStateException.

public void onShareTwitter(View v) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
      .setOAuthConsumerKey(CONSUMER_KEY)
      .setOAuthConsumerSecret(CONSUMER_SECRET)
      .setOAuthAccessToken(ACCESS_TOKEN)
      .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    Status status = null;
    try {
        status = twitter.updateStatus("Hello");
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
}

ERROR:

08-24 21:28:14.638: E/AndroidRuntime(11030): FATAL EXCEPTION: main
08-24 21:28:14.638: E/AndroidRuntime(11030): java.lang.IllegalStateException: Could not execute method of the activity
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.view.View$1.onClick(View.java:3724)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.view.View.performClick(View.java:4261)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.view.View$PerformClick.run(View.java:17356)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.os.Handler.handleCallback(Handler.java:615)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.os.Looper.loop(Looper.java:137)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.app.ActivityThread.main(ActivityThread.java:4921)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.lang.reflect.Method.invokeNative(Native Method)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.lang.reflect.Method.invoke(Method.java:511)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at dalvik.system.NativeStart.main(Native Method)
08-24 21:28:14.638: E/AndroidRuntime(11030): Caused by: java.lang.reflect.InvocationTargetException
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.lang.reflect.Method.invokeNative(Native Method)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.lang.reflect.Method.invoke(Method.java:511)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.view.View$1.onClick(View.java:3719)
08-24 21:28:14.638: E/AndroidRuntime(11030):    ... 11 more
08-24 21:28:14.638: E/AndroidRuntime(11030): Caused by: android.os.NetworkOnMainThreadException
08-24 21:28:14.638: E/AndroidRuntime(11030):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at libcore.net.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:281)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:135)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:98)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.TwitterImpl.post(TwitterImpl.java:1965)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:264)
08-24 21:28:14.638: E/AndroidRuntime(11030):    at com.dante.sphar.PhotoPreviewActivity.onShareTwitter(PhotoPreviewActivity.java:228)
08-24 21:28:14.638: E/AndroidRuntime(11030):    ... 14 more

Updated error after changing on asynctask

08-24 21:48:56.223: W/System.err(12740): No authentication challenges found

08-24 21:48:56.223: W/System.err(12740): Relevant discussions can be found on the Internet at:
08-24 21:48:56.223: W/System.err(12740):    http://www.google.co.jp/search?q=b2b52c28 or
08-24 21:48:56.223: W/System.err(12740):    http://www.google.co.jp/search?q=1206f231
08-24 21:48:56.223: W/System.err(12740): TwitterException{exceptionCode=[b2b52c28-1206f231 4ef6906d-2ed74fb5], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.5}
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:177)
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:98)
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.TwitterImpl.post(TwitterImpl.java:1965)
08-24 21:48:56.228: W/System.err(12740):    at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:264)
08-24 21:48:56.228: W/System.err(12740):    at com.dante.sphar.PhotoPreviewActivity.postToTwitter(PhotoPreviewActivity.java:247)
08-24 21:48:56.228: W/System.err(12740):    at com.dante.sphar.PhotoPreviewActivity.access$1(PhotoPreviewActivity.java:236)
08-24 21:48:56.228: W/System.err(12740):    at com.dante.sphar.PhotoPreviewActivity$1.run(PhotoPreviewActivity.java:224)
08-24 21:48:56.228: W/System.err(12740):    at java.lang.Thread.run(Thread.java:856)
08-24 21:48:56.228: W/System.err(12740): Caused by: java.io.IOException: No authentication challenges found
08-24 21:48:56.228: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.getAuthorizationCredentials(HttpURLConnectionImpl.java:427)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:407)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:356)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:292)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:486)
08-24 21:48:56.233: W/System.err(12740):    at libcore.net.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:134)
08-24 21:48:56.233: W/System.err(12740):    at twitter4j.internal.http.HttpResponseImpl.(HttpResponseImpl.java:34)
08-24 21:48:56.233: W/System.err(12740):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:141)

Body:
Try the following by putting the status calling function in async task. Like the following:

public ProgressDialog pdProgressCircleSend;

    public class UseTweeter extends AsyncTask<String,String,String>{
    String msg;

    @Override
    protected void onPreExecute() {
        pdProgressCircleSend=new ProgressDialog(getActivity());
        pdProgressCircleSend.setMessage(Constants.POSTING_TWEET);
        pdProgressCircleSend.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        onShareTwitter();
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        if(pdProgressCircleSend!=null && pdProgressCircleSend.isShowing()) {
            pdProgressCircleSend.dismiss();
        }
        Toast.makeText(getContext(), "Tweeted Successfully", Toast.LENGTH_SHORT).show();
    }
}
public void onShareTwitter(View v) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
  .setOAuthConsumerKey(CONSUMER_KEY)
  .setOAuthConsumerSecret(CONSUMER_SECRET)
  .setOAuthAccessToken(ACCESS_TOKEN)
  .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
Status status = null;
try {
    status = twitter.updateStatus("Hello");
} catch (TwitterException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}


问:
Oauth2 Access Token Security Issue + angular 2
I am storing access token coming from google oauth2 in local storage. Now, the issue is, this is a security issue. Another person can copy the local storage values from my browser and enter the url to access my account. How can we solve this as access token is generally stored in local or session storage only. We can give a logout after say 60 min, like this:

```<code>this.expiresTimerId = setTimeout(() => {
            console.log('Session has expired');
            this.doLogout(440);
        }, 3600);
</code>```

But, the vulnerability exists for 60 min, which may cause security breach. How to avoid this??

答:
I don't know about any simple way of securing an access token against "someone else comes to my computer and misuses my open session" attacks (access tokens use to be bound to client IP address).

You can improve the situation by using sessionStorage instead of the localStorage - it drops its values when a browser tab is closed.

To prevent an attacker from doing any harm, all operations performing data changes or displaying sensitive data would have to be re-authenticated in a similar way as online banking systems use to do it.

Body:
I am storing access token coming from google oauth2 in local storage. Now, the issue is, this is a security issue. Another person can copy the local storage values from my browser and enter the url to access my account. How can we solve this as access token is generally stored in local or session storage only. We can give a logout after say 60 min, like this:

this.expiresTimerId = setTimeout(() => {
            console.log('Session has expired');
            this.doLogout(440);
        }, 3600);

But, the vulnerability exists for 60 min, which may cause security breach. How to avoid this??


问:
Laravel custom error page if authorization fails
I am trying to show a custom 403 file in laravel when authorization fails in my edit request.

I tried forbiddenResponse() but as it turns out it has been eliminated.

Then I tried failedauthorization() but this does not redirect as well and allows me to edit.

here is my request file

```<code>public function authorize()
{
  $job_posting_id = $this->route('id');

  $job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();

  if($job_posting){
    return true;
  }

  return false;
}

public function failedAuthorization()
{

  return redirect('errors.dashboard.parent.403');
}
</code>```

I have a folder called errors and inside there I have dashboard folder and parent where the error file is located.

How can I redirect to that page if authorization fails?

答:
Go to the file Exceptions/Handler.php's report method.

```<code> public function report(Exception $e)
 {
     if(!Auth::check())
     {
        // Do whatever you want - redirect or return something
     }
     if($e instanceof HttpException && $e->getStatusCode() == 403)
     {
         // Do whatever you want - redirect or return something
     }
    return parent::report($e);
 }
</code>```

And wherever your authorisation failed, just write abort(403)

Hope this will help :)

Body:
I am trying to show a custom 403 file in laravel when authorization fails in my edit request.

I tried forbiddenResponse() but as it turns out it has been eliminated.

Then I tried failedauthorization() but this does not redirect as well and allows me to edit.

here is my request file

public function authorize()
{
  $job_posting_id = $this->route('id');

  $job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();

  if($job_posting){
    return true;
  }

  return false;
}

public function failedAuthorization()
{

  return redirect('errors.dashboard.parent.403');
}

I have a folder called errors and inside there I have dashboard folder and parent where the error file is located.

How can I redirect to that page if authorization fails?

Body:
Go to the file Exceptions/Handler.php's report method.

 public function report(Exception $e)
 {
     if(!Auth::check())
     {
        // Do whatever you want - redirect or return something
     }
     if($e instanceof HttpException && $e->getStatusCode() == 403)
     {
         // Do whatever you want - redirect or return something
     }
    return parent::report($e);
 }

And wherever your authorisation failed, just write abort(403)

Hope this will help :)


问:
how can I convert all of the pages from a website to pdf?
I need to make edits for a website developer / designer and he asked me to print all of the pages and make comments directly on them.

There are about 35 unique pages that I want to edit, although there are thousands that can be automatically generated from a database, but these are numbered sequentially. Thus, I would like to only download pages with an index of 1 in the address, e.g.,

It would be great if there were a bash solution that I could use, but Ruby would also work - the site is written in ruby, and the developer is good with ruby and bash and some other languages - so if you could give some suggestions to get us started, that would be great.

I want to print all pages in the server.com/ directory except, if the page is indexed by record, those with index > 1:

server.com/records/

server.com/records/1

server.com/records/1/new

but not

server.com/records/2

server.com/records/2/new

or any pages with a ? in them like

server.com/records?letter=K

and etc

Is there a simple, automated way that I could convert all of the pages to pdf?

答:
wkhtmltopdf is an excellent tool that works nicely in Ubuntu </p>

```<code> wkhtmltopdf www.google.com foo.pdf
 xpdf foo.pdf
</code>```

Body:
wkhtmltopdf is an excellent tool that works nicely in Ubuntu

 wkhtmltopdf www.google.com foo.pdf
 xpdf foo.pdf


问:
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>```

答:
try with com.example.neo.smsapp.IFTT.CancelAnAlarmActivity in manifest file. Like this:

```<code><activity android:name="com.example.neo.smsapp.IFTT.CancelAnAlarmActivity"
          android:label="CancelAlarm"
          android:screenOrientation="landscape">
</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:
try with com.example.neo.smsapp.IFTT.CancelAnAlarmActivity in manifest file. Like this:

<activity android:name="com.example.neo.smsapp.IFTT.CancelAnAlarmActivity"
          android:label="CancelAlarm"
          android:screenOrientation="landscape">
</activity>


问:
Can I add some comment while debugging my application?
Is there a way in Visual Studio to add some comment to my code while I am executing debugging?

If I try to do it Visual Studio tells me that changes are not allowed.

Searching on Google I found many people that ask about this feature but I can't find a real solution to insert some comment into my code (only bookmarks).

Is it impossible or is there a way to accomplish this operation?

I know that in Java (using Eclipse) I can do it and it is very comfortable

答:
Sure! you can both add comments to your codes and even modify your codes while debugging your application.

But, remember: you should Enable and Disable Edit and Continue(see here) as khellang said, and check you are in break mode(rather than debug mode).


问:
Cloud Functions for Firebase onWrite timeout
I return transaction promise which should wait for transaction to finish before stopping the function. The transaction executes fine, but the promise seems to never resolve.

I see in the Firebase console that this function always times out after 60s.

```<code>const functions = require('firebase-functions');
const admin = require("firebase-admin");
const db = admin.database();

export let countFollowers = functions.database.ref('followers/{followee}/{follower}').onWrite(event => {
    const followee = event.params.followee;
    let path = `posts/${followee}/cnt_foll`;
    const countRef = db.ref(path);
    let out = countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (parseInt(current) || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (parseInt(current) || 0) - 1;
        }
    });

    return out;
});
</code>```

EDIT:

I solve the problem with the following "hack", I create a promise myself, because whatever .transaction is returning is not working:

```<code>return new Promise(function(resolve, reject) {
    countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (parseInt(current) || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (parseInt(current) || 0) - 1;
        }
    }, () => resolve(null));
});
</code>```

答:
There was a known issue with older versions of the firebase-admin SDK where Firebase Database references and snapshots couldn't be JSON serialized and thus couldn't be used in return values for Cloud Functions. This includes transaction return values since they also have snapshots.

Your hack works around the bug; you should also get the fix if you update your version of firebase-admin.

Body:
I return transaction promise which should wait for transaction to finish before stopping the function. The transaction executes fine, but the promise seems to never resolve.

I see in the Firebase console that this function always times out after 60s.

const functions = require('firebase-functions');
const admin = require("firebase-admin");
const db = admin.database();

export let countFollowers = functions.database.ref('followers/{followee}/{follower}').onWrite(event => {
    const followee = event.params.followee;
    let path = `posts/${followee}/cnt_foll`;
    const countRef = db.ref(path);
    let out = countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (parseInt(current) || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (parseInt(current) || 0) - 1;
        }
    });

    return out;
});

EDIT:

I solve the problem with the following "hack", I create a promise myself, because whatever .transaction is returning is not working:

return new Promise(function(resolve, reject) {
    countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (parseInt(current) || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (parseInt(current) || 0) - 1;
        }
    }, () => resolve(null));
});


问:
AngularJS invoking function whose name is constructed as a string
I have a situation in which there are main functions named as:

```<code>Add_<Element_Type>_Page()
</code>```

where Element_Type is received as a parameter.

I can see two options to handle the invocation of the correct function:

Write a relatively long switch construct covering all possible values of Element_Type, or

Use some existing mechanism/trick (I'm not aware of) through which I can build a string using the received Element_Type and invoke a function whose name is contained in that string.

Needless to say, all the functions that can be invoked this way have exactly the same signature as far as parameters is concerned.

Obviously, Option 2 would be the best (easy to maintain and very general as no changes are needed whenever a new type of pages is added).

Is this possible to achieve within AngularJS framework?

Thanks in advance.

答:
You can simply do that using the [...] notation instead of .

Like this,

```<code>$scope["Add_" + Element_Type + "_Page"]()
</code>```

will call $scope.Add_test_Page() assuming Element_Type would be test

or  if using controllerAs syntax,

```<code>vm["Add_" + Element_Type + "_Page"]()
</code>```

where Element_Type is a received parameter as you mentioned.

If you want to use it inside HTML, you can have a reference to your Element_Type in $scope/vm (whichever way you are using) and access it.

Body:
I have a situation in which there are main functions named as:

Add_<Element_Type>_Page()

where Element_Type is received as a parameter.

I can see two options to handle the invocation of the correct function:

Write a relatively long switch construct covering all possible values of Element_Type, or

Use some existing mechanism/trick (I'm not aware of) through which I can build a string using the received Element_Type and invoke a function whose name is contained in that string.

Needless to say, all the functions that can be invoked this way have exactly the same signature as far as parameters is concerned.

Obviously, Option 2 would be the best (easy to maintain and very general as no changes are needed whenever a new type of pages is added).

Is this possible to achieve within AngularJS framework?

Thanks in advance.

Body:
You can simply do that using the [...] notation instead of .

Like this,

$scope["Add_" + Element_Type + "_Page"]()

will call $scope.Add_test_Page() assuming Element_Type would be test

or  if using controllerAs syntax,

vm["Add_" + Element_Type + "_Page"]()

where Element_Type is a received parameter as you mentioned.

If you want to use it inside HTML, you can have a reference to your Element_Type in $scope/vm (whichever way you are using) and access it.


问:
Disable weekly digest email for an environment in Application Insights
I have 2 web apps in Azure, one for UAT and another for Production. Both have Application Insights telemetry installed and active on them for performance monitoring.

I currently am receiving the Weekly Application insights digest email, which summarizes the telemetry for the week, as expected. However both environments are included in the one email.

I do require to switch off this feature for the UAT web app. I have already disabled all alerts.

I have read the following post, Disable digest email in Application insights, but this is a request to unsubscribe from the email and not to disable for an environment.

Disabled Alerts

答:
I'm afraid it's not possible to explicitly disable AI(likewise it's not possible to disable storage account/event hub and so on).

If this is not a case you can stop sending the data to your AI instance, but still I'm not sure whether this is going to help you(by stop sending the data I mean - disable whole telemetry I avoid initializing it from your code).