text:
Q: NotificationListenerService Implementation I am trying to implement NotificationListnerService which is added in android 4.3 but I am not able to get the notification details.
My code are as below
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setSmallIcon(R.drawable.ic_launcher);
        mBuilder.setContentTitle("notification test");
        mBuilder.setContentText("Notification text");
        mBuilder.setAutoCancel(true);
        Intent resultIntent = new Intent(this, ResultActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(ResultActivity.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(1, mBuilder.build());
    }

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

}

public class NotificationListenerTesting extends NotificationListenerService{

    public static String TAG = "NotificationListenerTesting";
    //private StatusBarNotification[] mStatusBarNotification;

    @Override
    public void onCreate(){
        super.onCreate();
        Log.d(TAG, "Inside on create");
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        TAG = "onNotificationPosted";
        Log.d(TAG, "id = " + sbn.getId() + "Package Name" + sbn.getPackageName() +
                "Post time = " + sbn.getPostTime() + "Tag = " + sbn.getTag());
    }
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        TAG = "onNotificationRemoved";
        Log.d(TAG, "id = " + sbn.getId() + "Package Name" + sbn.getPackageName() +
                "Post time = " + sbn.getPostTime() + "Tag = " + sbn.getTag());

    }

}

Android manifest file is
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.notificationtest"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.notificationtest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.notificationtest.ResultActivity"></activity>
        <service android:name="com.example.notificationtest.NotificationListenerTesting"
            android:label="notification"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService"/>
            </intent-filter>
        </service>
    </application>
</manifest>

but after notification click or on notification post NotificationListenerService is not getting called , Whats wrong in this or did I miss somthing ? How to implement it ?

A: It might be a bit late. But a few months ago I also struggled with making NotificationListenerService work.
Since then I`ve learned how to implement it and felt like building a implementation tutorial to help others who went through the same as me
If anyone is interested, check the project here:
https://github.com/Chagall/notification-listener-service-example
Hope it helps someone who is struggling with it.

A: I know its too late to answer the question , but as I was not able to find Settings > Sound and notifications -> Notification access, so I directly allow access of notifications to my app by firing this intent:
startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));

A: You need to grant access to your app to read notifications:
 "Settings > Security > Notification access" and check your app.

A: Inside the NotificationListenerService you need a looper to communicate with GUI thread so you can create a broadcast to handle the GUI interaction.
Hope this example will help you.

A: I ran into the same problem and have found some clues for that.
NotificationListenerService may not be running unless you call bindService() to start it.
Sometimes it started automatically when you enabled "Notification access" and sometimes it's not.

A: At least one problem with your code is that your implementation of onBind()
There is no necessity to override this method. But if you must, then at least return the IBinder returned by the superclass.
@Override
public IBinder onBind(Intent intent) {
    return super.onBind(intent);
}

A: I am doing the same thing as in GitHub, but still I am not going into the notification class.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;

/**
 * @author dinesh
 *
 */
public class UserNotificationService extends NotificationListenerService {

    private String TAG = "UserNotificationService";
    UserNotificationServiceReceiver notfRcvr;

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {

        Log.i(TAG,"********** onNotificationRemoved");
    Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText +"\t" + sbn.getPackageName());
    Intent i = new Intent("de.tu.darmstadt.moodsense.services.Notification");
    i.putExtra("notification event", "On notification removed");
    sendBroadcast(i);

    }

    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {

        Log.i(TAG,"**********  onNotificationPosted");
    Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
    Intent i = new Intent("de.tu.darmstadt.moodsense.services.Notification");
    i.putExtra("notification event", "On notification posted");
    sendBroadcast(i);

    }

    @Override
    public void onCreate() {
        super.onCreate();
        notfRcvr = new UserNotificationServiceReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("de.tu.darmstadt.moodsense.services.Notification");
        registerReceiver(notfRcvr, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(notfRcvr);
    }

    class UserNotificationServiceReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if(intent.getStringExtra("command").equals("clearall")) {
                UserNotificationService.this.cancelAllNotifications();
            }
        }

    }
}

import java.lang.Thread.State;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import twitter4j.Status;
import twitter4j.TwitterException;
import de.tu.darmstadt.moodsense.R;
import de.tu.darmstadt.moodsense.app.UserMood;
import de.tu.darmstadt.moodsense.constants.Constants;
import de.tu.darmstadt.moodsense.util.MqttMoodClient;
import de.tu.darmstadt.moodsense.util.TwitterMoodUtils;
import de.tu.darmstadt.moodsense.util.TwitterUtils;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

/**
 * @author dinesh
 * Added for V1.1
 * Code style based on : https://newcircle.com/s/post/1049/
 *                       tutorial_services_part_1_android_bootcamp_series_2012
 *
 */
public class UserMoodService extends Service{

    static final String TAG = "UserMoodService";
    public static boolean userMoodSet = false;
    //declarations for twitter
    private SharedPreferences prefs;
    SharedPreferences userPref;
    String userTwitterMood = "";
    String worldTwitterMood = "";
    String screenName, userName;
    int m_counter;
    long shortMinutes;
    boolean m_enterMood;
    int m_myMood;
    int m_moodIntensity;
    MqttMoodClient mqc;
    TwitterMoodUtils tmu;
    Calendar cal = Calendar.getInstance();

    private static final int MY_NOTIFICATION_ID=1;
    NotificationManager notificationManager;
    Notification myNotification;
    UserMoodNotificationReceiver usrMoodNotfnnRcvr;

    public UserMoodService() {
        // TODO Auto-generated constructor stub
        mqc = new MqttMoodClient();
        tmu = new TwitterMoodUtils();
    }
    public void reset() {

        m_myMood = Constants.NUM_MOOD_TYPES;
        m_moodIntensity = Constants.MILD;
        m_enterMood = false;

        m_counter = 0;

    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        // TODO Auto-generated method stub
        Intent restartService = new Intent(getApplicationContext(),this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(),
                1, restartService, PendingIntent.FLAG_ONE_SHOT);

         AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +100, restartServicePI);
    }

    /** (non-Javadoc)
     * @see android.app.Service#onCreate()
     */
    @Override
    public void onCreate() {
        Log.d(TAG, "OnCreation");
        //super.onCreate();
        usrMoodNotfnnRcvr = new UserMoodNotificationReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("Notofication Obj");
        registerReceiver(usrMoodNotfnnRcvr, filter);

    }

    /** (non-Javadoc)
     * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "OnStartCommand");
        try {
            ConnectivityManager cm =
                (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                Log.d(TAG,"Twitter loop enter");
                //Check the user's mood on twitter
                computeMoodOnTwitter();
                if(userMoodSet) {
                    Log.d(TAG, "user's twitter mood" + userTwitterMood);
                } /*else {
                    Log.d(TAG, "user mood not set, world mood computation started");
                    //If user's mood is not set then check for world's mood
                }*/

            }
        } catch(Exception e) {
            e.printStackTrace();
        }

        return START_STICKY;
    }

    private void computeMoodOnTwitter() {
        // TODO Auto-generated method stub
        reset();
        this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
        Thread twitterThread;
        twitterThread = new Thread() {
            public void run() {
                //userMoodSet = false;
                Log.d(TAG, "User mood is :: "+ userMoodSet);
            /*try {
                  String usrNme =  TwitterUtils.getUserName(prefs).toString();

                  List<Status> statuses = TwitterUtils.getHomeTimeline(prefs);

                     for(int i=0; i < Constants.NUM_MOOD_TYPES; i++) {
                        for (int j =0 ; j < Constants.NUM_MOOD_TYPES; j++)
                        {
                            for (twitter4j.Status status : statuses) {

                                //Check if the status is from the user and it matches our mood strings
                            if(status.getText().contains(Constants.searchStrings[i][j])
                                    && (status.getUser().getScreenName().equals(usrNme))) {
                                Date date = status.getCreatedAt();
                                long Minutes = tmu.getMinuteDifference(cal.getTime(), date);

                                if((Constants.sdf.format(date).equals(Constants.sdf.format(cal.getTime())))) {
                                  //Increment counter for each tweet
                                    Log.d(TAG, "User has a status");
                                    userMoodSet = true;
                                    m_counter++;
                                   //track time for the first tweet
                                   if(m_counter == 1) {
                                    shortMinutes = Minutes;
                                    m_moodIntensity = computeMoodIntensity(i,j);
                                    m_myMood = i;
                                    Log.d(TAG, "intensity + mood" + m_moodIntensity +","+ m_myMood);
                                    Log.d(TAG,"SocialMood:: mymood- " + Constants.moodIntensityNames[m_moodIntensity]+
                                               " "+ Constants.moodNames[m_myMood]);
                                    Log.d(TAG, "SocialMood:: status-"+status.getText());

                                   } else //counter more than 1   //track time for the later tweets
                                   {  //take latest tweet only if logged minutes is shorter than earlier minutes
                                       if(Minutes < shortMinutes) {
                                          shortMinutes = Minutes;
                                          Log.d(TAG, "Called compute mood_intensity :: "+ m_counter);
                                          m_moodIntensity = computeMoodIntensity(i,j);
                                          m_myMood = i;
                                        }

                                   }
                                  }
                                }
                              }
                            }
                         }
                    } catch(TwitterException te) {
                      userMoodSet = false;
                        Log.d(TAG, "Unable to process twitter get requests "+te.getErrorCode()+ " "+ te.getErrorMessage());

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        Log.d(TAG,"Error msg");
                        e.printStackTrace();
                    }*/

                try {
                    stopThread(this);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };

        twitterThread.start();

    }

    public int computeMoodIntensity(int m_detect, int m_type) {
        // TODO Auto-generated method stub
        for(int j=0; j < Constants.m_extreme.length; j++) {
            if(m_type == Constants.m_extreme[m_detect][j])
                return Constants.EXTREME;
        }
        for(int j=0; j < Constants.m_considerable.length; j++) {
            if(m_type == Constants.m_considerable[m_detect][j])
                return Constants.CONSIDERABLE;
        }

        return Constants.MILD;

    }

    private String userStatusToMood(int myMood) {
        // TODO Auto-generated method stub
        String userMood = Constants.userNoTwitter;
         if(m_myMood >= Constants.NUM_MOOD_TYPES) {
             m_enterMood = true;
         Log.d(TAG, userMood);
         //Unreachable code - maybe we need to delete this ?? QNS
         /*Intent i = new Intent(UserMoodService.this,UserMood.class);
             i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             startActivity(i);*/
         }
         else {
             userMood = "User mood is "+ Constants.moodNames[m_myMood];
             userTwitterMood = Constants.moodIntensityNames[m_moodIntensity]
                     +" "+Constants.moodNames[m_myMood];

             Log.d(TAG, "Updated user mood is "+userTwitterMood);
             //call MQTT
             MqttMoodClient mqc = new MqttMoodClient();

             mqc.setupMqttClient();
             mqc.sendMessage(userTwitterMood);

         }
         return userMood;
    }

    private void stopThread(Thread theThread) throws Exception {
        // method to stop the worker thread once the process needed to do has been completed
        Log.d(TAG,"userMoodSet :: "+ userMoodSet);
        if (theThread != null)
        {
            theThread = null;
            Log.d(TAG, "Execution complete inside stop thread");
            if(userMoodSet)
                userStatusToMood(m_myMood);
        }

        if(!userMoodSet) {
            Log.d(TAG, "In world thread");
            //Call world Service
            //WorldMoodService worldService = new WorldMoodService();
            //worldService.computeWorldMood(this);
            //show notification!!
            /**
             * V1.1
             * @author dinesh
             * Code adapted from : http://android-er.blogspot.de/2013/06/
             *                     start-activity-once-notification-clicked.html
             */
            Intent myIntent = new Intent(UserMoodService.this, UserMood.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(
                    UserMoodService.this,
                0,
                myIntent,
                Intent.FLAG_ACTIVITY_NEW_TASK);

            myNotification = new NotificationCompat.Builder(UserMoodService.this)
            .setContentTitle("MoodSense notification")
            .setContentText("Please enter mood to play music as per your mood")
            .setTicker("Please enter mood to play music as per your mood")
            .setWhen(System.currentTimeMillis())
            .setContentIntent(pendingIntent)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setAutoCancel(true)
            .setSmallIcon(R.drawable.app_icon)
            .build();

            notificationManager =
                       (NotificationManager)UserMoodService.this.
                       getSystemService(Context.NOTIFICATION_SERVICE);
                     notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

        } else if (userMoodSet) {
            Intent i = new Intent("de.tu.darmstadt.moodsense.services.Notification");
            i.putExtra("command", "clear all");
            sendBroadcast(i);
        }
    }

    public class UserMoodNotificationReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String temp = intent.getStringExtra("notification event");

        }

    }
    /** (non-Javadoc)
     * @see android.app.Service#onDestroy()
     */
    @Override
    public void onDestroy() {
        Log.d(TAG, "OnDeletion");
        super.onDestroy();
    }
}

A: Update 2020 Kotlin And AndroidX

package com.hiteshsahu.notificationlistener.notification

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager

class CustomNotificationListenerService : NotificationListenerService() {

    private var commandFromUIReceiver: CommandFromUIReceiver? = null

    override fun onCreate() {
        super.onCreate()

        // Register broadcast from UI
        commandFromUIReceiver = CommandFromUIReceiver()
        val filter = IntentFilter()
        filter.addAction(READ_COMMAND_ACTION)
        registerReceiver(commandFromUIReceiver, filter)
    }

    /**
     * New Notn Added Callback
     */
    override fun onNotificationPosted(newNotification: StatusBarNotification) {
        Log.i(
            TAG,
            "-------- onNotificationPosted(): " + "ID :" + newNotification.id + "\t" + newNotification.notification.tickerText + "\t" + newNotification.packageName
        )
        sendResultOnUI("onNotificationPosted :" + newNotification.packageName + "\n")
    }

    /**
     * Notn Removed callback
     */
    override fun onNotificationRemoved(removedNotification: StatusBarNotification) {
        Log.i(
            TAG,
            "-------- onNotificationRemoved() :" + "ID :" + removedNotification.id + "\t" + removedNotification.notification.tickerText + "\t" + removedNotification.packageName
        )
        sendResultOnUI("onNotificationRemoved: " + removedNotification.packageName + "\n")
    }

    internal inner class CommandFromUIReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            if (intent.getStringExtra(COMMAND_KEY) == CLEAR_NOTIFICATIONS)
                 // remove Notns
                cancelAllNotifications()
            else if (intent.getStringExtra(COMMAND_KEY) == GET_ACTIVE_NOTIFICATIONS)
                // Read Notns
                fetchCurrentNotifications()
        }
    }

    /**
     * Fetch list of Active Notns
     */
    private fun fetchCurrentNotifications() {
        sendResultOnUI("===== Notification List START ====")

        val activeNotnCount = this@CustomNotificationListenerService.activeNotifications.size

        if (activeNotnCount > 0) {
            for (count in 0..activeNotnCount) {
                val sbn = this@CustomNotificationListenerService.activeNotifications[count]
                sendResultOnUI("#" + count.toString() + " Package: " + sbn.packageName + "\n")
            }
        } else {
            sendResultOnUI("No active Notn found")
        }

        sendResultOnUI("===== Notification List END====")
    }

    // sendMessage success result on UI
    private fun sendResultOnUI(result: String?) {
        val resultIntent = Intent(UPDATE_UI_ACTION)
        resultIntent.putExtra(RESULT_KEY, Activity.RESULT_OK)
        resultIntent.putExtra(RESULT_VALUE, result)
        LocalBroadcastManager.getInstance(this).sendBroadcast(resultIntent)
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(commandFromUIReceiver)
    }

    companion object {

        const val TAG = "NotificationListener"

        //Update UI action
        const val UPDATE_UI_ACTION =   "ACTION_UPDATE_UI"
        const val READ_COMMAND_ACTION = "ACTION_READ_COMMAND"

        // Bundle Key Value Pair
        const val RESULT_KEY = "readResultKey"
        const val RESULT_VALUE = "readResultValue"

        //Actions sent from UI
        const val COMMAND_KEY = "READ_COMMAND"
        const val CLEAR_NOTIFICATIONS = "clearall"
        const val GET_ACTIVE_NOTIFICATIONS = "list"

    }
}

Complete Project
https://github.com/hiteshsahu/Android-Notification-Demo

A: The notification that you build does not have "tickerText." I have found that if the notification does not have tickerText, onNotificationPosted does not get called.
In your code add mBuilder.setTicker( "your text here" ).
onNotificationPosted should now be called assuming that the rest of the NotificationListenerService set up is copacetic.


text:
Q: Question inside $\int \tan^2 x dx$ $$\int \tan^2 x dx$$ the question isn't behind on how to do it but rather on its solution, let me go through my solution quickly:
If we do a substitution $u=\tan(x)$ then $du=\sec^2 x dx=(u^2+1)dx$ hence we get $$\int \frac{u^2}{1+u^2}du=\int\left(1-\frac{1}{1+u^2}\right)du=\tan x-\arctan(\tan x)+C$$ so no problem until here. The solution from the book or WolframAlpha is: $\tan x-x+C$ so it raised a question, since $\tan $ isn't injective and only has an inverse for $x\in(-\frac{\pi}{2},\frac{\pi}{2})$, for which then $\arctan(\tan(x))=x$ is only true for $x\in(-\frac{\pi}{2},\frac{\pi}{2})$. But then why if we do $\arctan(\tan x)=x$ in my solution we then get $$\tan x-x+C$$ which is the same as the correct solution the book or WolframAlpha shows, while we have only just considered the $x\in(-\frac{\pi}{2},\frac{\pi}{2})$ in my method? Isn't the indefinite integral considering $\forall x\in \mathbb{R}$? Why is this happening?
Note: Not looking at all for an alternative solution or how to get there, rather why I get the correct solution by considering $x\in(-\frac{\pi}{2},\frac{\pi}{2})$ while an integral should be $\forall x\in \mathbb{R}$

A: This is a phenomenon that happens with all indefinite integrals. The original integral
$$\int \tan^2 x\:dx$$
has singularities at $\frac{\pi}{2} + \pi k$ for $k\in\Bbb{Z}$, therefore, no, the original integral was not for all $x\in\Bbb{R}$. Whenever you have discontinuities like that, they are tucked away in the $+C$. For example, take the textbook case of
$$\int \frac{dx}{x} = \log|x| + C$$
but this answer is a little misleading misleading. Consider the function
$$f(x)=\begin{cases}\log( -x) +7 & x<0 \\ \log (x )-2 & x>0\end{cases}$$
Taking the derivative, we see that it is still $\frac{1}{x}$. That is because $f$ can still be written as
$$f(x) = \log|x| + C$$
but in this case, the constant $C$ changes values across the discontinuity
$$C = \begin{cases}7 & x<0 \\ -2 & x>0\end{cases}$$
and that is allowed for $+C$. In your answer, we have that
$$x = \arctan(\tan x) + C$$
where the $+C$ hides the arbitrary constant (s)
$$C = \pi\left\lfloor\frac{x+\frac{\pi}{2}}{\pi}\right\rfloor$$
which makes the two answers equivalent, since they are only off by an arbitrary constant.

A: Elementary Explanation
Most elementary textbook authors are fairly careful to define things in such a way that the situation you are describing is not an issue.  Because I have been teaching out of it recently, here is what Thomas' Calculus (instructor's 13th ed) has to say:

Definition: (p. 232) a function $F$ is an antiderivative of $f$ on an interval $I$ if $F'(x) = f(x)$ for all $x$ in $I$.

and

Definition: (p. 237) The collection of all antiderivatives of $f$ is called the indefinite integral of $f$ with respect to $x$, and is denoted by
$$ \int f(x)\,\mathrm{d}x. $$

Notice that the indefinite integral of $f$ is defined in terms of antiderivatives of $f$, and the antiderivative of $f$ is only defined if $f$ is defined on an interval.
This implies that before you even start to ask what the indefinite integral of a function is, you first have to be clear about the definition of that function.  What does the collection of symbols $\tan(x)^2$ represent?[1]
Barring any other information, I would assume that $\tan$ represents the tangent function, which is defined on the domain $\mathbb{R}\setminus \{\pi/2 + k\pi : k\in\mathbb{Z}\}$ (that is, the tangent function is defined everywhere that the cosine is not zero).  BUT there is a problem here, since the question is about the antiderivative of the square of the tangent function, and the tangent function is naturally defined on a set which is not an interval.
This implies that
$$\int \tan(x)^2\,\mathrm{d}x$$
does not, in fact, refer to the square of the tangent function on its natural domain, but only on some connected component of that domain, say $(-\pi/2,\pi/2)$, or $(\pi/2, 3\pi/2)$.  Before you can evaluate the indefinite integral, you must first specify the domain of the function which you are integrating.
But...
In their answer, Ninad Munshi argues that one can discuss antiderivatives of functions which are defined on disconnected domains, and that the "disconnection" is swallowed by the constant of integration.  I will not argue that they are wrong, but I do think that this is a wrongheaded approach, which could, potentially, lead to pain later on—being able to "split out" the behaviour of a function across singularities is often helpful.
Looking at the example of $x \mapsto 1/x$, we have two facts:

*

*if we assume that $x > 0$, then
$$ \int \frac{1}{x}\, \mathrm{d}x = \log(x) + C, $$
where $C$ is an arbitrary constant of integration, and

*if we assume that $x < 0$, then
$$ \int \frac{1}{x}\, \mathrm{d}x = \log(-x) + C, $$
where $C$ is an arbitrary constant of integration.

If we want to talk about an "antiderivative"[2] or "indefinite integral"[3] of $x \mapsto 1/x$ on the set $\mathbb{R}\setminus \{0\}$, then I think that it is wise to keep track of the various domains of definition.  Hence I would argue that the "correct" antiderivative is something like
$$ \int \frac{1}{x} \,\mathrm{d}x = \begin{cases} \log(x) + C & \text{if $x > 0$, and} \\ \log(-x) + D & \text{if $x < 0$,} \end{cases}
$$
where both $C$ and $D$ are arbitrary constants of integration.
In the case of $\tan(x)^2$, it would not be unreasonable to write
$$\int \tan(x)^2 \,\mathrm{d}x = \begin{cases}
\tan(x) + x + C_k & \text{if $x \in \left(\dfrac{\pi}{2} + (k-1)\pi, \dfrac{\pi}{2} + k\pi\right)$,} \end{cases}
$$
where $C_k$ is an arbitrary constant of integration for each $k\in \mathbb{Z}$.

[1] Minor pet peeve:  I work in an area of mathematics where $f^2$ means $f \circ f$, i.e. $f$ composed with itself.  Because of this, I find the notation $\tan^2(x)$ somewhat ambiguous.  Yes, it is common notation, and no, you aren't going to be misunderstood if you use it.  But my choice is to use $\tan(x)^2$, as I think that it is less ambiguous.  This explains my choice above.  Please make your own choices when writing.
[2] "Antiderivative" is in quotes because, per the definition at the top, an antiderivative is only defined on an interval, and we are about to talk about a function which is not defined on an interval, so the definition we are working with doesn't really apply.
[3] Ditto.

A: When you apply a substitution u=f(x) for an integral, the function f(x) must be bijective so that the inverse $f^{-1}$ exists.  In your case, you should let
$u=\tan x$ for $x\in \left(-\frac{\pi}{2}, \frac{\pi}{2}\right)$ so that $\arctan(\tan x)=x.$
For otherwise, if we fix an integer $n$ and let
$u=\tan x$ for $x \in\left( n \pi-\frac{\pi}{2}, n \pi+\frac{\pi}{2}\right)$,
then $$\arctan(\tan x)=n \pi+x$$
and
$$I=\tan x-\arctan(\tan x)+C= \tan x-(n \pi+x)+C=\tan-x+C',$$
where $C'=C-n\pi$ absorbs $-n\pi$ despite of the choice of principal values for the function $\arctan x$.
Wish it helps :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: May I ask how to understand the following bash script? May I ask what the following bash script is trying to do?
args=$(echo $@ |sed "s/^ *//;s/ *$//;s/ \{1,\}/ /g;s/-\{1,\} /-/g;s/ -/\t-/g")

Thanks!

A: Let us break it down:

*

*s/^ *//;

*s/ *$//;

*s/ \{1,\}/ /g;

*s/-\{1,\} /-/g;

*s/ -/\t-/g
1. Removes spaces at the beginning of line
2. Removes spaces at the end of line
3. Replaces spaces by a single space
4. Replaces dashes by asingle dash
5. Replaces space and dash by tab and dash

A: The script trims the arguments passed to the script via commandline. (The array of all arguments can be addressed using $@ in the shell)
Trimming means, it removes redundant whitespace in the middle of strings and removes whitespace completely at the start and end of each arguments. Your code will further replace a space in front of a hyphen by a TAB.
Transformations, made by the command, in detail:
s/^ *//          --> remove 0 or more spaces at the start of the string
s/ *$//          --> remove 0 or more spaces at the end of the string
/ \{1,\}/ /g     --> "melts" multiple spaces into one
s/-\{1,\} /-/g   --> Removes one or more white space after the hypen `-`
s/ -/\t-/g       --> Removes a space in front of a hypen by a TAB

A: Let's split it in small pieces, so it's easier to understand:

*

*Remove any spaces at the start of a line
s/^ *//;

*Remove any spaces at the end of a line
s/ *$//;

*Replace two or more spaces with a single space
s/ \{1,\}/ /g;

*Replace two or more dashes followed by a space - by a single dash
s/-\{1,\} /-/g;

*Replace a space and a dash - with a tab and a dash \t-
s/ -/\t-/g

A: The sed cleans up the spaces and changes this:
sdfgsdfg
  afadsfads fadsf
adsfadf   adfadfads
adfadfa - adsfdsf
dfadsf - dsfds
dfsd   -   sdfsd

To this:
sed "s/^ *//;s/ *$//;s/ \{1,\}/ /g;s/-\{1,\} /-/g;s/ -/\t-/g" file
sdfgsdfg
afadsfads fadsf
adsfadf adfadfads
adfadfa -adsfdsf
dfadsf  -dsfds
dfsd    -sdfsd

You can do it more simple by using awk
awk '{$1=$1;sub(/ - /,"\t-")}1' file
sdfgsdfg
afadsfads fadsf
adsfadf adfadfads
adfadfa -adsfdsf
dfadsf  -dsfds
dfsd    -sdfsd

Or in your case:
args=$(echo $@ | awk '{$1=$1;sub(/ - /,"\t-")}1')


text:
Q: Find the mean of columns with matching column names I have a dataframe similar to the following but with thousands of rows and columns:
x  y  ghb_00hr_rep1  ghb_00hr_rep2    ghb_00hr_rep3   ghl_06hr_rep1  ghl_06hr_rep2
x  y           2           3                 2                1         3
x  y           5           7                 6                2         1

I would like my output to look like this:
 ghb_00hr     hl_06hr
    2.3           2
     6           1.5

My goal is to find the average of the matching columns. I have come up with this: temp = df.groupby(name, axis=1).agg('mean') But I am not sure how to define 'name' as the matching columns.
My previous strategy was the following:
name = pd.Series(['_'.join(i.split('_')[:-1])
        for i in df.columns[3:]],
        index = df.columns[3:]
)
temp = df.groupby(name, axis=1).agg('mean')
    avg = pd.concat([df.iloc[:, :3], temp],
    axis=1
)

However the number of 'replicates' ranges from 1-4 so grouping by index location isn't an option.
Not sure if there is a better way to do this or if I am on the right track.

A: An option is to groupby level=0:
(df.set_index(['name','x','y'])
   .groupby(level=0, axis=1)
   .mean().reset_index()
)

Output:
    name  x  y  ghb_00hr  ghl_06hr
0  gene1  x  y  2.333333       2.0
1  gene2  x  y  6.000000       1.5

Update: for the modified question:
d = df.filter(like='gh')
# or d = df.iloc[:, 2:]
# depending on your columns of interest

names = d.columns.str.rsplit('_', n=1).str[0]

d.groupby(names, axis=1).mean()

Output:
   ghb_00hr  ghl_06hr
0  2.333333       2.0
1  6.000000       1.5

A: You can convert df.columns to set then iterate:
df = pd.DataFrame([[1, 2, 3, 4, 5, 6]], columns=['a', 'a', 'a', 'b', 'b', 'b'])

for column in set(df.columns):
    print(column, df[common_name].mean(axis=1))

will outputs
a 0    2.0
dtype: float64
b 0    5.0
dtype: float64

Use sorted if the order matters:
for column in sorted(set(df.columns)):

From here you can get the output in pretty much any format you want.


text:
Q: how to upload apk file to firebase realtime database by programmatically I'm using firebase real-time database first time, I saw many videos about uploading and retrieving data like images, video and pdf, but I couldn't found any apk uploading video, can anyone provide me documentation or any video link with quite coding change for uploading apk.. thanks in advance

A: Please refer to this firebase documentation - Uploading files on Android - Firebase
There's no difference in uploading an image, video or some other file type like APK. Also, please make sure to define proper rules for accessing the Firebase storage to upload your files. Refer Security rules for firebase

A: Its really funny thing ,im predicting fear before doing code of apk file but it is similar to all other methods like to upload pdf and images , by the way thanks to all and for ur couragement


text:
Q: Disable embedded keyboard on Linux How can I disable the embedded keyboard on my netbook so that I can put an external keyboard on top of it?
I'd like a solution that works across the whole system -- not just in a single X session but also in the virtual terminals.

A: For X11 you can use xinput list to find the keyboard id and xinput --disable ... to disable it. For the console keyboard I dont know of anything to disable it, but you can use loadkeys to install a dummy keyboard mapping that should stop most
accidental input. See man dumpkeys and keymaps(5).


text:
Q: javascript save canvas(png) from IE I used html2canvas library. I want to store the image using the html2canvas. I success to store image from html2canvas!!! WOW!!! but.... IE has failed... I want to store all of browser.
I find navigator.msSaveBlob... I was happy~  but the happiness did not last long... base64 Encording Image is String! but I want to store pngfile! help me!!!  (PS. I seriously want to slap a strong chest of IE)
~this is code~
html2canvas($("body")[0], {
        onrendered: function(canvas) {
      var img = canvas.toDataURL("image/png");
      var img2 = img.split("data:image/png;base64,")[1];

      //var blobObject = new Blob([img2],{type:"image/jpeg"});
        var blobObject = new Blob([img2]);
      window.navigator.msSaveBlob(blobObject, 'test.png'); // The user only has the option of clicking the Save button.
      alert('File save request made using msSaveBlob() - note the single "Save" button below.');
    }
});

A: The sad answer is... :-((
Chrome & Firefox have supported canvas.toBlob for a while, but...
IE & Edge don't yet natively support canvas.toBlob
But there are nice polyfills that bring .toBlob to IE/Edge.
I like Eli Grey's FileSaverJS and his canvas-toBlobJS.
BlueImp's JavaScript-Canvas-to-Blob  is popular, too.


text:
Q: 3.7v > 3.3v voltage stepdown with logic-driven on/off control [paused] (PAUSED): This topic is currently on hold as I source necessary hardware.
I need to connect a Wi-Fi/RS232 module to a low-powered monitoring device, and for maximum portability, I'd like to power the Wi-Fi module - which runs off 3.3v at a peak of 250mA - from the 3.7v/1200mAh Li-Po battery built into the device itself.
To do so, I first need to drop the voltage from 3.7v to 3.3v in a way that can tolerate 250mA. I figure a series resistor should be sufficient, since I'm just running off a battery and not an unregulated power source - but what value resistance should I use?
In addition, the Wi-Fi module's own low power/standby state draws 8mA, which is relatively low but still noticeable, and would drain the battery over time. I've managed to unearth some undocumented info on how to tweak a couple of unused sense inputs that wire straight into the device's CPU (one via a 100Ω series resistor, the other via a 330Ω one) so they work as output lines, and I'd like to use one of these to switch power to the module on/off (possibly via a transistor or something...?). [I need to verify this, but I'm 99% sure the output before the resistors is standard 3.3v TTL.]
Everything needs to fit inside a compartment 50x54mm in size, approximately 4-5mm thick.
My non-SMD soldering skills are passable, but I've never worked with SMD components, so I need non-SMD solutions.
I also need an solution that radiates virtually zero RFI/EMI due to the electromagnetically sensitive medical environment the device will be used in, which won't tolerate even low levels of continuous EMI/RFI radiation particularly well (although short Wi-Fi bursts will be fine).

A: A series resistor will not provide a good power supply for the WiFi module, as the voltage drop will vary depending on the current consumption of the module, which will vary.
Instead look at voltage regulator chips, "low-dropout" variety. Some are equipped with an enable line and sleep mode.

A: What you want is a buck-boost converter.  For example, the LTC3530EMS will take any input voltages from 1.8v to 5.5v, and you can set it to have an output of 3.3v.  If the voltage is above 3.3v, it will drop it down ("buck"), if the voltage is below 3.3v, it will boost it up.  That way, if your battery voltage drops below 3.3v, you can still power your electronics.
Most of these devices are relatively difficult to solder, with pins under the package.  Unfortunately none of them come in DIP packages.  However the LTC3530EMS, available from Digi-Key comes in a 10-MSOP package which is relatively easy to deal with.
For prototyping, you can get an MSOP to DIP adapter from several places, such as this one.
If all you need is to drop the input voltage to 3.3v (based on your comment below), then you might consider the LM3671MF, which is buck-converter only.  It is also available from Digi-Key in a SOT-23 package which will be easier to solder.  Re EMI, yes it does have a 2 MHz oscillator, but I have used these devices in several medical grade devices and have never had an EMI problem with them, after rigorous testing.
There are also SOT-23-5 to DIP adapters available.


text:
Q: Email Notification from Alias email address The Script:
function onFormSubmit() {

var ss = SpreadsheetApp.getActive().getSheetByName("Form responses 4");
var lastresponse =       ss.getRange(ss.getLastRow(), 1, 1, 18).getValues();
var customerEmail = lastresponse[0][10];
var Subject = "sample updates # " + lastresponse[0][1];
var alias = GmailApp.getAliases();

var Message = "Hello Team" +  ",
"
+ "Please Find Below Details :
"
+ "BN : " + lastresponse[0][1] + "
"
+ "PN : " + lastresponse[0][12] + "
"
+ "MN : " + lastresponse[0][13] + "
"
+ "MN1 : " + lastresponse[0][14] + "
"
+ "QP = " + lastresponse[0][3] + "
"
+ "QS = " + lastresponse[0][4] + "
"
+ "FR = " + lastresponse[0][5] + "
"
+ "SLR = " + lastresponse[0][6] + "
"
+ "SLRV = " + lastresponse[0][7] + "
"
+ "FR = " + lastresponse[0][8] + "
"
+ "PR = " + lastresponse[0][9] +"
"
+ "Co : " + lastresponse[0][11] + "
"

+ "please do not, reply on this    email.
"
+ "Thank you";

GmailApp.sendEmail(customerEmail, Subject, Message, { from:alias[0],htmlBody: Message,name: 'Updates'});
 }

I set up email notification on google form submit using alias email address but when the whole group receive email notification I am the only one who receive email from alias email address but everyone else receives email notification from my primary email address.
I am sending email notification using workspace account. Email notification set up using Appscript.
Is there anything I am missing to set this up for all?


text:
Q: curl unable to download webpages I am trying to open homepages of websites and extract title and description from it's html markup using curl with php, I am successful in doing this to an extent, but many websites are there I am unable to open. My code is here:
function curl_download($Url){
     if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
// $url is any url
$source=curl_download($url);
$d=new DOMDocument();
$d->loadHTML($source);
$title=$d->getElementsByTagName("title")->item(0)->textContent)
$domx = new DOMXPath($d);
$desc=$domx->query("//meta[@name='description']")->item(0);
$description=$desc->getAttribute('content');
?>

This code is working fine for most websites but there are many whome it doesn't even able to open. What can be the reason?
When I tried getting headers of those websites using get_headers function, its working fine, but these are not being opened using curl. Two of these websites are blogger.com and live.com.

A: Replace:
$output = curl_exec($ch);

with
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
$output = curl_exec($ch);
if (!$output) {
   echo curl_error($ch);
}

and see why Curl is failing.
It's a good idea to always check the result of function calls to see if they succeeded or not, and to report when they fail. While a function may work 99.999% of the time, you need to report the times it fails, and why, so the underlying cause can be identified and fixed, if possible.


text:
Q: Show message or run script on first login after reboot of ubuntu server essentially I would like to make sure I mount an encrypted drive after each reboot of my ubuntu server. Since this obviously requires me to type in my password, there are two ways I can imagine this to work:

*

*either show a message on each first log in of my user following a reboot (basically a reminder), or

*automatically running a script on each first log in of my user following a reboot.

Is either of the two possible at all and/or is there another (possibly more elegant) way to achieve this?
Thanks a ton for your advice!
Best,
J
See suggestion below for the first step toward a working solution. Basically, here's what I ended up doing:

*

*write script, which checks if device is mounted and execute mounting command if not:

mount | grep -c mapper/[device mapper] # this returns 1 if mounted, 0 if not

*Run this as cronjob

A: You could run a script on startup via cron.
Simply run crontab -e to create a cron-table. (It will create an empty one if you don't already have one.)
To run your script on startup, use
@reboot     /home/user/script_at_reboot.sh.
Further documentation in the ubuntu wiki.


text:
Q: One-to-many relationship only one entry of the many needed At first, thank you for taking the time to read this
Problem:
Example
SELECT Article.ID, Article.Name, Article.Price, EV.EV, Pic.Upload_Datum
FROM Article
LEFT JOIN Pic ON Articel.ID = Pic.Artikle_ID
LEFT JOIN Stock ON Stock.ID = Article.Lager_ID
LEFT JOIN EV ON EV.ID = Article.EV_ID
WHERE Article.Activ = "1"
AND Stock.trader_ID = "2"
AND Article.stock_ID = "1"
AND pic.Uploaddate IS NOT BETWEEN 1510903702 AND 1503127702
LIMIT 10

Example resutl
ID       Upload
2624919 1489736525
2624919 1489736528
2624920 1507295386
2624920 1507295389
2624920 1507295397
thats one of the results i get but i only need this two:
2624919 1489736525
2624920 1507295386
Now i get foreach Article.ID more than one record, because in the "pic" table there are more than one pictures of any article. The problem is, that i only need the first picture that the sql finds.
I hope its the right way to ask.
Greetings
B3rgi

A: If you dont really care of which data to take for your pic, see below sample, it will take the first pic of your Article.
SELECT Article.ID, Article.Name, Article.Price, EV.EV,

         SELECT  Pic.Upload_Datum
         FROM    Pic
         WHERE   Articel.ID = Pic.Artikle_ID
         LIMIT 1) AS Upload_Datum
FROM Article
LEFT JOIN Stock ON Stock.ID = Article.Lager_ID
LEFT JOIN EV ON EV.ID = Article.EV_ID
WHERE Article.Activ = "1"
  AND Stock.trader_ID = "2"
  AND Article.stock_ID = "1"
LIMIT 10


text:
Q: Object with nested array to filter, want to return entire object with new filtered array I'm attempting to remove an object out of an array nested within my movie object and then copy it to a new variable. So my original object looks like this:
{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 3,
            "lastName": "Weaver",
            "firstName": "Sigourney"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

and what I'm doing right now  is
const updatedMovie = const updatedMovie = movie.actors.filter((actor) => actor.id !== id);

but as you know that only returns the array of actors I filtered. I want to copy the entire object with the newly filtered actors so the object will come out like this (removing actor id 3):
{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

I've tried reading around but I'm not having any luck getting any solutions to work with me, so if anyone can help or point me in the right direction that would be great!

A: If you want to mutate the existing object, just assign the result of the .filter to the .actors property.
movie.actors = movie.actors.filter((actor) => actor.id !== id);
console.log(movie);

If you want to keep the existing object unmutated, spread the rest of the properties into a new object while filtering.
const updatedMovie = {
  ...movie,
  actors: movie.actors.filter((actor) => actor.id !== id)
};
console.log(updatedMovie);

A:

const movies = {
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 3,
            "lastName": "Weaver",
            "firstName": "Sigourney"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}
const id = 3; // or any other id you want
const actors = movies.actors.filter(actor => actor.id != id)
const newMovies = Object.assign({}, movies , { actors })
console.log(newMovies)


text:
Q: Hibernate program errors I am following this tutorial using eclipse EE : hibernate-tutorial-for-begin. There are the errors I am getting. One more thing is that I couldn't find all mentioned jar files in any one hibernate distribution, so I have all jars from openlogic-hibernate-3.3.1.GA-all-bin-1 & lib/jpa from hibernate-release-4.0.0.CR5 bec it was not included in 3.3.1.
I made tables in MySql.
EDIT
Here is list of Jar files I am using:
lib\mysql-connector-java-5.1.18-bin.jar
lib\slf4j-simple-1.6.4.jar
lib\antlr-2.7.6.jar
lib\commons-collections-3.1.jar
lib\dom4j-1.6.1.jar
lib\hibernate3.jar
lib\hibernate-cglib-repack-2.1_3.jar
lib\hibernate-entitymanager-4.0.0.CR5.jar
lib\javassist-3.4.GA.jar
lib\jta-1.1.jar
lib\slf4j-api-1.5.2.jar

Here are the errors:
Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
    at com.hib.HibernateUtil.<clinit>(HibernateUtil.java:7)
    at com.hib.Test.addUser(Test.java:61)
    at com.hib.Test.main(Test.java:20)
Caused by: java.lang.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory
    at org.slf4j.LoggerFactory.<clinit>(LoggerFactory.java:60)
    at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:151)
    at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
    ... 3 more

Here are program files:
Test.Java
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {

  Test tst = new Test();

  /**
   * adding records
   */
  tst.addUser("Saranga", "Rath");
  tst.addUser("Isuru", "Sampath");
  tst.addUser("Saranga", "Jaya");
  tst.addUser("Prasanna", "Milinda");

  tst.addTask(1, "Call", "Call Pubudu at 5 PM");
  tst.addTask(1, "Shopping", "Buy some foods for Kity");
  tst.addTask(2, "Email", "Send birthday wish to Pubudu");
  tst.addTask(2, "SMS", "Send message to Dad");
  tst.addTask(2, "Office", "Give a call to Boss");

  /**
   *  retrieving data
   */
  tst.getFullName("Saranga");

  /**
   * full updating records
   */
  User user = new User();
  user.setId(1);
  user.setFirstName("Saranga");
  user.setLastName("Rathnayake");
  tst.updateUser(user);

  /**
   * partial updating records
   */
  tst.updateLastName(3, "Jayamaha");

  /**
   * deleting records
   */
  User user1 = new User();
  user1.setId(4);
  tst.deleteUser(user1);
 }

 private void addUser(String firstName, String lastName) {

  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();

   User user = new User();

   user.setFirstName(firstName);
   user.setLastName(lastName);

   session.save(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void addTask(int userID, String title, String description) {

  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();

   Task task = new Task();

   task.setUserID(userID);
   task.setTitle(title);
   task.setDescription(description);

   session.save(task);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void updateLastName(int id, String lastName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   String hqlUpdate = "update User u set u.lastName = :newLastName where u.id = :oldId";
   int updatedEntities = session.createQuery( hqlUpdate )
   .setString( "newLastName", lastName )
   .setInteger( "oldId", id )
   .executeUpdate();

   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }

 }

 private void updateUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();

   session.update(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void getFullName(String firstName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   List<User> users = session.createQuery("from User as u where u.firstName = :firstName")
   .setString( "firstName", firstName )
   .list();
   for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
    User user = iter.next();
    System.out.println(user.getFirstName() +" " + user.getLastName());
   }
   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void deleteUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();

   session.delete(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }
}

HibernateUtil.java
package com.hib;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory() {
  try {
   // Create the SessionFactory from hibernate.cfg.xml
   return new Configuration().configure().buildSessionFactory();
  }
  catch (Throwable ex) {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}

hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost/userdata</property>
  <property name="connection.username">root</property>
  <property name="connection.password"></property>

  <!-- JDBC connection pool (use the built-in) -->
  <property name="connection.pool_size">1</property>

  <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

  <!-- Enable Hibernate's automatic session context management -->
  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache -->
  <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>

  <!-- Drop and re-create the database schema on startup -->
  <property name="hbm2ddl.auto">update</property>

  <!-- Mapping files -->
  <mapping resource="user.hbm.xml"/>
  <mapping resource="task.hbm.xml"/>

 </session-factory>
</hibernate-configuration>

task.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hib.Task" table="tasks">
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="userID">
   <column name="user_id" />
  </property>
  <property name="title">
   <column name="title" />
  </property>
  <property name="description">
   <column name="description"/>
  </property>
 </class>
</hibernate-mapping>

user.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hib.User" table="users" >
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="firstName">
   <column name="first_name" />
  </property>
  <property name="lastName">
   <column name="last_name"/>
  </property>
 </class>
</hibernate-mapping>

Task Class
package com.hib;

public class Task {

 private Integer id;
 private Integer userID;
 private String title;
 private String description;

 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public Integer getUserID() {
  return userID;
 }
 public void setUserID(Integer userID) {
  this.userID = userID;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}

User Class
package com.hib;

public class User {
 private Integer id;
 private String firstName;
 private String lastName;

 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
}

A: The runtime exception you've got is caused by slf4j (logging framework used by Hibernate). Make sure that you have provided the correct implementation that matches the slf4j API Hibernate was compiled with in your classpath, e.g. for Hibernate 3.3.1 (according to pom) the correct version is 1.5.2 (choose the target logging mechanism, e.g. simple/log4j/jdk14, according to your environment).

A: It's not compile-time error, it's run-time. You are missing slf4j-log4j12.jar binding or other, depending on what underlying logging framework you want to use.
You can download it from http://www.slf4j.org/

A: try to add hibernate-jpa-xxx.jar into your classpath.
Verify the database connection configuration as well.


text:
Q: How does the use of port 587 stop spammers? I see that that ISPs are starting to push users to use SMTP port 587 instead of old port 25. Spam usually appears in the ISP's reason for this need. My question is "how is this going to stem the spam tide?"

*

*Is this because 587 typically employs authentication? But some ISPs
don't require authentication on that port. Also, can't 25 be configured to require user authentication as well?

*Is this because 587 can use certificates? Aren't the certificates server-side rather than client-side?

*Is this to stop 'legacy' spam-bots? Won't the spammers just adapt?

What am I missing here? My Google searches return a lot of 'how to fix your port 25 issues', but very little 'why'.

A: This was done a very long time ago, and predominantly because of your first reason "587 typically employs authentication" and most (not all) ISP's do this. Port 25 has largely been closed down (public do not use / need it anymore) but spammers use to try to hijack port 25 to send out spam.  As I noted, this all happened a very long time ago in most places


text:
Q: Going through a range of numbers in python that each are supposed to be typed into a searchbox on a website maybe someone can help me, Im pretty new to coding
Im trying to go through a range of numbers that are each supposed to be typed into a searchbox on a website.
That is my sad try so far, does anyone have an idea? I guess its gotta be a little more complex than this

A: searchbar.send_keys('Numbers')

would send the word "Numbers" to the search bar, if you want to send the numbers themselves you could use a format string:
f"{Numbers}"

the f in front of the string "" indicates that it's going to be a format string and the {} evaluate your variables. So:
a = hello
print(f"{a} world!")
>>> hello world!

Though in that case that alone would only send the list to the searchbar so you could use a loop to get over the numbers one by one:
for i in Numbers:
     searchbar.send(str(i))

or you could "".join(Numbers) into one string and send them all at once. Kinda depends on why you're doing it and what you mean to accomplish with it.


text:
Q: firefox sandbox iframe location changing when it shouldn't When using html5 sandbox iframe I want the iframe to not be able to change its location:

It works great in Chrome but in Firefox an sandboxed iframe can still redirect.
it's a known bug but how can I patch it so that all Firefox users won't be redirected?

A: Example:
An with extra restrictions:

the sandbox attribute is supported in Internet Explorer 10, Firefox, Chrome, and Safari.
Note: The sandbox attribute is not supported in Internet Explorer 9 and earlier versions, or in Opera.
Definition and Usage
If specified as an empty string (sandbox=""), the sandbox attribute enables a set of extra restrictions for the content in the inline frame.
The value of the sandbox attribute can either be an empty string (all the restrictions is applied), or a space-separated list of pre-defined values that will REMOVE particular restrictions.
Differences Between HTML 4.01 and HTML5

The sandbox attribute is new in HTML5.

Syntax

Attribute Values

*

*"" => Applies all restrictions below

*allow-same-origin => Allows the iframe content to be treated as being from the same origin as the containing document

*allow-top-navigation => Allows the iframe content to navigate (load) content from the containing document

*allow-forms => Allows form submission

*allow-scripts => Allows script execution

javascript: is a kind of weird URI protocol. It works in some contexts, like , but not all - for instance, a window's location can not be set to such a URI. (While you can assign a javascript: URI to window.location as a really roundabout way of running a script, the window's location doesn't stay set to that value.)
To write content into an IFRAME, get a reference to the frame's document and write to it. Doing so will require that you set the allow-same-origin sandbox flag.

Live example: http://jsfiddle.net/wUvrF/1/


text:
Q: Extracting formula from model after using StepAIC I am running stepAIC for R. I am trying to extract the formula of the best model , and the best model itself from the returned value. Any thoughts?
Example:
library(tidyverse)
library(MASS)
df<-mtcars
mdl <- glm.nb(mpg ~ cyl +hp +drat+wt+qsec+gear+am +carb , data = df)
mdl <- stepAIC(mdl, trace = FALSE)

Edit
I know this code retuns a lot of values, I just need the formula.
mdl$terms
mpg ~ hp + wt
attr(,"variables")
list(mpg, hp, wt)
attr(,"factors")
    hp wt
mpg  0  0
hp   1  0
wt   0  1
attr(,"term.labels")
[1] "hp" "wt"
attr(,"order")
[1] 1 1
attr(,"intercept")
[1] 1
attr(,"response")
[1] 1
attr(,".Environment")
<environment: R_GlobalEnv>
attr(,"predvars")
list(mpg, hp, wt)
attr(,"dataClasses")
      mpg        hp        wt
"numeric" "numeric" "numeric"

A: How about
formula(mdl)

? .....


text:
Q: Find X so that $(p \Longleftrightarrow ¬q) ∧ (r ⇒ X) ∧ (¬r ⇒ ¬X)$ is contradiction I have to find X so that this $(p \Longleftrightarrow ¬q) ∧ (r ⇒ X) ∧ (¬r ⇒ ¬X)$ is a contradiction. Then I also have to find out whether or not I can find an X is a tautology.
What's the most efficient way of solving this? I'm clueless as to how to get this done. Should I draw a truth table? Is there a better way, because a truth table with 4 variables can take a lot of time + it's very easy to make a mistake. And even then, what do I do after I'm done with the truth table?

A: A trivial answer is to set $X = \neg r$. In fact, the proposition $(r \implies X) \land (\neg r \implies \neg X)$ has the same truth value of $(r \iff X)$. So, the whole proposition becomes
$$
(p \iff \neg q) \land (r \iff X)
$$
and, by setting $X=\neg r$, you obtain an easy contradiction $r \iff \neg r$ that makes the proposition a contradiction.


text:
Q: Is there a way to debug a release version when loading dlls? I am developing a 64 bit C++ application using Visual Studio 2015, Qt 5.5 and OpenCV3.0. The application runs well on the pc I use for developing in Release and Debug version. But the same application runs only in Debug on other PCs, and in release version I get this Error Message:
 The application was unable to start correctly 0xc0000005, Click Ok toclose the application:

I created a dump file to open it using visual studio debugger, it shows that the application stops when loading the dll before loading opencv_imgproc300.dll.
I tried to review the event viewer but I did not find this error there.
Is there a method to debug a release version in startup when loading the dlls to know which the cause of the problem?

A: After a great effort, I solved the issue, It was because the opencv_imgproc300.dll was corrupted, It has the true size but inside is corrupted, I checked with dependency walker and found that there is great difference between the linked DLL in the Application folder and  the original dll file.
As a summary, If you want to debug a release version when starting up, you have many methods. We will describe two of them:

*

*Compiling your Release version with Debug Info, and run your application like if it was in Debug version. If the application stops before loading a DLL. This DLL is probably corrupted or missing. This link show how to compile your Release version with Debug informations: How to: Debug a Release Build.

*Using Dependency walker, You open your release version application with this tool and you will find if there is any corrupted or missing dll  that it needs when starting up (It is marked with red color in dependency walker). If you application is built in 64 bit, your should use the x64 version of dependency walker. If it is x86, you should use the x86 version of dependency walker. If you use the x86 version to open the x64 version of your application,  you can see some false error related to linking with system DLL in their x86 version, but don't care about it, it is a bug in Dependency Walker itself.


text:
Q: Incorrect code is being called in 'if/elif/else' statement I'm making an interest calculator that does compound and simple interest. However, the if statement always runs the simple interest script regardless of input.
I have tried changing variables to strings, integers, and floats. I have tried changing variable names, I have tried removing the first block of code entirely. What the heck is wrong with it???
start = input("simple or compound: ")

if start == "simple" or "Simple":
    a = float(input('Starting balance: '))
    b = float(input('Rate: '))
    c = int(input('Years: '))

    final = int(a+((a*b*c)/100))
    print(final)
elif start == "compound" or "Compound":
    d = float(input('Starting balance: '))
    e = float(input('Rate: '))
    f = int(input('Years: '))

    final2 = int(d*(1+(e/100))**f)
    print(final2)
else:
    d = float(input('Starting balance: '))
    e = float(input('Rate: '))
    f = int(input('Years: '))

    final3 = int(d*(1+(e/100))**f)
    print(final3)

If I input Starting balance as 5000, rate as 5, and years as six into simple it gives 6500. But the same result occurs when I call compound.

A: This expression is not correct:
start == "simple" or "Simple"
should be
start == "simple" or start "Simple"
code below worked:
start = input("simple or compound: ")

if start == "simple" or start == "Simple":
    # print("simple")
    a = float(input('Starting balance: '))
    b = float(input('Rate: '))
    c = int(input('Years: '))

    final = int(a+((a*b*c)/100))
    print(final)
elif start == "compound" or start == "Compound":
    # print("compound")
    d = float(input('Starting balance: '))
    e = float(input('Rate: '))
    f = int(input('Years: '))

    final2 = int(d*(1+(e/100))**f)
    print(final2)
else:
    # print("unknown")
    d = float(input('Starting balance: '))
    e = float(input('Rate: '))
    f = int(input('Years: '))

    final3 = int(d*(1+(e/100))**f)
    print(final3)

A: Because of operator precedence
if start == "simple" or "Simple"

is evaluated as
if (start == "simple") or "Simple"

The (...) part is True if the user entered "simple", but the "Simple" part is always True.


text:
Q: How to run a software from other drives rather than the root? I downloaded the blender software from its official site and I read the installation procedure. It stated that blender can be run from any drives/partition on Ubuntu and all we must do is extract to the desired location.
But blender only runs on the root directory folder (/home for example). And I need it to run on my D drive where I have all my blend files from windows. So is there any way to run blender on any of my partitions?

A: Probably you are talking about where Blender saves/loads user files. That paths are different from application's installation directories. Blender from repos doesn't install in /home directory. It has its main executable in /usr/bin and most of its required files in /usr/share/blender.
You might want to check this: File -> User Preferences

Anyway if you want to use the version from http://www.blender.org/ and not from Ubuntu repos just extract archive contents to any folder/drive you like and launch blender's main executable blender. If it doesn't work open a Terminal and cd to the folder where you extracted the archive then:
sudo chmod +x ./blender
./blender

Linux is not Windows. The so called root partition is Linux's main filesystem and any other partitions are mounted in folders that are in the root drive. No C, D, E... drives. Just one big filesystem where you can add contents from other partitions/disk drives/USB drives by mounting them to any folder you wish. If blend files from windows refers to Blender's setup file for Windows, then you should know it's useless on any Linux.


text:
Q: GLIB D-BUS Bluetooth - How to get the file descriptor? I am using BLUEZ and GLIB/D-BUS to connect 2 Raspberry Pi (also a laptop and a Raspberry Pi).
So far I could make fair progress.
EDIT: on good advises from @ukBaz I am using a python client from my laptop, and my C code server on the Raspberry Pi.
On the "server", I can register the device with a custom service UUID and a Serial RFCOMM profile UUID, and wait for connection. Connecting with the python client works and I can see that there is a handler available (see after code below for debug output)
I'm using this code (within a dbus loop, code simplified for readability):
static void new_connection(GDBusMethodInvocation *inv)
{
    g_log(LOG_SERVER, G_LOG_LEVEL_MESSAGE, "New connection.");

    GDBusMessage *msg = g_dbus_method_invocation_get_message(inv);

    // This prints the output below this code snippet
    gchar *content = g_dbus_message_print(msg, 2);
    g_log(LOG_SERVER, G_LOG_LEVEL_INFO, "Message is:\n%s", content);
    g_free(content);
    GVariant *params = g_dbus_method_invocation_get_parameters(inv);

    const char *object;
    GVariant *properties;
    gint32 *handle;
    g_variant_get(params, "(oha{sv})", &object, &handle, &properties);

    // Problem here, 'handle' is NULL
    g_log(LOG_SERVER, G_LOG_LEVEL_INFO, "Object is [%s]\nHandle is [%ls]", object, handle);
    GVariantIter iter;
    g_variant_iter_init(&iter, properties);
    display_properties(&iter);
}

Here is the output:
New connection.
Message is:
  Type:    method-call
  Flags:   none
  Version: 0
  Serial:  32
  Headers:
    path -> objectpath '/org/bluez/jscturret'
    interface -> 'org.bluez.Profile1'
    member -> 'NewConnection'
    destination -> ':1.18'
    sender -> ':1.11'
    signature -> signature 'oha{sv}'
    num-unix-fds -> uint32 1
  Body: (objectpath '/org/bluez/hci0/dev_00_AA_AA_AA_AA_AA', handle 0, @a{sv} {})
  UNIX File Descriptors:
    fd 7: dev=0:8,mode=0140777,ino=41101,uid=0,gid=0,rdev=0:0,size=0,atime=0,mtime=0,ctime=0

Object is [/org/bluez/hci0/dev_00_AA_AA_AA_AA_AA]
Handle is [(null)]

It shows that there is a file descriptor fd 7 but when I read the GVariant parameter I get NULL.
How can I access the file descriptor? My understanding is I need that to be able to read/write from/to the client.
I used https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/device-api.txt and https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/adapter-api.txt for reference and a few other posts here on SO.
Also got a lot of info in https://www.linumiz.com/.
Current full code is available here: btservice

A: Oh! I am pretty sure you are supposed to send a pointer to an integer (not a pointer to a pointer to it).
You can do
gint32 handle; // instead of gint32 *handle;
and it should work.
This API has a very poor design (relying on variadic, with format specifiers... the reason why people dislike C).


text:
Q: Nested Objects in Bootstrap.js I'm making some improvements to a Combobox class I made to go with Bootstrap 4, and I wanted to make the Javascript match what already exists in Bootstrap.
In the process, I found some code that I don't quite understand in bootstrap.js while checking out the Modal:
var Modal = function () {
    var NAME = 'modal';
    // Other Constants

    var Modal =
    /*#__PURE__*/
    function() {
        function Modal(element, config) {
            this._config = this._getconfig(config);
            // Other Assignments
        }

        var _proto = Modal.prototype;
        // Other Prototype Assignments
    }();
}($);

My question is this: Why is var Modal = function() ... nested inside itself? What does this nested pattern accomplish? Should I use this pattern in my Combobox?

A: We use a Babel to compile our plugins in ES5 but our code source is in ES6, so for me this question should be related to Babel questions


text:
Q: Import not work when using MEF in WPF MVVM I want to do a test of MEF on WPF.
I use a project as interfaces:
// Project name MEFWpfTest.Interfaces
public interface IAppViewModel
{
    string Name { get; set; }
}

then create a new project to implement this interface:
// Project name MEFWpfTest.ViewModels
[Export("AppViewModel")]
public class AppViewModel : IAppViewModel
{
    public string Name { get; set; }
}

in App.xaml.cs, WPF project, I try to compose parts in MEF:
// Project name MEFWpfTest
public partial class App : Application
{
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        var aggregateCatalog = new AggregateCatalog();
        Assembly assembly = Assembly.GetExecutingAssembly();
        aggregateCatalog.Catalogs.Add(new AssemblyCatalog(assembly));

        var directoryPath = Path.GetDirectoryName(assembly.Location);

        if (directoryPath != null)
        {
            aggregateCatalog.Catalogs.Add(new DirectoryCatalog(directoryPath, $"MEFWpfTest.*.dll"));

        }

        CompositionContainer Container = new CompositionContainer(aggregateCatalog);
        Container.ComposeParts(this);

        MainWindow w = new MainWindow();
        w.Show();
    }
}

then in MainWindow.xaml.cs, I use a IAppViewModel to Import:
// Project name MEFWpfTest
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    [Import("AppViewModel")]
    public Interfaces.IAppViewModel AppVM { get; set; }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    { // I set a break point here.

    }
}

when I run this application, I've found that AppVM is null. It's fine when I do the same thing in One assembly.
MEFWpfTest already referenced MEFWpfTest.Interfaces and MEFWpfTest.ViewModels.
where I do wrong?

A: Compose parts on its constructor:
public MainWindow()
{
    InitializeComponent();
    Container.ComposeParts(this); // get container somehow
}

Note that importing property/field owner class automatically imports its properties/fields without explicit ComposeParts(). If AppViewModel has [Import] properties/fields, they are set automatically. You don't need to call ComposeParts(this) in the constructor of AppViewModel. ComposePart() cascades importing of the classes.


text:
Q: Ошибка System.UnauthorizedAccessException" в mscorlib.dll в приложении в win 10 Есть мое приложение. которое работает, и вот в него добавлю  механизм  записи технической информации. Система win 10, лог пишется в папку c:WI\debug\ Проблема в том, что как работает сам модуль записи я вижу все прекрасно, но лог файл всегда остается пустой. Прочитав про эту ошибку я изменил права доступа на папку на запись и чтение, нахожусь под учеткой администратора и студию запускаю с правами администратора.Но увы ошибку не могу победить. (Так же возникает вопрос. если я запускаю приложение в студии оно тоже в режиме администратора или нет, так как студия сама запущена с правами администратора.) На всякий случай вот так я делаю эту запись.
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Reflection;

namespace Utils
{

    public class DebugModule
    {
        private static bool needdebuginfo = false;
        private static bool init = false;
        public static bool NeedDebugInfo
        {
            get
            {
                if (!init)
                {
                    needdebuginfo = System.IO.Directory.Exists("c:\\WIdebug\\debug\\") || System.IO.File.Exists("c:\\WI\\debug");
                    init = true;
                }
                return needdebuginfo;
            }
            set
            {
                needdebuginfo = value;
            }
        }
        private static bool warnshowed=false;
        public static void WriteDebugMessage(Func<string> GetMessage)
        {
            try
            {
                if (NeedDebugInfo)
                {
                    if (!warnshowed)
                    {
                        warnshowed = true;
                        if (MessageBox.Show("Включен режим отладки, продолжить работу в этом режиме","Внимание!!!",MessageBoxButtons.OKCancel)==DialogResult.Cancel)
                        {
                            try {
                                System.IO.Directory.Delete("c:\\WI\\debug");
                            }
                            catch
                            { }
                            try
                            {
                                System.IO.File.Delete("c:\\WI\\debug");
                            }
                            catch { }
                            needdebuginfo = false;
                            return;
                        }
                    }
                    System.IO.File.AppendAllText("c:\\WI\\debug"
                        , string.Format("NewLine {0}@#${1}@#${2}@#${3}@#${4}@#${5}@#${6}@#${7}@#${8}@#${9}@#${10}@#${11}\r\n"
                        , SystemTime.Current.ToString("dd.MM.yyyy HH:mm:ss.fffffff")
                        , GetMessage()
                        , Environment.MachineName
                        , Environment.UserDomainName
                        , Environment.UserName
                        , Environment.Version
                        , Environment.OSVersion
                        , Environment.Is64BitProcess
                        , Environment.Is64BitOperatingSystem
                        , Environment.CurrentDirectory
                        , Application.ProductVersion
                        , Assembly.GetExecutingAssembly().GetName().Version));
                }
            }
            catch (Exception)
            {
            }
        }
        public static void WriteDebugMessage(string format,params object[] args)
        {
            WriteDebugMessage(() => { return string.Format(format, args); });
        }
        public static void WriteDebugMessage(string message)
        {
            WriteDebugMessage(() => { return message; });
        }
        public static void WriteDebugMessage(Exception e)
        {
            WriteDebugMessage("{0}",e);
        }

    }
}

A: Я подозреваю, что ошибка тут:
 System.IO.Directory.Delete("c:\\WI\\debug");

Ниже через System.IO.File.AppendAllText вы создаете файл c:\WI\debug, а пытаетесь удалить директорию.


text:
Q: cygwin exception stackdumpfile error? I have made a function that is supposed to add two numbers in a given base represented as strings together. The reverse string method referenced reverses a string and works correctly.  However, whenever I try to call this method, I receive the following error.
 0 [main] proj02 7364 cygwin_exception::open_stackdumpfile: Dumping stack trace to proj02.exe.stackdump
Any ideas as to what is causing this error and how I could fix it?
const string the_chars = "0123456789abcdefghijklmnopqrstuvwxyz";
string add_string_nums(string num1, string num2, long base)
{
    string added_num="";
    long len1 = num1.length(), len2 = num2.length(), extra = 0, temp;
    num1 = reverse_str(num1);
    num2 = reverse_str(num2);
while (len1 > len2)
    num2 += "0";
while (len2 > len1)
    num1 += "0";
num1 = reverse_str(num1);
num2 = reverse_str(num2);
for (int i = 1; i <= num1.length(); i ++)
{
   temp = the_chars.find(num2[num2.length() - i]) + the_chars.find(num2[num2.length()-i]) + extra;
   extra = 0;
   if (temp > base)
   {
       extra = 1;
       temp = temp - base;
   }
   added_num += the_chars.at(temp);
    }
    return added_num;
}
int main() {
  string s = add_string_nums("1", "12", 10);
   cout << s;
    return 0;
}

A: The immediate problem is here:
while (len1 > len2)
    num2 += "0";
while (len2 > len1)
    num1 += "0";

len1 and len2 are cached values and never change as the strings grow in size. Unless both strings are the same size, one loop will spin until the string it's modifying gets so big that the computer runs out of storage.
Solution (also removes the need to reverse the strings):
while (len1 > num2.length())
    num2 = "0" + num2;
while (len2 > num1.length())
    num1 = "0" + num1;

Couple other problems in there, but you shouldn't have any trouble finding them with a debugger.


text:
Q: Anaconda navigator is not launching after installing node js & npm After I installed the node.js and npm (using anaconda prompt which was probably wrong) Anaconda is not able to launch. I tried to uninstall it and even uninstalled python and reinstalled it. It still won't open even though I uninstalled node.js and npm. Instead of launching the navigator two "frames" are displayed in the taskbar as if the system tries to launch it. The task manager doesnt implicate that theres anything linked to anaconda or python running tho. Anaconda prompt runs fine.
Thanks in advance for any help :)


text:
Q: integral one variable out in multiple integral I have a function $\;f$: $\mathcal{R}^d\rightarrow\mathcal{R}$, and x,y,z $\in \mathcal{R}^d$ are spatial coordinate vector.
Could we express:
$\int\; f($x-z$)f($y+z$) \;d$z as a functional of $f($x+y$)$, for example $(f($x+y$))^2$


text:
Q: Correct use of arrayBaseOffset and arrayIndexScale I have defined a simple array and I want to use Unsafe.arrayBaseOffset and Unsafe.arrayIndexScale with the following snippet.
import sun.misc.Unsafe;
public class Arr
{
  public static void main(String[] args)
  {
    int [] a = new int[3];
    a[0] = 10; a[1] = 20; a[2] = 30;
    int baseOffset = Unsafe.arrayBaseOffset(a.getClass());
    int indexScale = Unsafe.arrayIndexScale(a.getClass());
  }
}

However I get these errors
Arr.java:11: non-static method arrayBaseOffset(java.lang.Class) cannot be referenced from a static context
    int baseOffset = Unsafe.arrayBaseOffset(a.getClass());
                           ^

Arr.java:12: non-static method arrayIndexScale(java.lang.Class) cannot be referenced from a static context
    int indexScale = Unsafe.arrayIndexScale(a.getClass());
                           ^

A: The arrayBaseOffset and arrayIndexScale methods are not static, so you cannot call them the way you are.  You need to do it like this:
    Unsafe u = Unsafe.getUnsafe();
    int baseOffset = u.arrayBaseOffset(a.getClass());
    int indexScale = u.arrayIndexScale(a.getClass());


text:
Q: Getting Istanbul.js to ignore the define (require.js) definition Say I have the following code:
define([
    'a'
], function(a) {
    return {
        initialize: function() {

        },

        stuff: function() {

        }
    };
});

Istanbul reports that only 1/3 functions have been tested. Which is somewhat true as I have only run a test against main.initialize.
How can I get Istanbul to ignore the function used for define callback?
Edit: Additional Gruntfile.js config
jasmine: {
    coverage: {
        src: 'src/assets/js/app/**/*.js',
        options: {
            specs: 'src/assets/js/spec/**/*Spec.js',
            host: 'http://127.0.0.1:8000/',
            template: require('grunt-template-jasmine-istanbul'),
            templateOptions: {
                //files: 'src/assets/js/app/**/*.js',
                coverage: 'bin/coverage/coverage.json',
                report: [
                    {type: 'html', options: {dir: 'src/coverage/html'}},
                    {type: 'text-summary'}
                ],
                template: require('grunt-template-jasmine-requirejs'),
                templateOptions: {
                    requireConfig: {
                        baseUrl: 'src/assets/js',
                        paths: {
                /*          'jquery': 'lib/jquery',
                            'underscore': 'lib/lodash',
                            'text': 'lib/text',
                            'i18n': 'lib/i18n',*/
                        }
                    }
                }

            },
            keepRunner: true
        }
    }
}

Edit: Example Spec
define([
    'app/main'
], function(main) {
    describe('app/main', function() {
        it('initailize should not error', function() {
            expect(main.initialize()).toBe(undefined);
        });
    });
});

A: Istanbul let's you define your own custom ignores explicitly in your code here
You may use /* istanbul ignore define */ at the top of your file to prevent define(...) from been checked.
Hope it'll help


text:
Q: Kotlin: Public getter returns immutable list but private getter should return mutable list I want my class to have a field that is return an immutable list for all public accesses but inside the object instance I want the list to be mutable so I can add elements to it.
   class GrammarParser {
    private val grammars: List<Grammar> = mutableListOf()
    get() = field.toList()
   }

Try
 class GrammarParser {
    private val _grammars: MutableList<Grammar> = mutableListOf()
    val grammars: List<Grammar>
    get() = this._grammars.toList()
   }

I tried this but am unsure if this is considered good practice?

A: In Kotlin, every MutableList<T> is also a List<T>. So, you can create a MutableList in a private field, and declare an additional field of type List that points to the same object. Inside the class, you can use the mutable reference to modify the list, and expose the List to outside.
Example:
class GrammarParser {
    private val mutableGrammars = mutableListOf<Grammar>()
    val grammars: List<Grammar> = mutableGrammars
}

In your second example, you create a copy (snapshot) of the list every time you call the getter. This means, after you call the getter and got a list, even if the _grammars is modified somewhere else, the changes will not be reflected in the read-only list view you got the reference of. This might be something you want - then what you are doing is ok. But if that's not something you are looking for, then the example I gave above will avoid the copying.


text:
Q: What should I use as a login and password while connecting to the bitcoin daemon I'm creating a pool, right now I'm trying to connect to bitcoin daemon, it responses with error "401", "HTTP Error 401 Unauthorized".
What should I enter in "login" and "password" fields?
Btw: should I ask here on maybe on https://bitcoin.stackexchange.com/? It's the same company, isn't it?

A: Do you have a bitcoin.conf file with the credentials in there? You need to make one and put it in ~/.bitcoin/


text:
Q: How to get data via Facebook api & FQL from a url (page fan) I have for example a fan page url (http://www.facebook.com/Microsoft).
I want to get via this url, data about the page - I mean name, likes, pic.. (What I can get from the table page).
I thought to do something like that:
SELECT name FROM page WHERE page_id IN (SELECT page_id FROM ?? WHERE url = http://www.facebook.com/Microsoft)

But I dont know where I can get a page_id by url.. any suggestions?
I have to use FQL

A: To get the ID from url's, use the object_url table:
SELECT id FROM object_url WHERE url = "http://www.facebook.com/Microsoft"
returns
[
  {
    "id": 20528438720
  }
]

Once you have that, you can use it to query the page using the ID.
SELECT name,pic,fan_count FROM page WHERE page_id = "20528438720"
returns
[
  {
    "name": "Microsoft",
    "pic": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/195730_20528438720_693767_s.jpg",
    "fan_count": 702319
  }
]

If you only want to query url's which are under Facebook, i.e. profiles, then use the profile table instead and get rid of the url, and use the username instead:
SELECT id,name,url,pic FROM profile WHERE username = "Intel"

[
  {
    "id": 22707976849,
    "name": "Intel",
    "url": "http://www.facebook.com/Intel",
    "pic": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/203507_22707976849_6594669_s.jpg"
  }
]


text:
Q: Adobe Air: Start native window hidden How do I open a new window as hidden? (note the visible="false")
<s:Window xmlns:fx="http://ns.adobe.com/mxml/2009"
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/mx"
      showStatusBar="false"
      resizable="false"
      visible="false">

If I declare a window this way, and then call this.open(false);, the window will quickly open and then hide, and then be reshown when I actually display it, which is quite ugly.
I want to do this to be able to load content and fit the window to that size before showing it.

A: I was able to set my application invisible (visible=false) in the preinitialize event handler of the application and set it to visible in the handleOnInvoke event handler.

A: If you don't use systemChrome, you can set initial and minimal size to zero, otherwise system header will be visible. SystemChrome also prohibits use of transparency, so I see no way to make hidden window with it.


text:
Q: Подключение библиотеки в IntelliJ IDEA Нашел библиотеку на GitHub https://github.com/processing/processing-sound
но не понимаю как подключить без jar файла, Maven не использую.

A: Как собрать написано в пункте How to build по приведенной ссылке проекта.
Там же на странице проекта, есть ссылка именуемая Github releases page, перейдя по ней выбираем нужную версию, качаем sound.zip файл, в нем есть jar'ники текущей sound библиотеки и еще двух (видимо внешних/вспомогательных/не знаю).
Затем добавляем библиотеку(-и) в свой проект - File -- Project structure -- Project settings -- Libraries, нажимаем + и выбираем библиотеки из файловой системы.


text:
Q: Using MAX() in MySQL more efficiently I am trying to get all email addresses of customers who have ordered anything with categoryID of 10 but ordered nothing this month. If they've ordered any type of categoryID this month then I don't want to include them.
I am using this query but I don't think it is very efficient, it has been running for ages.
SELECT
    contactEmail,
    (select max(orderDate) from orders o where o.customerID=orders.customerID) latestOrder
FROM orders
    WHERE categoryID='7'
group by contactEmail
    HAVING latestOrder <= '2014-04-01 00:00:00'

Is there a better way?

A: You don't need the subquery.  You already reference orders in your main query.
Something similar to this should work (not tested)
SELECT
    contactEmail,
    max(orderDate) as latestOrder
FROM orders
    WHERE categoryID='7'
group by customerID
    HAVING latestOrder <= '2014-04-01 00:00:00'

A: I think you want something like this:
SELECT contactEmail
FROM orders
group by contactEmail
HAVING max(orderDate) <= '2014-04-01 00:00:00' and
       sum(category = '10') > 0;

Note that this puts both conditions in the having clause and there is no filtering using a where clause.


text:
Q: Components of Torsion Tensor So I am trying to calculate the components $T^i\,_{j k}$ relative to a coordinate basis, of the torsion tensor defined as:
$$
\bf{T(u,v)= \nabla_{u}v-\nabla_v u-[u,v]}
$$
Or:
$$
T= T^i\,_{j k} e_i\otimes\omega^j \otimes \omega^k
$$
Now, I have read through a couple resources and found that I can find the components by evaluating my first expression on my basis vectors. I am curious why this is so and if every tensor is like this.
I should add that the $e_\alpha$ and $\omega^\beta$, are my coordinate vectors and the dual vectors (respectively).

A: If $\{e_i\}$ is a given frame then there are functions such that
$$\nabla_{e_i}e_j=\alpha_{ij}^ke_k,\quad [e_i,e_j]=c_{ij}^ke_k.$$
Then,
$$T(e_i,e_j)=\nabla_{e_i}e_j-\nabla_{e_j}e_i-[e_i,e_j]=\alpha_{ij}^ke_k-\alpha_{ji}^ke_k-c_{ij}^ke_k.$$ That is,
$$T=(\alpha_{ij}^k-\alpha_{ji}^k-c_{ij}^k)e^i\otimes e^j \otimes e_k.$$
Note that since $T$ is a tensor it is enough to compute it on a given basis (of course, this works for any tensor). If you want to evaluate it at $u=u^ie_i,v=v^je_j$ you have
$$T(u,v)=u^iv^jT(e_i,e_j),$$ since, as I have said, it is a tensor.