I want to update/delete the data in sqlite by using Push Notifications android

Question: I want to update/delete the record in my sqlite table using notifications, but when i send push notification from firebase, it is only updating/deleting when the app us opened, but when i close the app and pass the notification it is not updating/deleting the record
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    Context mycontext;
    private static final String ACTION_DESTINATION = "action_destination";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
       // Db_Controller controller = new Db_Controller(getApplicationContext());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            Map<String, String> data = remoteMessage.getData();

            handleData(data);
        } else if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            Map<String, String> data = remoteMessage.getData();
            handleNotification(remoteMessage.getNotification());
        }// Check if message contains a notification payload.

        Db_Controller dataBaseHelper = new Db_Controller(getApplicationContext()); //my database class
        dataBaseHelper.getWritableDatabase();
        dataBaseHelper.allexecutequery("UPDATE users SET name='"+remoteMessage.getNotification().getBody()+"' WHERE id_user='"+1+"'"); //from here i am updating/deleting data.
        dataBaseHelper.close();

    }

    private void handleNotification(RemoteMessage.Notification RemoteMsgNotification) {

        String message = RemoteMsgNotification.getBody();
        String title = RemoteMsgNotification.getTitle();
        notification_class notificationVO = new notification_class();
        notificationVO.setTitle(title);
        notificationVO.setMessage(message);

        Intent resultIntent = new Intent(getApplicationContext(), users_class.class);
        NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.displayNotification(notificationVO, resultIntent);
        notificationUtils.playNotificationSound();

    }

    private void handleData(Map<String, String> data) {

        String title = data.get(TITLE);
        String message = data.get(MESSAGE);
        String iconUrl = data.get(IMAGE);
        String action = data.get(ACTION);
        String actionDestination = data.get(ACTION_DESTINATION);
        notification_class notificationVO = new notification_class();
        notificationVO.setTitle(title);
        notificationVO.setMessage(message);

        Intent resultIntent = new Intent(getApplicationContext(), users_class.class);

        NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.displayNotification(notificationVO, resultIntent);
        notificationUtils.playNotificationSound();

    }

}

Comment: Notification messages are delivered to your onMessageReceived callback only when your app is in the foreground. So  when you close the app and pass the notification it is not updating/deleting the record.
Comment: so in that case what to do? @Kabir
Comment: Use WakefulBroadcastReceiver .Try to perform update/delete operation of database inside onReceive method of WakefulBroadcastReceiver.
Comment: But WakefulBroadcastReceiver Deprecated in API level 26.1.0.As of Android O, background check restrictions make this class no longer generally useful. (It is generally not safe to start a service from the receipt of a broadcast, because you don't have any guarantees that your app is in the foreground at this point and thus allowed to do so.) Instead, developers should use android.app.job.JobScheduler to schedule a job, and this does not require that the app hold a wake lock while doing so (the system will take care of holding a wake lock for the job).
Comment: basically i want to update/delete my data when any changes happen in mysql through push notifications, how can i do this?
Comment: Meke a broadcast receiver : below is code:
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
}
Comment: and what to do inside OnReceive() funtion?
Comment: Inside onReceve method: you can get push notification data like this:intent.getExtras().get("message"));
     -->Then perform update/delete code of database.
Comment: should i also pass parameters from onMessageReceived() to onReceve() and call  onReceve() in onMessageReceived() function?
Comment: I just shared example code in answer section.
Answer: You can do like this:
public class FirebaseDataReceiver extends WakefulBroadcastReceiver {
    private Context context;
    PendingIntent pendingIntent;
    DbHelper dbHelper;
    @Inject
    MySharedPreferences mySharedPreferences;

    String userId;

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

            if (intent.getExtras().get("message") != null && intent.getExtras().get("title") != null && intent.getExtras().get("requestid") != null) {

                dbHelper = new DbHelper(context);
                dbHelper.insertNotification(intent.getExtras().get("message").toString(), intent.getExtras().get("title").toString(), intent.getExtras().get("requestid").toString(), userId);

                Intent intent1 = new Intent(context, LoginPanelActivity.class);
                intent1.putExtra("Data", "1");
                intent1.putExtra("requestidkey", intent.getExtras().get("requestid").toString());
                intent1.putExtra("messagekey", intent.getExtras().get("message").toString());

                intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                pendingIntent = PendingIntent.getActivity(context, 0, intent1, PendingIntent.FLAG_ONE_SHOT);

                if (!FileUtils.isAppIsInBackground(context)) {
                    showNotification(intent.getExtras().get("message").toString(), intent.getExtras().get("title").toString());
                }

            }
        }
    }

    private void showNotification(String message, String title) {
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                R.mipmap.ic_launcher);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "com.xyz";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, context.getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_DEFAULT);
            AudioAttributes attributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();
            notificationChannel.setDescription("Xyz App");
            notificationChannel.enableLights(true);
            notificationChannel.setShowBadge(true);
            notificationChannel.setLightColor(Color.BLUE);
            notificationChannel.setSound(defaultSoundUri, attributes); // This is IMPORTANT
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            if(notificationManager!=null) {
                notificationManager.createNotificationChannel(notificationChannel);

            }

        }
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);

        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                .setContentTitle(title)
                .setContentText(title)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(icon)
                .setColor(context.getResources().getColor(R.color.blackColor))
                .setContentInfo("Info")
                 .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        notificationManager.notify(new Random().nextInt(), notificationBuilder.build());

    }

}

And register your receiver in Manifest file:
<receiver
            android:name=".service.FirebaseDataReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </receiver>

Answer: You can create worker and schedule deletion:
public class ClearDbWorker extends Worker {

    public ClearDbWorker(
        @NonNull Context context,
        @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {
      Db_Controller dataBaseHelper = new Db_Controller(getApplicationContext()); //my database class
        dataBaseHelper.getWritableDatabase();
        dataBaseHelper.allexecutequery("UPDATE users SET name='"+remoteMessage.getNotification().getBody()+"' WHERE id_user='"+1+"'"); //from here i am updating/deleting data.
        dataBaseHelper.close();

      // Indicate whether the task finished successfully with the Result
      return Result.success()
    }
}

After creating worker class, you can add following code to MyFirebaseMessagingService.onMessageReceived enqueue deletion:
OneTimeWorkRequest clearDbWorkRequest = new OneTimeWorkRequest.Builder(ClearDbWorker.class)
        .build()
WorkManager.getInstance().enqueue(clearDbWorkRequest);

Don't for get to add following dependencies:
dependencies {
    def work_version = "2.1.0"

    // (Java only)
    implementation "androidx.work:work-runtime:$work_version"
}


How to prove SPRT terminates with probability unity?

Question: Can anyone provide me the easily explainable proof of 'SPRT terminates with probability unity'?
To be more specific- 'Prove that SPRT terminates with probability unity'
Answer: SPRT terminates at the $N$-th trial where $$N:=\min\left\{n\in \mathbb Z^{> 0}\big | \sum_{i=1}^n z_i~\geq \ln A ~\lor~\leq \ln B\right\} .\tag 1$$ Then it is needed to prove
$$ \mathbb P\{N<\infty\} =1.\tag 2$$ Define $c = \ln A-\ln B.$
Let $\zeta_k$ be the sum of $z_i$ in the $k$-th segment of length $r$ comprising of elements ranging from $\overline{k-1}~r+1$ to $kr.$ So, if SPRT never terminates, then
$$ |\zeta_k| < c ~~~\forall~ k ~\in \mathbb Z^{>0}. \tag 3$$
Note each $\zeta_k$ follow the same distribution.
Define $$Q_r := \mathbb P\{|\zeta_1|< c\}.\tag 4$$
Now, for $t\in \mathbb Z^{>0}, $
\begin{align}\mathbb P\{N >   t+r\} &= \mathbb P\left\{\ln B < \sum_{i=1}^j z_i<\ln A, ~\forall ~j \in S_{t+r+1}\right\}\\ & \leq \mathbb P\left\{\ln B < \sum_{i=1}^j z_i<\ln A, ~\forall ~j \in S_{t+1}~\land~j\in \{t+r\}\right\}\\ &= \mathbb P\left\{\ln B < \sum_{i=1}^j z_i<\ln A, ~\forall ~j \in S_{t+1}\right\}\times \mathbb P\left\{\left|\sum_{i= t+1}^{t+r} z_i\right|< c\right\}\\ &= \mathbb P\left\{\ln B < \sum_{i=1}^j z_i<\ln A, ~\forall ~j \in S_{r+1}\right\}\times \underbrace{\mathbb P\{|\zeta_1| < c\}}_{=~Q_r}\\ &= \mathbb P\{N> t\}~Q_r.\tag 5\label 5\end{align}
Consider $t = (k-1)~ r, ~~k\in\mathbb Z^{>0}\setminus\{1\}. $ Then, using $\eqref 5,$ recursively it can be shown \begin{align}\mathbb P\{N> kr\}&\leq \mathbb P\{N > (k-1) ~r\}~Q_r\\ &\vdots \\&\leq Q_r^{k-1}.\tag 6\label 6\end{align}
Now for a certain $s\in \mathbb Z^{>0}, $ by Archimedean Property, one can find the largest $k\in \mathbb Z^{>0}$ such that $s > kr. $ Then, by $\eqref{6}, $
$$ \begin{align}\mathbb P\{N > s \} &\leq \mathbb P\{N > kr\}\\&\leq Q_r^{k-1}.\tag 7\end{align}$$
Therefore, it suffices to prove that $Q_r < 1.$
WLOG, assume $\mathbb P\{z_i> 0\}>0;$ therefore for very large $r,~\mathbb P\{z_i> c/r\}> 0.$
Now,
\begin{align}1- Q_r &= \mathbb P\{|\zeta_1|\geq c\}\\& \geq \mathbb P\{\zeta_1\geq c\}\\ &\geq \mathbb P\{z_i\geq c/r,~~\forall i\in S_{r+1}\}\\&\geq\left[ \mathbb P\{z_i\geq c/r\}\right]^r\\&> 0.\tag 8\end{align}
$\square$

References:
$[\rm I]$ Sequential Analysis, Abraham Wald, Dover Publications, $2004,$ appendix  $\rm A. 1,$ pp. $157-158.$
$\rm [II]$ Statistical Inference, M. Rajagopalan, P. Dhanavanthan, PHI Learning, $2012,$ chapter $13, $ pp. $352-353.$


Why should a transverse intersection give intersection multiplicity one?

Question: My setting is that of Hartshorne chapter I ("classical varieties" over an algebraically closed field, which are irreducible [not schemes]).
Background
I've been working on problem 7.7(a) and I've hit a bit of a wall with part (a):

Problem 7.7. Let $Y$ be a variety of dimension $r$ and degree $d>1$ in $\Bbb P^n$. Let $P\in Y$ be a nonsingular point. Define $X$ to be the closure of the union of all lines $PQ$, where $Q\in Y$, $Q\neq P$.
(a) Show that $X$ is a variety of dimension $r+1$.

Clearly $X$ contains $Y$, so $X$ must be of dimension at least $r$. On the other hand, we can define a map $f$ from $(Y\setminus\{P\})\times\Bbb P^1$ to $X$ by sending $(Q,[a:b])\mapsto aQ+bP$ which surjects on to the collection of points in $X$ which are on a line $PQ$ with $Q\in Y$ and $Q\neq P$. Since $(Y\setminus\{P\})\times\Bbb P^1$ is irreducible, this shows that $X$ is irreducible, and the map is dominant, so we get an extension of function fields $k(X)\to K(Y\times\Bbb P^1)$. This shows that $\dim X \leq r+1$. So all I have to do finish the problem is to show that $X$ contains one point which isn't in $Y$. This is turning out to be harder than I expected!
Here's how I'd want to solve this problem: Pick a hyperplane $H$ through $P$ which is transverse to $Y$ (we can do this because $r<n$ by the degree assumption plus the fact that $P$ is a smooth point). Then the algebraic set $Y\cap H$ is smooth at $P$ (I can prove this via the Jacobian criteria), so there's a unique irreducible component $Z\subset Y\cap H$ through $P$. If I could prove that the intersection multiplicity along $Z$ is equal to one, I'd win: either $Y\cap H$ is reducible and I can connect $P$ with a point $Q$ on some other irreducible component and find a point in $X\setminus Y$ on the line $PQ$, or $Y\cap H=Z$, a variety of dimension $r-1$ and degree $d$, and eventually I can get it down to the case of a curve and I understand what to do in that case.
Question
Suppose $Y\subset \Bbb P^n$ is a variety of dimension $r$ and degree $d>1$, and $P$ a smooth point on $Y$. Suppose $H$ is a hyperplane through $P$ so that $Y\cap H$ is smooth at $P$ and $Y\cap H$ is irreducible. Why should $i(Y,H;Y\cap H)=1$?
My thoughts
The problem is that I feel very unsure about why or how I should be able to get this result. I'm supposed to compute the length of $(S/(I_Y+h))_\mathfrak{p}$ over the local ring $S_\mathfrak{p}$, where $\mathfrak{p}$ is the homogeneous prime ideal corresponding to the irreducible subvariety $Y\cap H$ and $h$ is a generator for the ideal of $H$. I can show that this the same as what you'd want in the affine case - that is, if we work in some standard affine patch $U$ containing $P$, I can show that the intersection multiplicity is the same as the length of $(k[Y\cap U]/(\widetilde{h}))_{\mathfrak{p}'}$ over $k[Y\cap U]_{\mathfrak{p}'}$ where $\mathfrak{p}'$ is the ideal corresponding to $Y\cap H\cap U$, but I don't see how I'm supposed to conclude this is $1$ if I know smoothness at $P$.
Edit: I've made a little progress - I can show that $f$ is in the maximal ideal of $P$ in $Y$  but not it's square, so $f$ is in the ideal of $Y\cap H$ but not it's square. I still don't see how this gives that the intersection multiplicity is one - I would need to know something along the lines of $\mathcal{O}_{Y,Y\cap H}$ having principal maximal ideal, which would mean it's a DVR? Still pretty stuck, though.
Or, if you think I'm barking up the wrong tree, is there some other way I'm supposed to finish problem 7.7(a)?
Answer: In the language of the post, the local ring of $Y\cap H\cap U$ at $P$ is $\mathcal{O}_{Y,P}/\sqrt{(f)}=k[x_1,\cdots,x_n]_{(x_1,\cdots,x_n)}/\sqrt{(I_{Y\cap U}+(f))}_{(x_1,\cdots,x_n)}$, which is the reduction of $k[x_1,\cdots,x_n]_{(x_1,\cdots,x_n)}/(I_{Y\cap U}+(f))_{(x_1,\cdots,x_n)}$. But Hartshorne's theorem I.5.1 says that this last ring is actually a regular local ring by the Jacobian criterion and therefore reduced. So this is an equality, and $\mathcal{O}_{Y\cap U,P}/\sqrt{(f)}=\mathcal{O}_{Y\cap U,P}/(f)$. By the transitivity of localization, we have that $\mathcal{O}_{Y\cap U,Z\cap U}=(\mathcal{O}_{Y\cap U,P})_{I_{Z\cap U,P}}$, so the multiplicity of $k[U]/(I_{Y\cap U}+(f))$ is one. Since this is equal to the multiplicity of the homogeneous version, we have that the intersection multiplicity is one.
Comment: Reread the question, especially the part in "my thoughts" where I talk about intersection multiplicity and length. Then it should all become clear.
Comment: How the fact $\mathcal{O}_{Y\cap U,Z\cap U}=(\mathcal{O}_{Y\cap U,P})_{I_{Z\cap U,P}}$ concludes that $k[U]/(I_{Y \cap U}+(f))$ has multiplicity 1?


Como eu faço para pegar informação das três primeiras linhas de uma table?

Question: Eu tenho uma tabela com varias linhas carregadas, porém preciso pegar informação das três primeiras linhas e armazenar em uma variável sem precisar usar a função click.Com essa informação armazenada em uma variável irei atribuir a um campo que vai carregar o gráfico, como faço isso  via script?
Comment: Podes mostrar o HTML que tens?
Answer: Não sei exatamente do que precisa, mas talvez possa começar com algo do tipo.
function le_tabela(linhas){
  var tabela = $("#tabela").find("tr");
  var matriz = new Array(linhas);
  for(var i=0;i<linhas;i++){
    var linha_tabela = tabela[i].childNodes;
    var tamanho = linha_tabela.length;
    var linha = new Array(tamanho);
    for(var j=0;j<tamanho;j++){
        linha[j] = linha_tabela[j].innerText;
    }
    matriz[i] = linha;
  }
    return matriz;
}

https://jsfiddle.net/zkgnddsj/


Error getting result from second query using variables from first query

Question: I get result from first query correctly However, when I want to use them in second query in WHERE condition I get query error 1064. If I remove WHERE it will work fine. Also,when I try to echo variables inside while in second query code it will print.the variables will not work only in WHERE in second query

<code> $queryDate = "SELECT date , time from DATES where ID = $ID";
 $result = mysqli_query($connection, $queryDate);

 if ($result->num_rows > 0) {
      while($row = $result->fetch_assoc()) {

   $date = $row['date'];
   $time = $row['time'];

   }
 }

 $queryCom = "SELECT * from DATES, BOOKING where dates.time = $time and booking.IDofFullDate= $date";
 $result1 = mysqli_query($connection, $queryCom);
 if (!$result1)
    {

     die("Query Faile".  mysqli_errno($connection));
    }

 if ($result1->num_rows >0) {
     echo $date;
     echo $time;
 }</code>
Comment: The full error message usually indicates exactly where the problem is... but you should use parameterized queries; your issue is most likely because the variables you are using in the query need delimited by `'`
Comment: What is the point of the while loop in this script? You are only ever going to run the second query on the last set of dates and times
Comment: thank Uueerdo it works now. some time the issue will be crazy
Comment: You are getting a syntax error.  MySQL is generally case sensitive.  If your tables (DATES and BOOKING) are in upper case, then they should be upper case in the  WHERE statement.   Also, you should use some type of JOIN statement.
Answer: on your second query try this below:
<code>$queryCom = "SELECT * from DATES as dates, BOOKING as booking where dates.time = $time and booking.IDofFullDate= $date";
</code>


Tkinter: how to bind scale hotkeys?

Question: I'd like to bind Control+MouseWheelUp combination.
I tried to do so:
import tkinter as tk

root = tk.Tk()
root.bind('<Control-Button-4>',print)

This gives no reaction? Why?
Answer: Use <MouseWheel> to bind the mouse wheel:
import tkinter as tk

root = tk.Tk()
root.bind('<Control-MouseWheel>', lambda e: print('f'))

root.mainloop()

Tkinter: how to bind scale hotkeys?


Playing trombone with a beard?

Question: I've just picked up trombone, for the first time. I find it really enjoyable to play, but I'm having trouble with my beard and mustache. As far as I can tell, it doesn't affect the sound at all, but after a while playing, the area above and below my lips - at the top and bottom of the mouth piece, starts getting itchy, due to the pressure. I don't get this with trumpet, I guess because of the smaller mouth piece.
I'm wondering if anyone has any experience playing trombone (or tuba perhaps) for extended periods with a beard? Do you become accustomed to the sensation, or does it remain irritating? Do different beard lengths have different effects? Does it ever get to the point where the hair affects your sound?
Answer: Nowadays I always get a close shave before playing the tuba in a gig. I started doing this when I realized that after longer breaks from playing I had trouble getting a distinct attack and tone when I had facial hair around the lips. I also had trouble playing pedal-notes. I then experienced getting a close shave as "gaining" one or two weeks of practice, quickly eliminating most of the troubles.
Regarding your questions:
1) As I recall I did get accustomed to the sensation.
2) I remember that some shorter hair lengths - before you get the softer feel - were more   irritating.
3) As stated, at least when out of form, I experienced facial hair to have a massive negative impact on my tone and control.
However for instance Calle Jacobsson - one of Swedens premiere tubaists - has a fashionable beard around his mouth and it does not seem to affect his excellent playing or tone.
You'll have to experiment yourself. :-)
Comment: The troubles I describe are, for me, lesser on a trombone/bass trumpet or euphonium mouthpiece and non-existing on a trumpet mouthpiece.
Answer: I can't speak definitively on this since I haven't had a full beard and mustache before, but I've always made a point to keep what facial hair I do have out of the way of my mouthpiece placement. Not knowing the full magnitude of your facial hair, it's hard to make specific suggestions, but I wouldn't want a lot of hair cushioning the mouthpiece against my lips. You do need to use at least enough pressure to create an air seal between the lips and mouthpiece, and if there's hair in the way there's a possibility for irritation.
Every body is different, of course--different tolerances for irritation, different mouthpiece placement, different facial hair. Personally I use a medium-high placement, so the soul patch I had at one point didn't affect my playing.
That said, I do know a handful of trombonists who played with significant facial hair. More experienced beard owners should offer input.
Answer: I have played trombone with varying degrees of facial hair. I just trimmed the area around my lips so that I could sort of tuck the mouthpiece under my moustache in order to contact only skin for a seal. It was fairly easy, and with care to let the upper hairs grow long and hang over that area, unnoticeable. There was no real difference in my playing when I did this.
When I WASN'T careful to do that, well, then it resulted in the differences others have mentioned.
As @Ulf Åkerstedt mentioned, trumpet players won't have an issue, but tuba players might have more of an issue.
Experiment with trimming the area closest to the lips, while combing the moustache up and out of the way!
Answer: I play trombone.  I have beard and moustache. No problems.  If you DO have problems, what's more important - your trombone playing or your facial hair?
Answer: How long have you been playing trombone? I get itchy lips when I haven't played in a while. I think it's just the nerves around your mouth reacting to getting vibrated. It might not happen with the trumpet because of the smaller size.
With that said, I do find it easier to play with a shaved upper lip. More contact between the skin and the mouthpiece.

Playing trombone with a beard?


Logistic growth inflection point

Question: I have a logistic growth curve as follows:
$y = \frac{1}{(1 + ae^{-bx})}$, where x is the independent measure (x-axis) and a and b are paramaters. The inflection point of this equation is when y = 0.5.
Given that information, I need to find the x-value at y = 0.5. But this equation isn't easy to solve. I'm using the statistical language R to find these fits.
So, given the parameters a and b, how can I find the x-value at y = 0.5 (and again, I can't do things like derivatives because I am using a programming language). By the way, I did try to solve for x, but it's quite ugly and I'm not sure how to do it...
Comment: Hint: Writing the formula in the location-scale form $y = (1 + \exp(-b(x - \log(a)/b)))^{-1}$ shows that if $x_0$ is the solution when $\log(a)=0$ and $b=1$, then $x_0 + \log(a)/b$ is the general solution. Can you find $x_0$ such that $1/2 = y = 1/(1 + \exp(-x_0))$?
Answer: Solving for $x$, you get:
$$x = -\frac{1}{b} \ln\left(\frac{1-y}{ay}\right)$$
Insert $y = 0.5$ and you get:
$$x = -\frac{1}{b} \ln\left(\frac{1}{a}\right)$$
It isn't that ugly... Practice the math - I promise it will help you.
Comment: ln(-1/a)??? but "a" is positive.
Comment: @CodeGuy then that point is not on the plot. Look closely: If y equals 0.5, then (1-a*e^(-bx))=2, meaning a*e^(-bx)=-1 right? now e^(-bx) is always positive, so a has to be negative always.
Comment: oh sorry...the original function should be 1 + a...
Comment: @CodeGuy I changed the question and answer accordingly.

Logistic growth inflection point


Inserting a dotted line between articles

Question: Can anyone help on how I can insert a dotted line between articles? Currently I created it in view Global Custom text field using horizontal rule
 which gives a solid line, but I need dotted lines instead. Any idea?
Comment: Welcome to Drupal Answers :) questions about CSS are off topic here so this needs to be closed
Answer: Use CSS instead, adding a bottom border to the articles:
article { border-bottom: 1px dotted black; }

If you also want to hide the bottom border of the last element, just add:
article:last-of-type { border-bottom: none; }

It is possible depending on the theme you are using that the article contains first or last inside class tag.


I need help formating this data

Question: I have data like this
id,phonenumbers,firstname,lastname,email,birthday,gender,locale,hometown,location,link

The problem is some data is not in the format like this
000000,000000,name1,name2,email@email,1 1 1990,female,en_En,new york,USA ,new yourk,https://www.example.com

As you can see in the "local,hometown" there are 3 commas, I want to delete one of them so the data become like this
000000,000000,name1,name2,email@email,1 1 1990,female,en_En ,new york USA, new yourk,https://www.example.com

This is just an example to the problem in my data there could be more than 3 commas and different addresses
Essentially I want to load the data into excel and have it show up clean each column with the right data
Comment: Please show the data and your code that you have worked on so far
Answer: The problem is that a value is split into multiple colums when it should be in one column. If this is only possible with one column but we have a fixed number of columns before and after, then it's possible to fix it:
testdata = "000000,000000,name1,name2,email@email,1 1 1990,female,en_En,new york,USA ,new yourk,https://www.example.com"

def split(data, cols_before_addr=8, cols_after_addr=1):
    raw_cols = data.split(',')
    return  raw_cols[:cols_before_addr] \
          + ["\n".join(raw_cols[cols_before_addr:-cols_after_addr])] \
          + raw_cols[-cols_after_addr:]

print(split(testdata))

Comment: thx it works but in my data i have arabic words and i shows up like this "'ط³ط§ظ"ظ…'"

i tryed changing the encode to UTF-8 but is shows up like this

 "\xd8\xb7\xc2\xb3\xd8\xb7\xc2\xa7\xd8\xb8\xe2\x80\x9e\xd8\xb8\xe2\x80\xa6"

I need help formating this data


Stored procedure dynamic query with if

Question: I have a stored procedure in which I have to compare the values using =, <, > as a parameter and compare it with the another parameter value rating which has the value 1,2,3,4,5 but not have any idea how to do that please help.
Here is my stored procedure what I have tried so far, and I have three tables user, RatingReview and accounttype :
Create Procedure searchsp_LenderSearch
    @pAccountTypeId int =null,
    @pFirstName varchar(25)=null,
    @pLastName varchar(35)=null,
    @pZip varchar(10)=null,
    @pOperator varchar(2)=null,
    @pRating varchar(2)=null
AS
BEGIN

    SET NOCOUNT ON;
Declare @SQLQuery AS NVarchar(4000)
    SET @SQLQuery=
  'select
   at.AccountName,
   U.UserId,
   U.FirstName,
   U.LastName,
   U.NMLS,
   U.[Address],
   U.PrimaryEmailId As Office,
   U.AdditionalEmail As Personal,
   U.DirectPhone As Work,
   U.Mobile,
   R.RatingStar

    from [User] U
    left outer join  RatingReview R   on R.UserId =U.UserId
    left outer join AccountType at on at.AccountTypeId = U.AccountTypeId
  where U.Deleted =0
  AND at.AccountTypeId = '+CAST(@pAccountTypeId as Varchar(10))+'
  AND U.FirstName = ''' + @pFirstName + '''
  AND U.LastName = ''' + @pLastName + '''
  AND U.Zip = ''' + @pZip + '''
  AND R.RatingStar = ''' + @pRating  + ''''

 IF(@pAccountTypeId  !=null OR @pAccountTypeId  != '')

    BEGIN
        SET @SQLQuery=@SQLQuery+' AND at.AccountTypeId='+CONVERT(VARCHAR, @pAccountTypeId )
    END

   IF(@pFirstName !=null OR @pFirstName != '')
    BEGIN
        SET @SQLQuery=@SQLQuery+' AND U.FirstName Like ''%' + @pFirstName + '%'''
    END

    IF(@pLastName !=null OR @pLastName != '')
    BEGIN
        SET @SQLQuery=@SQLQuery+' AND U.LastName Like ''%' + @pLastName + '%'''
    END

    IF(@pZip !=null OR @pZip != '')
    BEGIN
        SET @SQLQuery=@SQLQuery+' AND U.Zip Like ''%' + @pZip + '%'''
    END

    IF(@pRating !=null OR @pRating != '')
    BEGIN
        SET @SQLQuery=@SQLQuery+' AND R.RatingStar Like ''%' + @pRating + '%'''
    END

   IF(@pOperator = '=')
    BEGIN
    SET @SQLQuery += ' AND R.RatingStar = ' + CAST(@pRating AS NVARCHAR(5)) + ''
    END

    IF(@pOperator = '>')
        BEGIN
        SET @SQLQuery += ' AND R.RatingStar > ' + CAST(@pRating AS NVARCHAR(5)) + ''
        END

    IF(@pOperator = '<')
        BEGIN
        SET @SQLQuery += ' AND R.RatingStar < ' + CAST(@pRating AS NVARCHAR(5)) + ''
        END
        SET @SQLQuery=@SQLQuery+
  'group by
  at.AccountName,
  U.UserId,
   U.FirstName,
   U.LastName,
   U.NMLS,
   U.[Address],
   U.PrimaryEmailId,
   U.AdditionalEmail,
   U.DirectPhone,
   U.Mobile,
   R.RatingStar'

   EXEC (@SQLQuery)
END

Answer: You need to escape the parameters you pass into the query to concatenate them in the @sqlstring variable. Try this query:
Create PROCEDURE searchsp_LenderSearch
    @pAccountType int,
    @pFirstName varchar(25),
    @pLastName varchar(35),
    @pZip varchar(10),
    @pOperator varchar(2),
    @pRating int
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQLQuery AS NVarchar(4000)
    SET @SQLQuery = '
SELECT
    at.AccountTypeId,
    U.UserId,
    U.FirstName,
    U.LastName,
    R.RatingStar AS Rating,
    U.NMLS,
    U.[Address],
    U.PrimaryEmailId As Office,
    U.AdditionalEmail As Personal,
    U.DirectPhone As Work,
    U.Mobile
FROM [User] U
LEFT OUTER JOIN RatingReview R ON R.UserId = U.UserId
LEFT OUTER JOIN AccountType at ON at.AccountTypeId = U.AccountTypeId
WHERE U.Deleted = 0
  AND at.AccountTypeId = 1
  AND U.FirstName = ''' + @pFirstName + '''
  AND U.LastName = ''' + @pLastName + '''
  AND U.Zip = ''' + @pZip + ''''

IF(@pOperator = '=')
    BEGIN
    SET @SQLQuery += ' AND r.ratingstar = ' + CAST(@pRating AS NVARCHAR(5)) + ''
    END
IF(@pOperator = '<')
    BEGIN
    SET @SQLQuery += ' AND r.ratingstar < ' + CAST(@pRating AS NVARCHAR(5)) + ''
    END
IF(@pOperator = '>')
    BEGIN
    SET @SQLQuery += ' AND r.ratingstar > ' + CAST(@pRating AS NVARCHAR(5)) + ''
    END

SET @SQLQuery += '
GROUP BY
    at.AccountTypeId,
    U.UserId,
    U.FirstName,
    U.LastName,
    U.NMLS,
    U.[Address],
    U.PrimaryEmailId,
    U.AdditionalEmail,
    U.DirectPhone,
    U.Mobile,
    R.RatingStar'
EXEC (@SQLQuery)
END

The code above will generate a query like:
SELECT
    at.AccountTypeId,
    U.UserId,
    U.FirstName,
    U.LastName,
    R.RatingStar AS Rating,
    U.NMLS,
    U.[Address],
    U.PrimaryEmailId As Office,
    U.AdditionalEmail As Personal,
    U.DirectPhone As Work,
    U.Mobile
FROM [User] U
LEFT OUTER JOIN RatingReview R ON R.UserId = U.UserId
LEFT OUTER JOIN AccountType at ON at.AccountTypeId = U.AccountTypeId
WHERE U.Deleted = 0
  AND at.AccountTypeId = 1
  AND U.FirstName = 'John'
  AND U.LastName = 'Adams'
  AND U.Zip = '100AA' AND r.ratingstar > 1
GROUP BY
    at.AccountTypeId,
    U.UserId,
    U.FirstName,
    U.LastName,
    U.NMLS,
    U.[Address],
    U.PrimaryEmailId,
    U.AdditionalEmail,
    U.DirectPhone,
    U.Mobile,
    R.RatingStar

if executed like exec searchsp_LenderSearch 1, 'John', 'Adams', '100AA', '>',1
I think this is what you want. Obviously you might want to add some error checking and validation of parameters etc.
As requested here is an updated version of the query changed to match the updated question:
Create Procedure searchsp_LenderSearch
    @pAccountTypeId int       = null,
    @pFirstName varchar(25) = null,
    @pLastName      varchar(35) = null,
    @pZip           varchar(10) = null,
    @pOperator      varchar(2)  = null,
    @pRating        varchar(2)  = null
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQLQuery AS NVarchar(4000)
    SET @SQLQuery ='
SELECT
    at.AccountName,
    U.UserId,
    U.FirstName,
    U.LastName,
    U.NMLS,
    U.[Address],
    U.PrimaryEmailId As Office,
    U.AdditionalEmail As Personal,
    U.DirectPhone As Work,
    U.Mobile,
    R.RatingStar
FROM [User] U
LEFT OUTER JOIN RatingReview R ON R.UserId = U.UserId
LEFT OUTER JOIN AccountType at ON at.AccountTypeId = U.AccountTypeId
WHERE U.Deleted = 0
 '
IF(@pAccountTypeId  !=null OR @pAccountTypeId  != '')
    BEGIN
        SET @SQLQuery += ' AND at.AccountTypeId = '+CONVERT(VARCHAR(10), @pAccountTypeId ) + ''
    END

IF(@pFirstName !=null OR @pFirstName != '')
    BEGIN
        SET @SQLQuery += ' AND U.FirstName Like ''%' + @pFirstName + '%'''
    END

IF(@pLastName !=null OR @pLastName != '')
    BEGIN
        SET @SQLQuery += ' AND U.LastName Like ''%' + @pLastName + '%'''
    END

IF(@pZip !=null OR @pZip != '')
    BEGIN
        SET @SQLQuery += ' AND U.Zip Like ''%' + @pZip + '%'''
    END

IF(@pOperator = '=')
    BEGIN
        SET @SQLQuery += ' AND R.RatingStar = ' + CAST(@pRating AS NVARCHAR(5)) + ''
    END

IF(@pOperator = '>')
    BEGIN
        SET @SQLQuery += ' AND R.RatingStar > ' + CAST(@pRating AS NVARCHAR(5)) + ''
    END

IF(@pOperator = '<')
    BEGIN
        SET @SQLQuery += ' AND R.RatingStar < ' + CAST(@pRating AS NVARCHAR(5)) + ''
    END

SET @SQLQuery += '
GROUP BY
    at.AccountName,
    U.UserId,
    U.FirstName,
    U.LastName,
    U.NMLS,
    U.[Address],
    U.PrimaryEmailId,
    U.AdditionalEmail,
    U.DirectPhone,
    U.Mobile,
    R.RatingStar'

    EXEC (@SQLQuery)
   --PRINT (@SQLQuery)
END

Comment: Thank you So much Sir @ jpw . it helps a lot
Comment: sir while implementing the above condition exec searchsp_LenderSearch 1, 'John', 'Adams', '100AA', '=',5 is working but the condition exec searchsp_LenderSearch 1, 'John', 'Adams', '100AA', '>',1 is not working . can you please help me on this
Comment: sir i have updated my question Please have a look in which exec searchsp_LenderSearch 1, 'John', 'Adams', '100AA', '=',5  this condition is working fine but when i do the same like exec searchsp_LenderSearch 1, 'John', 'Adams', '100AA', '>',1 its not showing me that record . can you please help me.
Comment: @ReshavChandanSingh I think the problem is that you have two mutually exclusive conditions since you both have `AND R.RatingStar = ''' + @pRating  + ''''` and then the dynamic chosen condition for the operator, for example `SET @SQLQuery += ' AND R.RatingStar > ' + CAST(@pRating AS NVARCHAR(5)) + ''` The conditions can't be true at the same time so I think you need to remove the first.
Comment: sir can you please please update you answer according to my updated answer, I'll be very grateful .
Comment: @ReshavChandanSingh Sure I can give it a try.
Comment: @ReshavChandanSingh I've added an updated query at the end of the answer; I removed the mutually exclusive conditions and I think it should work.
Comment: sir there is one problem i am facing that i have zip in the form of comma seprated string where i am checking the condition like
And U.Zip in ('+@pZipList+') its giving me an error when the value is null how can i avoid this please help.

Stored procedure dynamic query with if


Abrir arquivo .pas pelo explorer no win10

Question: Utilizo o Delphi 7 e após fazer a troca do windows 7 para o windows 10 (Enterprise), não estou conseguindo mais abrir arquivos do tipo .pas diretamente do Explorer.
Quando utilizo o duplo click no arquivo .pas é aberta uma nova instância do Delphi, porém sem trazer o arquivo desejado.
Já tentei abrir o arquivo executando como administrador, porém sem sucesso.
Sempre que necessário abrir um arquivo .pas preciso abrir o mesmo utilizando o OpenDialogs do próprio Delphi.
Alguém já passou por essa situação?
Comment: Você precisa colocar como Programa padrão o Delphi para abri .pas
Answer: Mudar os programas padrão no Windows 10

No menu Iniciar , selecione Configurações .
Selecione Aplicativos > Aplicativos padrão.
Role a página até o fim e clique em "Definir padrões por aplicativo"
Selecione o aplicativo padrão que você deseja definir no caso o (Delphi)  e, em seguida, escolha as Extenções .

Ps: Os aplicativos precisam estar instalados para que você possa defini-los como o padrão.
Comment: Seguindo os passos, não encontrei o Delphi na lista dos padrões por aplicativos. Ele já esta instalado a um tempo neste computador. Verificando em outro computador com Windows 10 e Delphi o mesmo não aparece também nesta lista.
Comment: você terá que adicionar deve ter lá uma opção de adicionar programa aos programas padrão. (Não estou com o win 10 aberto aqui para ver). Mais 100% de certeza que é assim para add programa padrão no win 10


What is the probability that two nodes are connected in a random graph?

Question: I have just started with the theory of random graphs. I have come across the following expression of the probability that two nodes $i$ and $j$ are connected where $k_i$ and $k_j$ are the respective node degrees and $m$ is the number of edges in the graph, according to Erdos and Renyi:
$$p_{ij}=\frac{k_ik_j}{2m-1}$$
According to my understanding, the probability should be the number of possible connections between $i$ and $j$ divided by the total number of possible connections in the graph. In that sense the numerator of the formula is obvious. Can any of you explain me the denominator or the formula as a whole?
I was consulting this lecture slides when I came across the formula in the 17th slide. The professor gave an explanation of the formula in this lecture at around 1:10:00 timestamp. However, I did not understand the concept clearly.
EDIT
I have tried to explain the expression in the following way with the help of this.
A stub of node $i$ can be connected to $2m-1$ other stubs.
The probability of a stub of node $i$ being connected to one of $k_j$ stubs is: $$\frac{k_j}{2m-1}$$ The probability that $k_i$ stubs being connected to one of $k_j$ stubs is:
$$
\frac{\overbrace{k_j+\ldots+k_j}^{k_i-times}}{2m-1} =
\frac{k_ik_j}{2m-1}
$$
Answer: Some reflections. Just from my understanding here the degrees of the nodes are fixed and connected means "adjacent".
From the video let's call $S_i$ the stubs of $i$ and $S_j$ the stubs of $j$.
Now I guess one should make the approximation:
$P(i, j \ \text{connected}) \sim \sum_{s\in S_i}P(i, j \ \text{connected via stub } s)$
I think this is an approximation because the events are not disjoints. Two nodes may be connected via multiple stubs therefore the probabilities do not simply add. Now we consider that:
$P(i, j \ \text{connected via stub } s)=\frac{k_j}{\text{Total number of stubs -1}}$
( where $-1$ is there because we cannot connect a stub to itself ). Of course $\text{"Total number of stubs $-1$"}=2m-1$.
Putting everything together, and replacing $\sum_{s\in S_i} \rightarrow k_i$, we get at least the formula you proposed.
Comment: Hi, see the edit portion in my question. Let me know if you agree on that.
Comment: before reading your link, I think you should say if you agree on what I wrote and if you think it is different from what you wrote ;)
Comment: What you wrote is basically the same as what I wrote except the approximation part. Node i has k_i stubs means node i has k_i half links say k_i1, k_i2...k_iki etc. The same can be imagined for node j. Now, k_i1 can be connected to node j in k_j ways via k_j1, k_j2,....k_jkj. Same can happen for k_i2...k_iki etc. Each possible connection is an event, right? So k_i1 connets with k_j1 is an event. k_i1 connects with k_j2 is another event. Then why ain't they disjoint events?
Comment: Two events are disjoints if they cannot happen simultaneously, and as a consequence the probability of the union is the sum of the probabilities. Actually it depends on how you define your events. But fix a,b two stubs in i and c,d two stubs in j. Than it can happen that a->c so that i, j are connected via this "event" and that c->d as well. These events can therefore happen at the same time and are therefore not disjoints in my opinion.
Comment: I think you are right. a->c and c->d both can happen simultaneously because the graph under consideration is a multigraph, so they are not disjoint events. In case of simple graph it's either a->c or c->d, but not simultaneously. So they are disjoint event. I'm satisfied with your explanation now.
Comment: Why would connected mean adjacent? Why wouldn't adjacent mean adjacent and connected mean connected? Vertices $u$ and $v$ are connected if there is a path from $u$ to $v$; they are adjacent if they are connected by a path of length one.
Answer: To add some more details to the existing answer: the formula $\frac{k_i k_j}{2m - 1}$ given describes the expected number of edges between vertex $i$ and vertex $j$: for each half-stub of vertex $i$, the probability of being connected to vertex $j$ is $\frac{k_j}{2m-1}$, and by linearity of expectation (i.e. summing over the half-stubs of vertex $i$), we obtain $\frac{k_i k_j}{2m-1}$.
Thus, this in fact is an upper bound for the probability that $i$ and $j$ are connected, since $p_{ij} = \mathbb{P}(i \sim j) = \mathbb{P}(\mathrm{Edges}(i, j) \geq 1) \leq \mathbb{E}[\mathrm{Edges}(i, j)] = \frac{k_i k_j}{2m - 1}$ by Markov's inequality.
Now in practice, this formula is probably true asymptotically, i.e. $p_{ij} = (1 + o(1)) \frac{k_i k_j}{2m - 1}$ (where we must make sense of what $n \to \infty$ means for the degree sequence). This is discussed more precisely in this answer.


how to update ext list value of pptx scatter chart

Question: Read pptx template then use new data to replace it, there is a scatter chart

associated excel data

xVal and yVal could replace successfully but how to replace C column (extList)  ?
xVal and yVal replace by below manner
final CTScatterSer ser = serList.get(0);
final CTAxDataSource xVal = ser.getXVal();
final CTNumDataSource yVal = ser.getYVal();
final CTExtension ctExtension = ser.getExtLst().getExtList().get(0);
final long ptCount = xVal.getNumRef().getNumCache().getPtCount().getVal();
for (int i = 0; i < scData.size(); i++) {
    SCNameDouble data = scData.get(i);

    CTNumVal xNumVal = ptCount > i ? xVal.getNumRef().getNumCache().getPtArray(i)
            : xVal.getNumRef().getNumCache().addNewPt();
    xNumVal.setIdx(i);
    xNumVal.setV(String.format("%.2f", data.xValue));

    CTNumVal yNumVal = ptCount > i ? yVal.getNumRef().getNumCache().getPtArray(i)
            : yVal.getNumRef().getNumCache().addNewPt();
    yNumVal.setIdx(i);
    yNumVal.setV(String.format("%.2f", data.yValue));

}

final int newSize = scData.size();
xVal.getNumRef().setF(
        replaceRowEnd(xVal.getNumRef().getF(),
                ptCount,
                newSize));
yVal.getNumRef().setF(
        replaceRowEnd(yVal.getNumRef().getF(),
                ptCount,
                newSize));

xVal.getNumRef().getNumCache().getPtCount().setVal(newSize);
yVal.getNumRef().getNumCache().getPtCount().setVal(newSize);

Comment: While updating the data the need is always updating the data in the embedded workbook and updating the data in the chart. See https://stackoverflow.com/questions/66774234/java-edit-bar-chart-in-ppt-by-using-poi/66777798#66777798 for an example using bar chart.
Comment: @AxelRichter Thanks could have scatter chart example or document?
Answer: Using current apache poi versions one should not trying manipulating charts using the low level CT... classes. There is XDDF for such cases now.
If it comes to PowerPoint charts, then the need is always updating the data in the embedded workbook and updating the data in the chart. See Java edit bar chart in ppt by using poi for an example using bar chart.
Of course a scatter chart is another case then as it not has a category axis but has two value axes. But this also can be updated using XDDF.
The biggest problem you have is the data labels. There is not full support for chart data labels in XDDF upto now. And since you are talkig about extLst and your Excel table shows the data labels in a cell range, I suspect you have set the data labels comming from a cell range. This is a new feature which was not present when Microsoft had published Office Open XML. So not even the low level CT... classes are able to support that feature.
The only way is to manipulate the XML using pure XML manupulating based on org.apache.xmlbeans.XmlObject.
The following shows this on sample of a template you seems to use according to your question.
ScatterChartSample.pptx:

Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.AreaReference;

import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumns;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;

public class PowerPointChangeScatterChartData {

 //patched version of XSSFTable.updateHeaders, see https://stackoverflow.com/questions/55532006/renaming-headers-of-xssftable-with-apache-poi-leads-to-corrupt-xlsx-file/55539181#55539181
 static void updateHeaders(XSSFTable table) {
  XSSFSheet sheet = (XSSFSheet)table.getParent();
  CellReference ref = table.getStartCellReference();

  if (ref == null) return;

  int headerRow = ref.getRow();
  int firstHeaderColumn = ref.getCol();
  XSSFRow row = sheet.getRow(headerRow);
  DataFormatter formatter = new DataFormatter();

  if (row != null /*&& row.getCTRow().validate()*/) {
   int cellnum = firstHeaderColumn;
   CTTableColumns ctTableColumns = table.getCTTable().getTableColumns();
   if(ctTableColumns != null) {
    for (CTTableColumn col : ctTableColumns.getTableColumnList()) {
     XSSFCell cell = row.getCell(cellnum);
     if (cell != null) {
      col.setName(formatter.formatCellValue(cell));
     }
     cellnum++;
    }
   }
  }
 }

 static void updateScatterChart(XSLFChart chart, Object[][] data) throws Exception {
  // get chart's data source which is a Excel sheet
  XSSFWorkbook chartDataWorkbook = chart.getWorkbook();
  String sheetName = chartDataWorkbook.getSheetName(0);
  XSSFSheet chartDataSheet = chartDataWorkbook.getSheet(sheetName);
  // current Office uses a table as data source
  // so get that table if present
  XSSFTable chartDataTable = null;
  if (chartDataSheet.getTables().size() > 0) {
   chartDataTable = chartDataSheet.getTables().get(0);
  }

  if (chart.getChartSeries().size() == 1) { // we will process only one chart data
   XDDFChartData chartData = chart.getChartSeries().get(0);
   if (chartData.getSeriesCount() == 1) { // we will process only templates having one series

    int rMin = 1; // first row (0) is headers row
    int rMax = data.length - 1;

    // column 0 is X-Values
    int c = 0;
    // set new x data
    XDDFDataSource xs = null;
    for (int r = rMin; r <= rMax; r++) {
     XSSFRow row = chartDataSheet.getRow(r); if (row == null) row = chartDataSheet.createRow(r);
     XSSFCell cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
     cell.setCellValue((Double)data[r][c]); // in sheet
    }
    xs = XDDFDataSourcesFactory.fromNumericCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c)); // in chart

    // set new x-title in sheet
    String xTitle = (String)data[0][c];
    chartDataSheet.getRow(0).getCell(c).setCellValue(xTitle); // in sheet

    // column 1 is Y-Values
    c = 1;
    // set new y data in sheet and in chart
    XDDFNumericalDataSource<Double> ys = null;
    for (int r = rMin; r <= rMax; r++) {
     XSSFRow row = chartDataSheet.getRow(r); if (row == null) row = chartDataSheet.createRow(r);
     XSSFCell cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
     cell.setCellValue((Double)data[r][c]); // in sheet
    }
    ys = XDDFDataSourcesFactory.fromNumericCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c));
    XDDFChartData.Series series1 = chartData.getSeries(0);
    series1.replaceData(xs, ys); // in chart

    // set new y-title in sheet and in chart
    String yTitle = (String)data[0][c];
    chartDataSheet.getRow(0).getCell(c).setCellValue(yTitle); // in sheet
    series1.setTitle(yTitle, new CellReference(sheetName, 0, c, true, true)); // in chart

    series1.plot();

    // column 2 is data-labels-range
    c = 2;
    // set new data labels data in sheet and in chart
    XDDFDataSource dataLabelsRangeSource = null;
    for (int r = rMin; r <= rMax; r++) {
     XSSFRow row = chartDataSheet.getRow(r); if (row == null) row = chartDataSheet.createRow(r);
     XSSFCell cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
     cell.setCellValue((String)data[r][c]); // in sheet
    }
    dataLabelsRangeSource = XDDFDataSourcesFactory.fromStringCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c)); // in chart
    updateDataLabelsRange(chart, dataLabelsRangeSource); // in chart

    // set new data-labels-title in sheet
    String descrTitle = (String)data[0][c];
    chartDataSheet.getRow(0).getCell(c).setCellValue(descrTitle); // in sheet

    // update the table if present
    if (chartDataTable != null) {
     CellReference topLeft = new CellReference(chartDataSheet.getRow(0).getCell(0));
     CellReference bottomRight = new CellReference(chartDataSheet.getRow(rMax).getCell(c));
     AreaReference tableArea = chartDataWorkbook.getCreationHelper().createAreaReference(topLeft, bottomRight);
     chartDataTable.setArea(tableArea);
     updateHeaders(chartDataTable);
    }

   }
  }
 }

 static void updateDataLabelsRange(XDDFChart chart, XDDFDataSource dataLabelsRangeSource) {
  String declareNameSpaces = "declare namespace c='http://schemas.openxmlformats.org/drawingml/2006/chart'; "
                           + "declare namespace c15='http://schemas.microsoft.com/office/drawing/2012/chart' ";
  org.apache.xmlbeans.XmlObject[] selectedObjects = chart.getCTChart().selectPath(
   declareNameSpaces
   + ".//c:ext[c15:datalabelsRange]"); // needs net.sf.saxon - Saxon-HE (Saxon-HE-10.6.jar)

  if (selectedObjects.length > 0) { // we have at least one ext containing datalabelsRange
   org.apache.xmlbeans.XmlObject ext = selectedObjects[0]; // get first ext containing datalabelsRange
   // get dataLabelsRange
   org.apache.xmlbeans.XmlObject[] datalabelsRanges = ext.selectChildren(new javax.xml.namespace.QName("http://schemas.microsoft.com/office/drawing/2012/chart", "datalabelsRange", "c15"));
   org.apache.xmlbeans.XmlObject dataLabelsRange = datalabelsRanges[0];
   // set formula
   org.apache.xmlbeans.XmlObject[] formulas = dataLabelsRange.selectChildren(new javax.xml.namespace.QName("http://schemas.microsoft.com/office/drawing/2012/chart", "f", "c15"));
   org.apache.xmlbeans.XmlObject formula = formulas[0];
   ((org.apache.xmlbeans.impl.values.XmlObjectBase)formula).setStringValue(dataLabelsRangeSource.getFormula());
   // get dlblRangeCache
   org.apache.xmlbeans.XmlObject[] dlblRangeCaches = dataLabelsRange.selectChildren(new javax.xml.namespace.QName("http://schemas.microsoft.com/office/drawing/2012/chart", "dlblRangeCache", "c15"));
   org.apache.xmlbeans.XmlObject dlblRangeCache = dlblRangeCaches[0];
   // empty the cache
   dlblRangeCache.newCursor().removeXmlContents();
   // create new cache from dataLabelsRangeSource
   org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData cache = org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData.Factory.newInstance();
   dataLabelsRangeSource.fillStringCache(cache);
   // set new cache
   dlblRangeCache.set(cache);
  }
 }

 public static void main(String[] args) throws Exception {

  String filePath = "ScatterChartSample.pptx"; // has template scatter chart
  String filePathNew = "ScatterChartSample_New.pptx";

  Object[][] data = new Object[][] { // new data 1 series, 6 x-y-values and data labels
   {"X-Values", "Y-Values", "DataLabels"}, // series title
   {0.7d, 1.7d, "aa"}, // x1
   {1.8d, 3.2d, "bb"}, // x2
   {2.6d, 2.8d, "cc"}, // x3
   {1.7d, 3.7d, "dd"}, // x4
   {2.8d, 4.2d, "ee"}, // x5
   {3.6d, 1.8d, "ff"} // x6
  };

  XMLSlideShow slideShow = new XMLSlideShow(new FileInputStream(filePath));

  XSLFChart chart = slideShow.getCharts().get(0);

  updateScatterChart(chart, data);

  FileOutputStream out = new FileOutputStream(filePathNew);
  slideShow.write(out);
  out.close();
  slideShow.close();
 }

}

Resulting ScatterChartSample_New.pptx:

Note: Tested and works using current apache poi 5.2.0.
To be able to use XPath as .//c:ext[c15:datalabelsRange] it needs net.sf.saxon - Saxon-HE (Saxon-HE-10.6.jar in my case).
And it needs poi-ooxml-full-5.2.0.jar and not only the lite version of ooxml-schemas.


git add of unstaged file succeeds, but file is not staged

Question: I have a number of files that I noticed are not in my repo.  One of those files is:
> ls -l emtProblemSet1Problem1.tex
  682  -rw-r--r--  1 pjoot  staff  3605  6 Oct 10:00 emtProblemSet1Problem1.tex

Git seems to think that the file isn't in the repo (although I am sure that I would have 'git add'ed it sometime prior to this) :
> git rm -n emtProblemSet1Problem1.tex
fatal: pathspec 'emtProblemSet1Problem1.tex' did not match any files

I can add it explicitly:
> git add emtProblemSet1Problem1.tex
> echo $?
0

but then commit doesn't think that it's been added:
> git commit emtProblemSet1Problem1.tex
error: pathspec 'emtProblemSet1Problem1.tex' did not match any file(s) known to git.

commit -a is acting no differently.
I've checked that the file in question was not in .gitignore.  I'm running on mac, not cygwin, so don't have a file name case issue.
I'm not sure what else could explain this, and don't get any errors when I attempt to do the git add, and am running it from the same directory.  I do have some submodules in my git repository, but this directory is not one of them.
EDIT: I was able to hack around this issue, by moving the files to a new directory (../tmp/), adding them in that directory, and then git mv'ing them back to the place I wanted.  I am able to 'touch foo ; git add foo ; git commit foo' and this works fine?
Answer: This appears to be a filesystem case insensitivity issue.  I'd thought that the Mac filesystem was case sensitive, but that no longer appears to be the case.
$ rm -f t T
$ echo hi > t
$ cat T
hi

It appears that I've got 'git' thinking that the file exists in a different case than it appears in 'ls', and modifications to that alternate case are showing up as unstaged.
I've been able to remove the two versions of the file by running:
git mv emtproblemSet1Problem1.tex Set1Problem1.tex

which results in two actions to be commited:
renamed:    emtproblemSet1Problem1.tex -> Set1Problem1.tex
deleted:    emtProblemSet1Problem1.tex


Issue With Configuring AppSetting Services c#

Question: I am trying to load the app settings file from my program.cs file as below:
static void Main(string[] args)
    { Setup(); }

private static IServiceProvider Setup()
    {
        var services = new ServiceCollection();

        //configuration
        var config = SetupConfigurationServices(services);

        //app services
        ConfigureApplicationServices(services, config);

        services.AddSingleton<IStartup, Startup>();
        return services.BuildServiceProvider();
    }

private static IConfigurationRoot SetupConfigurationServices(ServiceCollection services)
    {
        var builder = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        return builder.Build();
    }

private static void ConfigureApplicationServices(IServiceCollection services, IConfiguration configuration)
        {
            //configuration
            services.Configure<AppSettings>(configuration.GetSection("App"));

        }

Here is my appsettings file:
{
  "App": {
    "AppName": "Test",
    "Version": "0.1",
    "Environment": "local"
  }
}

Below is the AppSettings.cs class
public class AppSettings
    {
        public string AppName{ get; set; }
        public string Version { get; set; }
        public string Environment { get; set; }
    }

The problem I am facing here is from the 'ConfigureApplicationServices' method, when using the below piece of code
services.Configure(configuration.GetSection("App"));
I keep getting error as below:
'Cannot convert from Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action.TestProcessor.Domain.AppSettings>'

I am not sure what wrong I have been doing here. Can someone help me out with this?
Answer: Try to use services.Configure as below:
services.Configure<AppSettings>(setting =>
{
    Configuration.GetSection("App").Bind(setting);
});


Realmente é necessário criar uma propriedade que indica a foreign-key de uma relação One-To-Many?

Question: Gostaria de saber se as informações que encontrei após buscas, que resumidamente, está no link abaixo, procede:
http://www.tiselvagem.com.br/desenvolvimento/chave-estrangeira-e-associacao-independente-no-entity-framework/
Pergunta:
Em uma situação hipotética, se temos a classe Carro e a classe Marca, onde Carro tem uma Marca e Marca pode ter vários Carros (One-to-Many), o EntityFramework me obriga a criar um campo 'MarcaId' no objeto Carro, ou caso contrário, eu teria que carregar todo o objeto Marca no momento de uma inclusão/alteração de um Carro se eu não quiser utilizar um campo MarcaId ?
Motivo da pergunta:
Inclusive nos links em que encontrei esta informação, frizam que esta prática fere as boas práticas da OO. Existe uma solução melhor para estes casos?
Answer: o EntityFramework me obriga a criar um campo MarcaId no objeto Carro?
Sim. É o padrão do Framework.
Adicionalmente, você teria que adicionar uma propriedade de navegação (como abaixo) para ficar inteiramente dentro do padrão:
public virtual Marca Marca { get; set; }

eu teria que carregar todo o objeto Marca no momento de uma inclusão/alteração de um Carro?
Não. A carga de Marca é preguiçosa por padrão. É feita na propriedade de navegação que mencionei acima.
Não concordo que o padrão do Entity Framework fere práticas de OO.
...se eu não quiser utilizar um campo MarcaId?
Se você não quiser usar, não vai funcionar, simplesmente, porque você não está seguindo o padrão do Framework. MarcaId é mapeada em banco, portanto precisa existir como propriedade na classe Carro.
Sobre o tutorial
Ele tem várias imprecisões. Não recomendo se basear por ele.
Comment: Editei o trecho sobre a pergunta _eu teria que carregar todo o objeto Marca no momento de uma inclusão/alteração de um Carro?_ , não especifiquei a situação.
Comment: @JoaquimMagalhães Editei a resposta.
Comment: Pessoalmente acho muito estranho! Se já configurei a chave do objeto Marca, por que o EF me obriga a criar um campo `MarcaId` ao invés de utilizar `Marca.Id`. Estou alterando o modelo (uma representação de um conceito do mundo real) com a finalidade de atender ao framework de persistência. Obrigado pelos eslcarecimentos e desculpe-me pelas insistências... rs
Comment: @JoaquimMagalhães Porque um *Model* reflete a representação de dados do banco de dados. Se por exemplo você tem uma `DropDownList` em uma tela de edição e ela está baseada em `MarcaId` (supondo, hipoteticamente, que você pode trocar a marca do carro), não faz sentido usar `Marca.Id`. Você estaria alterando um dado de `Carro`, e não de `Marca`.
Comment: Entendo. Está mais relacionado a um _Model_ do que um _Dominio do problema_. Nesta visão faz sentido!
Comment: MVC  com Entity Framework não é DDD estrito. Ele segue algumas coisas do DDD, tanto que podemos dizer que ele implementa o DDD, mas de uma forma mais flexível.


Solving two-parameter linear recurrence with different initial values

Question: I'm looking for a method to solve the well-known recurrence ralation with different initial values. The one-parameter linear recurrence is easier. Let's take a peek:

$a_0 = \alpha$; $a_1 = \beta$; $a_{n+2} = a_{n+1} + a_n$ whenever $n \in \mathbb Z$. We can use the repertoire method to solve it. Supposing that $a_n = A(n)\alpha + B(n)\beta$, well, let's plug $a_n = F_n$ into the recurrence, where $F_n$ is the Fibonocci sequence. We derive $F_n = B(n)$. Now, let's plug $a_n = F_{n+1}$ into it. we get $A(n) + B(n) = F_{n+1}$. So $A(n) = F_{n-1}$, $B(n) = F_n$.
(Concrete Mathematics EXERCISE 5.73) $X_0 = \alpha$; $X_1 = \beta$; $X_n = (n-1)(X_{n-1}+X_{n-2})$. The repertoire method also works. We can plug the factorial function $n!$ and the subfactorial function $n! \sum_{k \le n} \frac{(-1)^k}{k!}$ into the recurrence.

Well, let's take a breather, and go on the main topic. I wonder how to solve two-parameter recurrence whose relation is well-known but with different initial values. Take an example from Concrete Mathematics:

(Concrete Mathematics EXERCISE 5.74, modified)
  $f(n,k)$ is defined when $1 \le k \le n$, and $f(n,1) = f(n,n) = n$, $f(n,k) = f(n-1,k) + f(n-1,k-1)$ for $1 < k < n$.

It is related to the binomial coefficients, because the recurrence relation is same. It can be solved with generating function, but the next one might not:

(Concrete Mathematics EXERCISE 6.16)
  $A_{n,0} = a_n [n \ge 0]$; $A_{0,k} = 0$, if $k > 0$;
  $A_{n,k} = kA_{n-1,k} + A_{n-1,k-1}$, integers $k,n$,

The recurrence relation is same as Stirling numbers of the second kind but the initial values.
The more general problem arises:
solve the recurrence $X_{n,k} = \alpha(n,k)X_{n-1,k} + \beta(n,k)X_{n-1,k-1}$, when we know that $A_{n,k}$ is a (non-degenerate) solution with special initial values.
The problem is more difficult than one-parameter recurrence because there're infinity initial values in the recurrence, so the repertoire method might not work well.
Thanks for help.
Answer: Use generating functions. Consider:
$$
a_{n + 2} = a_{n + 1} + a_n \qquad a_0, a_1 \text{ given}
$$
Define $A(z) = \sum_{n \ge 0} a_n z^n$, multiply the recurrence by $z^n$, sum over $n \ge 0$ and recognize some sums to get:
$$
\frac{A(z) - a_0 - a_1 z}{z^2}
  = \frac{A(z) - a_0}{z} + A(z)
$$
Solve for $A(z)$:
$$
A(z) = \frac{a_0 + (a_1 - a_0) z}{1 - z - z^2}
$$
This gets messy, as the denominator factors as $(1 - \tau z) (1 - \overline{\tau} z)$, where
$$
\tau = \frac{1 + \sqrt{5}}{2} \\
\overline{\tau} = \frac{1 - \sqrt{5}}{2}
$$
A way out is to remember that the Fibonacci numbers satisfy the recurrence, with $F_0 = 0$, $F_1 = 1$, and have generating function:
$$
F(z) = \frac{z}{1 - z - z^2}
$$
By Binet's formula:
$$
F_n = \frac{1}{\sqrt{5}} \left( \tau^n - \overline{\tau}^n \right)
$$
while the Lucas numbers also satisfy it, with $L_0 = 2$, $L_1 = 1$, which from the above has generating function:
$$
L(z) = \frac{2 - z}{1 - z - z^2}
$$
which gives:
$$
L_n = \tau^n + \overline{\tau}^n
$$
Either from the above, or by recognizing:
$$
\frac{1}{1 - z - z^2} = \frac{F(z) - F_0}{z}
$$
which is the generating function of the sequence $\langle F_{n + 1}\rangle$, you see that:
$$
\frac{a_0 + (a_1 - a_0) z}{1 - z - z^2}
  = a_0 \frac{F(z) - F_0}{z} + (a_1 - a_0) F(z)
$$
which gives:
$$
a_n = a_0 F_{n + 1} + (a_1 - a_0) F_n
$$
In terms of Lucas and Fibonacci numbers:
$$
A(z) = \frac{a_0}{2} (L(z) + F(z)) - (a_1 - a_0) F(z)
     = \frac{a_0}{2} L(z) - a_1 F(z) - \frac{a_0}{2} F(z)
$$
so that:
$$
a_n = \frac{a_0}{2} L_n + \frac{2 a_1 - a_0}{2} F_n
$$


Add text to input field instead of replacing it with ListView + jQuery Mobile

Question: What I am trying to accomplish:
Clicking a button adds a word to filter the jQuery Mobile ListView.
HTML:

                        Iedereen
                        LinkedIn
                        Facebook

                        Design
                        Development

Stephen Weber

You've been invited to a meeting at Filament Group in Boston, MA

Hey Stephen, if you're available at 10am tomorrow, we've got a meeting with the jQuery team.

LinkedIn

JavaScript
$(document).ready(function () {
                    $("#filterButton").delegate("a", "click", function () {
                        $("div.ui-input-search").find("input").val($(this).text());
                        $("div.ui-input-search").find("input").keyup();
                    });
});

At this moment it replaces the whole value inside the input field instead of adding it to the existing value.
http://jsfiddle.net/J4HZp/6/
Answer: $("#filterButton").delegate("a", "click", function () {
     var txt = $(this).text();
     $("div.ui-input-search").find("input").val(function(i, currentValue) {
        return currentValue + txt;
     }).trigger('keyup');
});

Comment: This is exactly what he asked for, but I would `.trigger('keyup')`. I don't really think in this scenario it's too much of an issue, but most of the time people simply want to trigger any functions attached to the event handler, and not to trigger the event it's self.
Comment: This did the job! I used .trigger('keyup') because otherwise I got the same result twice (it repeated the word). http://jsfiddle.net/J4HZp/8/


DKIM FAIL with domain null in GMail

Question: I'm getting a DKIM: FAIL with domain null error in GMail. When I go to See Original in GMail, I get dkim=fail firstname.lastname@example.com;.
In my DNS I have the following TXT Records:
DMARC TXT Entry: _dmarc v=DMARC1;p=reject;sp=reject;rf=afrf;pct=100;ruf=mailto:email@example.com;rua=mailto:firstname.lastname@example.com;ri=86400
SPF TXT Entry: example.com
v=spf1 +a +mx +ip4:70.xxx.xxx.xxx +ip4:71.xxx.xxx.xxx +ip4:72.xxx.xxx.xxx ~all

DKIM TXT Entry: _default._domainkey
v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo/HYr74H9Ty6HjTpjawYIfiDa7kOPx+0GJiw4rw7IYkfvrfrLojmGLuS4lg3NbIqYmLg9Ziz77q9vVT15ftrFB1+lTz6+Ei19b6AM8FGCJoDWRHRwB+YN0InJaFs/kPfy1SktqQI8TntPNfH2+tTOUrIT1gi8fjwSnfSkUsbNuSpIp3XrAU6pYzEjXF2h1A3UMFV+7+jLRzEvunj2YCsJ3vaifTihat+Nsw7eP5L2iAzW8b0joP3z6k/UkhUa7/35oNC4Xn1dY532irsBunMJz9QsBxIaNpepiZZkTxfglsq2RP4FWGZbiVFRDDcvsnpi4kFx3eAQtAoo+szLA70FQIDAQAB

I tested my records via https://www.mail-tester.com/spf-dkim-check and http://dkimcore.org/tools/keycheck.html and it all checks out. Public Key is 2048-bit. I read the GMail was failing DKIM with smaller keys.
I also tested it with http://unlocktheinbox.com and at the DKIM Validation Check it says:
Signature Found:    Yes
SmarterMail DKIM Test:  Failed - Bad Signature
MailBee.NET DKIM Test:  Failed - SignatureInvalid

GMail doesn't seem to have any issues with my SPF and DMARC. Here's the authentication-results for those:
spf=pass (google.com: domain of firstname.lastname@example.com designates 70.xxx.xxx.xxx as permitted sender) email@example.com;

dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=example.com

My emails are hosted/sent from http://inmotionhosting.com. My DNS is at CloudFlare.
What am I doing wrong or missing here?
Thanks!
Answer: Check the DKIM signature in the header.  The diagnostic messages seem to indicate that the domain field (d=) is empty or missing.  Ensure you are supplying your domain when you sign the emails.  The DKIM header should look something like the following:

DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed;
    d=example.com; s=201602; h=Content-Transfer-Encoding:Content-Type:
    MIME-Version:Date:Message-ID:Subject:From:To;
    bh=GUIz2zzhMS1zh+o3BSEHOEq5KPzYRRlG+wqnc7+1vNM=; b=Q0LXbOPly2f1Ns6kpuS5e6dykT
    mefOZ8WX5tzNR0jD4Mqttg9IDutAE25M3FR+1UXcnakHCIsj+ELuoqafHvu/1av6vvAhZXMudoo/V
    wz3FDWwUnOroIaDPLvSR9RgBA/SHpPL9REEpCtN5WDnWDQK4P69CygrX+zbyh60aZVhE=;
Comment: Answering to myself: the actual problem (raising a 'DKIM failing with null domain' with gmail), is that I had a masquerade map defined, rewriting FROM fields, ... I fixed by commenting it out.
Comment: Having a similar issue, gmail complains about DKIM failing with null domain, while my message headers show that `d=` is properly set: `DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=maildomain.example.com; s=default; t=1495658386; bh=...`.
Answer: Try removing quotation marks from the TXT, if you have them.
That is: replace "v=DKIM1; ..." with v=DKIM1; ... in your TXT DNS entry.
For me, this solved the topic's error message. I used Cloudflare as DNS.
I got hang of it with https://mxtoolbox.com  (dkim:example.org:mail).
With quotation marks, the tool didn't recognize the DKIM1 "TagValue" and showed "Unknown" in the "Name" column.
But, without quotation marks, that column turned into "Version" and "Description" into "The DKIM record version."
And Gmail Show original turned into "PASS with domain example.org".
Answer: Having had a similar issue today - GMail complaining about null domain, while original message reports both passing and failing DKIM, ... and the DKIM-signature header including the proper d= field, I finally found that the problem was not the signature itself, rather the message being rewritten at some point.
I used to have some smtp_generic_maps = regexp:/etc/postfix/masquerade directive, in my /etc/postfix/main.cf, rewriting the FROM address of some outbound messages.
Turns out GMail is now confirming my DKIM signature is valid, since I commented out masquerading. Pebkac. And surprised by that GMail error message: confusing, if not wrong.

DKIM FAIL with domain null in GMail


Books or articles to study different forecasting techniques for lumpy and intermittent demand

Question: I am doing a project to forecast demand for an automotive firm making spare parts. Using average demand interval (ADI) and square of the Coefficient of Variation (CV2), I have categorized product SKUs into smooth, erratic, lumpy and intermittent. There are ARIMA, exponential smoothing techniques for smooth demand. However, I am unable to find enough literature for lumpy and intermittent demand. There are 3 methods that have been mentioned in several blogs for intermittent -
1) Croston's method
2) Adjusted Croston's method
3) Bootstrap method
I am reading about these 3 methods. However, I haven't found any literature on lumpy demand forecasting.
Can some please suggest me some good books or articles to understand the different forecasting techniques for lumpy and intermittent demand (can have state space and neural networks also)? If that book or article explains the above 3 methods, it will be an added bonus for me. Thanks.
Comment: I have already gone through these articles -
1) https://medium.com/analytics-vidhya/croston-forecast-model-for-intermittent-demand-360287a17f5f
2) http://kourentzes.com/forecasting/2014/06/11/on-intermittent-demand-model-optimisation-and-selection/
3) https://kourentzes.com/forecasting/wp-content/uploads/2014/06/Kourentzes-2014-Intermittent-Optimisation.pdf
Answer: This article by Hyndman and Kostenko proposes the following schema for applying models based on the $ADI$ and $CV2$ coefficients that you have mentioned. Notice that CRO stands for the simple Croston Method and SBA for the bias adjusted version of the Croston Method.

For count data model there are three main approaches that you could consider:

Ad-hoc models. Croston model and the modified versions.
Statistical based models. Like an INARMA or GARMA models.
Regression models. Zero Inflated, Hurdle or Poisson-Tweedie Regression

Ad-hoc models can account for reducing the bias (error in the prediction) in the forecast like the SBA, but if you update the forecast only in periods of positive demand it has a negative effect for periods of highly intermittent demand, in this case the TSB model is more suitable. The INARMA model is more adecuate if you would like to consider also the lead time for inventory replenishment. Now, Zero Inflated or Hurdle Regression is more useful when you have a great amount of zeros in your data. However, the Poisson-Tweedie regression can account for zeros present, extreme values and over dispersion (the variance is greater than the expected).
To get an insight about the theory of this models, I suggest you to consider

Regression Analysis of Count Data by Colin Cameron and Pravin Trivedi.
Managing Intermittent Demand by Torben Engelmeyer.

Regarding practical implementations in R

Regression Models. This link explains how to implement them. It considers from the Poisson to the Hurdle model, also you could consider the ZIM package for Zero Inflated Models. Also tweeDESeq can be considered as an alternative for the Tweedie models.
Ad-hoc models. tsintermittent implements the Croston, SBA and TSB model.

It is important also to consider an appropiate metric for evaluating the forecast, because traditional metrics like $RMSE$ or $MAE$ tend to bias forecast in favour of zero demand forecast. Hyndman and Koehler suggest to consider the MASE as metric.
Also, the current M5 forecasting competition in Kaggle considers sku's with lot of zeros, here is a link for an example of a Tree Based Model that considers Tweedie Regression. Finally, I have provided a brief explanation of count models on this repo, I would really appreciate your comments.
Comment: Thank you for such a great explanation :). It's a great starting point for anyone. I would also like to add few more links and articles that I found helpful-
1) Blogs by Nikolaos Kourentzes -
      a) https://kourentzes.com/forecasting/?s=intermittent
      b) **Forecasting using neural network** - https://kourentzes.com/forecasting/wp-content/uploads/2014/04/paper_Intermittent_NN_Kourentzes.pdf
      c) **Forecasting using Ad-hoc models and discussion on different error methods** - https://kourentzes.com/forecasting/wp-content/uploads/2014/06/Kourentzes-2014-Intermittent-Optimisation.pdf
Comment: Other resources -
1) **General methods for intermittent forecasting** - https://www.lancaster.ac.uk/pg/waller/pdfs/Intermittent_Demand_Forecasting.pdf

2) **Intuitive and simple explanation on medium**:  https://medium.com/analytics-vidhya/croston-forecast-model-for-intermittent-demand-360287a17f5f


unable to set CONTEXTUAL FILTERS according to Raw Value from Url

Question: In my project having two type of Content Type 1) Artist and 2) Work
I have added the content for the Artist and now also i have added  the content for the Work according to Artist Name having field name (Artist field_artist    Entity reference)
On view Page i want to show the result according to the artist
http://localhost/drupal8/artists-works/robert

According to name robert i have set the CONTEXTUAL FILTERS and Relationship.but its not showing any result
when removed the filter its showing all the work content type type
How can I set CONTEXTUAL FILTERS and Relationship according to this
Answer: You need to add a relationship to the content, and use the title (or whatever field contains "robert") as the contextual filter instead.
Currently the query that's getting built is trying to find content with an ID of "robert", which won't work as nid is numeric.
Comment: i have set the Content referenced from field_artist its using in the work content type for relationship
Comment: I'm not sure what that means. You need to use the title from the field_artist relationship as the contextual filter
Comment: In work content type , i have the field for artist and  insert record according to that artist name : example "/artists" url its showing the details of all artists after click on the one of robert it redirect to this path  "/artists-works/robert" . Now i want to fetch all the work content type record according to this name "robert". Now its showing me all records of work content type ,
Comment: I can only reiterate what I said in the answer and previous comment -that's how to fix your problem


jquery keypress() event get text

Question: I want a function to be run when a keypress occurs on a text box, so I have this code:
$("input[x]").keypress(function() {
        DoX();
    })

This is working fine, but in my function I want to do something based on the text value in the textbox
var textValue = ("input[x]").val();

Now the problem here is that it lags behind by a key so if my text box says 'He' and I type an 'l', then I want my textValue to be 'Hel', but it is returning the previous value 'He' because presumably the character hasn't been put in the text box yet.
Is there a way of getting 'Hel' out of my function here?
Thanks :)
Answer: You can try to use the keyup event:
$(selector).keyup(function() {
  var textValue = $(this).val();
  DoX();
});

Answer: if you are stuck using the keypressed for some other reason (so you cannot change to keyup as suggested) then you can get the last character typed like this:
$("input[x]").keypress(function (e) {
    var c = String.fromCharCode(e.which);
    //process the single character or
    var textValue = $("input[x]").val();
    var fulltext = textValue + c;
    //process the full text

});

Comment: A word of warning after I ran into problems with this approach - it assumes the cursor is always at the end of the textbox text. For example, if you type E-S-T-Home-T, in a normal editor window you'd get "TEST", but this JS will result in "ESTT".
Comment: `("input[x]").val()` should to be: `$("input[x]").val()` or even better: `$(this).val()` or even better: `this.value`
Answer: Use onkeyup, it will show the right value.
Answer: Use setTimeout without a delay. It will run immediately after keypress event completes so you'll have the correct value of the input.
$("input[x]").keypress(function() {
  setTimeout(DoX);
});

jquery keypress() event get text


Why I Iose correlation when diff has been done?

Question: Good Morning
I'm trying to study a set of samples. In the original set there are several samples along the day.  Samples time is not regular. But I can get average of that sample and fill the gaps. So I've made a new set containing average values per hour. I've 24 samples per day on a complete year. My target is to forecast next hour before that data is measured.
Due nature of sample metrics, I think they cannot be 0 but they can be extremely little compared to the rest of samples so Naan and ceros have been reemplaced by 0.05 Quantile value.
This is the graphical look

Histogram for that values (200 bins)  is:

Next I've taken a log of every sample. There is no ceros and taking a log helps on remove trend. It does not seem having trend , but I think it could not be bad. At least peeks will be smoothed. Another way to smooth is normalizing. I do not what is better, so I got this one. Once log is taken Histogram is

It seems it is a bimodal distribution. I need to find how it affects to an arima model… But in this moment this question is parked, to keep on thinking….As far I know it could be related to a seasonality but I cannot figure out how. But any comment about it is welcome.
And now the real trouble.
This is autocorrelation_plot of the serie.

Remember there is a sample every hour So 24 per day and 8760 Samples in a year.
I'm new on this field, completely, so I ignored that result. It looks very nice.. But that's all
Next thing I did is the make an adfuller test. Pvalue is 2.7959091995853143e-22 <<<< 0.05 So it is Stationary. Isn't It?
Well not only newbe. I'am a little bit nervous too. So I try some arima models playing with values of pdq , (Every new element is included in history to calculate new forecast) . My best bet was 202 model:

Blue is original data and red  forecasting. Both are closed and MSE for this model (2,0,2) is 0.3303230211924562.
Residuals Plot is

Sligthy biased but centered. I do not know whether that bias is significative. Nother thing to inform about.
As far 202 is an ARMA these are model results
Looks Nice…  But… After that, I kept reading… and from several articles I do not remember, it seems Prediction Vs Original plot show a periodic behavior… And I'm concerned for the damped oscillator plot that acf looks. I do not Understad at all
So I got my acf plot manually

First thing:  I got better MSE with 202 rather than 101 as I think it is suggested by those graphs.  ¿I'm wrong about 101?
Second, Yes I've have Stacionality, a 24 period to be exact. Because I've a hourly sample on daily basis. So clear as water, I need to diff the serie to avoid that seasonality.
Third: Every cols in Pacf are out of the blue confident  area (it is no good true?)
If I understood correctly the way to remove seasonality is to diff, and then make the model, forecast and undiff the final result . This is the way I wanted to took
But when I differed on a lag of 24…. THERE IS NO AUTOCORRELATION. Both plots acf and pacf are plane. If I'm right, That implies I can forecast one value looking at the last day same hour but it is not true !!!. So I can try the first way but in the meantime, Why I get this result and what means. I have review every lines  and it seems there no typhos, so I think there are some things, concepts, ideas I do not get completely along this travel…
¿Who can kindly help me?
Answer: After several days... I know what happened...
So I'll answer myself for helping somebody were in similar situation.
1.- How to convert n modal to a normal distribution.
2.- Why I lost my correlation?
First the easiest and hardest question. The second. I lost correlation because I'M a COMPLETELY ROOKIE. I got the main serie differenced once by 24 lag... This implies that the 24th first elements are NAN. Plot acf and plt pacf do not work with nan's so the plot was empty. I realize that several days ago working on a different problem. Suddenly the plot was there!!!
Second question. The binormal distribution above is a 3-normal distribution. I found that result applying transforms. After that I normalized. Then I got distribution too pointy to be gaussian but with a single maximun. I think it is not a key result but it worked and I could have an arima model converged.


Network interfaces, how many can handle

Question: I got very confused about network interfaces. My laptop has only 1 network interface card with just 1 port. So I assume it is 1 mac address. When router using its routing table to route packet to my laptop it sends it to a registered mac address port. So, in theory, my pc can have "virtual interfaces" and each can have it is own IP address?
Example: Currently my pc has, Npcap adapter, Virtual box adapter, 2 blank ethernet adapters.
Question: Can I just manually create an adapter and pretend to be the second machine on the network?
Answer: You can uses the macvlan or the ipvlan interfaces, but this isn't required. You can assign the several addresses on single interface. Second way is more simple because you don't need manage multiple interfaces with overlapping subnets.

In this case the macvlan the virtual interface has own mac and ip address. If you want use this virtual interface to connect to same lan segment the configuration is not trivial. Prefer this way to connect to different subnet within single broadcast domain.

Detailed description you can find here

Assigning of multiple address from same subnet on the same interface is pretty simple:

<code>ip address add <ip2>/<prefixlen> dev <iface>
ip address add <ip3>/<prefixlen> dev <iface>
ip address add <ip4>/<prefixlen> dev <iface>
</code>
Comment: oh hi again Anton, thanks for your answer. how about creating a bottleneck ? will it cause traffic impedance?
Comment: First way require complex routing setup and theoretically can cause issues. Second way is completely safe.
Comment: if i add new interface with ip command and i have 4 physical ports on my nic, can i bind it to a specific port using that ip command?
Comment: Depends of type the virtual interface. Some types doesn't require binding to physical interface (like dummy interfaces). For other types you can specify physical interface at creation. Check `man ip-link`.

Network interfaces, how many can handle


Resizing a block on a drupal 7 website

Question: I have three blocks A, B and C on the home page on location Content Bottom. I have another block D I want to place at location A+B and I want to keep C at the same location. I will move A and B to another location on the layout. How to do that? Currently when I place block D at Content Bottom it only takes the space (and width) of block A and other two columns look Odd. Block D now shows up as a single long column. Not a developer, using Drupal for three years, always learning more about Drupal. I know a little bit about css files and css injector.
If I place block D at Tertiary Content location, it takes the whole width of the screen. It shows below the region for A, B and C.
Answer: The block widths are most likely controled by the theme CSS and it seems each block is given a third of the width of the container.
To change that and make one block take up two thirds of the container width you have to override the theme CSS. Exactly which selector and declarations to use depends on your particular case. You enter your overrides in the CSSinject or a similar module that overrides CSS through the interface.
If your theme is using floats, then you can find with your browser dev tools which selector was used to set that and the width, then use that same selector but with your own declaration override, something like:
<code>.special-region .block {
  width: 60%;
}
</code>
If the layout method isn't floats then you'll have to adjust accordingly.
One other thing to consider is that this is most likely only code for wide screens, and it should be different for mobiles. Usually the mobile styles stack blocks one on top of the other so you won't have to do anything there, but you'll have to restrict your float to the same <code>@media</code> query as used by the theme, for example:
<code>@media screen and (min-width: 900px) {
  .special-region .block {
    width: 60%;
  }
}
</code>
You can find out about which media query is being used through the browser dev tools.
Comment: Thanks for very detailed instructions. I am working on it. I may have to seek assistance.

Resizing a block on a drupal 7 website


pandas filtering column names

Question: I have this type of dataframe;
A =  ["axa","axb","axc","axd","bxa","bxb","bxc","bxd","cxa".......]
My question is I have this type of data but there are more than 350 columns and for example i need only 'c' including column names in new dataframe. How can i do that?
new dataframe columns should look like this;
B =  A[["axc","bxc","cxa","cxb","cxc","cxd","dxc","exc","fxc".......]]
Answer: Use for filter columns names with c by DataFrame.filter:
df2 = df.filter(like='c')

Or use list comprehension for filter columns names:
df2 = df[[x for x in df.columns if 'c' in x]]

Comment: filter is working very fast and good
Answer: You can do it easily using list comprehension:
new_df = df[[col for col in df.columns if 'c' in col]]

pandas filtering column names


Display a text message when wordcloud is not diplayed in shiny app

Question: In the shiny app below I display a wordcloud and a slider that sets the number of words displayed. When this number =1 (input$max==1) nothing is displayed though. So I would like to replace this wordcloud I have now ith a renderUI() that will display a message when input$max==1 and in the other cases the wordcloud will be displayed.
if(require(shiny)){
  library(wordcloud2)
  wordcloud2(data = demoFreq)

  # Global variables can go here
  n <- 1

  # Define the UI
  ui <- bootstrapPage(
    sliderInput("max",
                "Maximum Number of Words:",
                min = 1,  max = nrow(demoFreq),  value =nrow(demoFreq),step=1 ),
    uiOutput("wordcloud2ortext"),
    wordcloud2Output('wordcloud2')
  )

  # Define the server code
  server <- function(input, output) {
    output$wordcloud2 <- renderWordcloud2({
      # wordcloud2(demoFreqC, size=input$size)
      wordcloud2(demoFreq[1:input$max,])
    })
    output$wordcloud2ortext<-renderUI({
      if(input$max==1){
        "No words found"
      }
      else{
        wordcloud2(demoFreq[1:input$max,])
      }
    })
  }
  # Return a Shiny app object
  # Sys.setlocale("LC_CTYPE","chs") #if you use Chinese character
  ## Do not Run!
  shinyApp(ui = ui, server = server)
}

Answer: You just need to comment out the other output (wordcloud2Output):
if(require(shiny)) {
  library(wordcloud2)
  wordcloud2(data = demoFreq)

  # Global variables can go here
  n <- 1

  # Define the UI
  ui <- bootstrapPage(
    sliderInput(
      "max",
      "Maximum Number of Words:",
      min = 1,
      max = nrow(demoFreq),
      value = nrow(demoFreq),
      step = 1
    ),
    uiOutput("wordcloud2ortext")
    # , wordcloud2Output('wordcloud2')
  )

  # Define the server code
  server <- function(input, output) {

    output$wordcloud2 <- renderWordcloud2({
      # wordcloud2(demoFreqC, size=input$size)
      wordcloud2(demoFreq[1:input$max, ])
    })

    output$wordcloud2ortext <- renderUI({
      if (input$max == 1) {
        strong("No words found")
      }
      else{
        wordcloud2(demoFreq[1:input$max, ])
      }
    })

  }
  # Return a Shiny app object
  # Sys.setlocale("LC_CTYPE","chs") #if you use Chinese character
  ## Do not Run!
  shinyApp(ui = ui, server = server)
}


which is faster unomalizede database or third nomal form database

Question: hay im doing a dissertation on database speed as I have been told that there are a couple of company that have switched form having a third normal form layout to a single table to hold there data as i've been told that it is faster for accessing and wighting to the data.
so in my dissertation i have decided to test this by creating 3 septate databases containing the same data

with all data in 1 table
with data separated in 2 tables with relationships
with data separated in 3 tables with relationships

where i will run a query on each which will select one value and pull back the entire row and connected records.
anyway I was wondering if you could give me a any website/pages or books/jernals that would either say normalized database are faster then un-normalized
Comment: I realize you are a new user.  StackOverflow is not a site for extended sicussion -- and this question can definitely lead there.  Also, the answer to your question is "it depends on what you are doing with the database".  So, I voted to close.
Comment: It's all going to depend on load, records being returned, volume of data being returned, indexes used, etc.  Both have merit there isn't a silver bullet choice here.  CONTEXT of the problem matters so SOMETIMES 3rd normal form DB & engine is faster; othertimes de-normalized data is faster.  It just "depends".
Comment: I respectfully suggest it isn't a meaningful test, because the test you propose may return widely differing results depending upon the host database in which the test is conducted, the way table(s) within the database are optimized, how lookups are performed, how memory and queries are managed.
Answer: I have a few years experience working with highly denormalized databases in the field of Data Warehousing(you should read up on it if you want to be knowledgeable of scenarios where denormalization applies), as well as several years working with traditional applications doing OLTP.
You said that the company chose to switch to a single denormalized table because it is faster for reading and writing.  In the majority of cases, it is absolutely NOT faster for writing.  Imagine if you denormalized a region/employee table.  The region record would be duplicated thousands of times in this table.  If a single region must be changed, such as it's name, then you will be applying that update across thousands of records, when a normalized database would require only one record be updated.  This has many serious performance problems.  One, in any type of transaction, an update to a region would cause thousands of employee records to be locked in some way(depending on the type of transaction).  Snapshot transactions would consume a much larger amount of memory.  Indexes on region columns would be much larger than necessary.  You would be limited in your index optimization strategies due to only one clustered index per table.  With a normalized database, you have greater flexibility in the physical ordering of the separate tables.
The most important thing to understand, is that you cannot evaluated one use case(such as selecting a single record) and then conclude that design 1, 2, or 3 is the best.  Such a test doesn't represent a typical usage scenario.  If you are selecting single records, then most likely you are dealing with an OLTP scenario where you selecting AND likely editing single records.  In such a scenario, if your test would be extremely unrealistic if you didn't also include in your tests the most common CRUD operations:

Single inserts
Single updates
Single deletes
Thousands of concurrent operations

Also you must account for the fact that thousands of these operations will be occurring concurrently, and thus deadlocks and waiting for locks will cause the denormalized database to perform very poorly.  This is will make a huge difference when you account for that common usage scenario.
And by "single", I don't mean an entire denormalized record, I mean only the portion of it that represents an entity.  For example, updating or deleting a region, but leaving the employee portions of the record in place, which will make your code more complicated, and it will perform poorly.
The other scenario you could evaluate, instead of OLTP, is OLAP, which is a subject area of Data Warehousing.  While there are OLAP database engines that use cubes, you can implement a data warehouse using an OLTP engine, but using a denormalized design.  Usually though, you don't denormalize everything down to a single table.  Usually you have a denormalized fact table and then other tables joined to it which are also denormalized to prevent there ever being a scenario with more than one join to get from the fact table to any other data.  The usage scenario of this type of denormalized design is almost never a single record!  Usually you are aggregating a very large number of records(on order of millions) and have denormalized the structure in a way to do two things, minimize joins, and minimize record size(maximizing records per page).  Thus you get maximum throughput from your "fact" table.  There is a WHOLE LOT more to it than that.  The field of data warehousing is vast, and there's lots of things to evaluate when deciding how to denormalize your data.  The good thing is that it has just about been boiled down to a science.  Kimball's "Date Warehousing Toolkit" is a great book, although it is a little bit TOO far on the conceptual side, and won't go over implementation details.
The point being, you should recognize that there is no declaring one design as best, there are lots of hybrid designs, and there are usage scenarios that each design is tailored to.
If I were you, I would clarify my propspectus to only cover the investigation of one usage scenario, and acknowledge that there are other usage scenarios in which other database designs might perform better.  But doing a single record select does not, in my opinion, cover a complete usage scenario, that should include other common operations I listed for OLTP.
Or you could do the data warehousing usage scenario, but the problem here is that you would really need good data warehousing design skills in order to make a fair comparison.  It is very easy to denormalize a database in a way that produces poor results for even the most applicable usage scenario of aggregate reporting.
Comment: thank you AaronLS for you answere i will take a look at the book you segested


Hibernate Persistence Exception

Question: @Entity
Class A{

//assume proper annotations present
private Long id;
@OneToMany(@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List b;

//all getters and setters are present...

}

Code:
A a =//get a from data base using hibernate by id
//a contains b also
a.setId(null);
entityDao.persist(a);//line at which i am getting exception

Exception:
Caused by: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: B

When using merge instead of persist everything works fine. But i would like to know what was the problem with persist?
Answer: When you set the primary key you're making the object detached hence before you can persist the detached object you would first have to reattach the object which merge does.

Hibernate Persistence Exception