Why does a callback method needs to return something?

Question: I have never before seen such a thing, so let's say I have such listener object:
MyWhateverListener dafuqListener = new MyWhateverListener() {

  @Override
  public void onSuccessCall(String s) {
    // success call
  }

  @Override
  public void onFailCall(boolean b) {
    // fail call
  }

  @Override
  public boolean onDafuqCall(int i, boolean b) {
      // some whatever code
      return false;
  }
};

Everything fine, the appropriate method will be called back to, when some action succeedes, but what's with this return inside onDafuqCall method, why is it needed, where it will return something?
P.S. This interface is from an Android ads provider's SDK.
Comment: the method declares it returns a boolean.  What exactly is the issue?
Comment: Why minus one? The question is not as obvious as it appears.
Comment: @Radiodef the said interface is from a closed .jar file, there is no documentation explaining all the source code, I am asking in general, what is the purpose of a return inside a callback method
Comment: https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html
Comment: man, I know what a return does, but what is its purpose inside a method of a listener?
Comment: We don't know that, you should read the documentation to find out what it means.
Comment: It could be anything, surely? For example, perhaps you have the opportunity to deal with an event, but if you choose not to, you may return false. The event could then be propagated elsewhere.
Comment: In what IDE you're doing this, Intellij Idea / Android Studio? By default Intellij could return smth when you're implementing this. I think that this is what you're looking for.
Comment: @Borislav: if there is no documentation, the only way to find out it's purpose is to check the sources.
Comment: @Yuri Eclipse with Android ADT
Comment: I know that the comment is not relevant - but throw away Eclipse and use Android Studio :) BTW Intellij Idea has built-in decompiler ;)
Comment: @Yuri please don't make me swear at you :D I am gathering info and examples, and I'm preparing to make a huge Android Studio hate thread
Answer: This is really quite a normal thing. A listener/observer interface is paired with a subject/event throwing class. Often you want your listeners to be totally disconnected from the behaviour of the subject, to the extent that the subject neither knows nor cares about how many listeners are registered. This is the 'pure' pattern. And this is the most common and it makes sense for all the methods to be void, since they are called only by the subject and the subjects behaviour does not depend on its listeners.
However, sometimes it makes sense for a listener to have other methods not intended to be called by the subject, and for the listener to act as a bridge between the state of the subject and some other part of the program. One common example is making special listeners for debugging. Here you make a new listener which extends your previous listener but it also keeps track of exactly when it is called by a subject, it then has a method with a return value so that your testing code can access this state, and see exactly what that listener was doing.
Finally, it occasionally makes sense to have listeners which affect the behaviour of the subject. In this case return methods are necessary. But this is rare and not without danger, it is sometimes used e.g. to make sure that things are deleted in a chain in the right order. So you stop the chain of deletes if you failed to delete a child. It has a name, but I cannot remember exactly what this pattern is called right now.
Answer: It is quite unclear what you ask but I'll give it a shot.
Interfaces are a way to allow objects to follow a specific pattern. They come handy, for instance, when I have an interface called "Listener" and five implementations:
ActionListener, MouseListener, KeyListener, CloseListener, StateChangeListener.
If I want to have a method allowing the user to register a user, instead of having to make separate "registerListener" methods for each implementation I can have: registerListener(Listener l).
Now back to your post, Interfaces may contain methods with return values, as an example if I have an interface called Event, and it contains a method called isCanceled() that returns boolean, then if I have an implementation called "ClickEvent" and I want to check if this event (after it has been called) is canceled by anyone or anything I'll invoke the isCanceled() method and that should return a value, because it is handled by the implementing object.
So to wrap this up, the return value is needed by the piece of code that calls the listener to get information. If we look in Java interfaces and their implementations we can find a ton of examples. You can check for yourself by looking into the java.uti.List interface source and an implementation like java.util.ArrayList
More information can be obtained from the Docs:

https://docs.oracle.com/javase/tutorial/java/concepts/interface.html
https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html

EDIT #1: Here is the example explained above, represented in code:
The event interface:
package com.fillpant.examples;

public interface Event {

    public boolean isCanceled();
    public void setCanceled(boolean value);

}

The ClickEvent (that implements Event):
package com.fillpant.examples;

public class ClickEvent implements Event {

    private boolean canceled = false;

    @Override
    public boolean isCanceled() {
        return canceled;
    }

    @Override
    public void setCanceled(boolean value) {
        canceled = value;
    }

}

The place where ClickEvent is called. Here I demonstrate why the return value is needed (See the isCanceled() method):
package com.fillpant.examples;

public class EventCaller {
//This class calls an event, and all the listeners will have to handle it;

    public void callClickEvent(){
        Event e = new ClickEvent();
        for(Listener l : all_registered_listeners){//this is hypothetical, if we had listeners.
            l.event(e);
        }
        if(e.isCanceled()) return;
        else{
            //DoStuff
        }
    }

}

If you have any question don't hesitate to ask :D
Comment: I think the question is "why does a callback method need to return something?"
Comment: but where does the callback method returns that value from the 'return'?
Comment: i didnt get that sorry, Wait ill code an example for you :D
Comment: @BalkrishnaRawool exactly what I meant, you explained it more clearly
Comment: There you go! i added the example :- )
Answer: This is my understanding about the topic:
Generally Listener/call-back methods don't need to return anything and they are called in response to an event.
e.g. onClick() method of OnClickListener.
OnClickListener onClickListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        //some click handling code
    }
};

But if they are part of an event-chain then a boolean return type is used to either abort of continue the execution of events. e.g. onDrag() method from OnDragListener.
OnDragListener onDragListener = new OnDragListener() {
    @Override
    public boolean onDrag(View v, DragEvent event) {
        //some drag handling code
        return false;
    }
}

Documentation of this method says "return true if the drag event was handled successfully, or false if the drag event was not handled. Note that false will trigger the View to call its onDragEvent() handler."
so it is not very uncommon to have return in call-back/event-handling methods if they are part of chain of events. And what should be returned is part of the documentation of the API.


In music how much Research and Theories are Independent from Trends and Traditions?

Question: What i belief that in music research and theories can't be certain unlike Mathematics, Science or somewhat Engineering discipline.
I think that first any composition with/without song came first intuitively and among them some make huge impact on certain audience and that impact needed to be recreate by other composer and they do studied those already ageless composition and that's how study of music began.
and as music is very vast and diverse there are lots of area has been emerged and that's how research of music has began.
so study of music is not different from study of Trends and Traditions and Research is also mostly in fashion why this pattern or style is trend and others not with/without some scientific approach.
so wanted to know is research and study in Music is different than studying Trends and Traditions? and how much certainty in this already done research in Music till now?
Comment: Theory describes - it doesn't dictate.
Comment: It was tough in the Winter of '77… having to change to playing long-sleeve punk with wooly jumpers, after a summer of carefree t-shirt & ripped jeans.
Comment: From Piston's Counterpoint introduction (page 11, Spanish edition) "But the fundamental deficiency of virtually all traditional methods is that they are not intended to communicate knowledge of the practice of composers, but they deploy a set of instructions to write music, even though, no one can know with certainty how the Music from here to only ten years will be written " Hope this illustrates something.
Comment: I'm voting to close this question because it's a topic for discussion rather than a simple Q&A. It would be an excellent post for the chat room.
Comment: You could study "Trends and Traditions in Music" without having to do any reference to various theory schools, and vice versa.  I don't think your question reallly means much.
Comment: @CarlWitthoft It's **to me** a valid question, as it address the ponderance of dogma in musical innovation. But as Tim said "Theory describes - it doesn't dictate".
Comment: Yes `Theory Describes Don't Dictate` but how much theories are certain, on that someone could decide to stick and cover that for creation or not and its contradiction could make any negative impact or not that understanding is necessary so i did post this question here but yes its debatable thanks for your all concerns by the way.
Answer: Thanks for sharing! I take the core of your question to be: How much does musicology—"music studies"—deal in measurable, quantifiable "certainties" that can be objectively observed and impassively analyzed... and how much does it deal in culturally-constructed abstracts and intangibles, subjective frameworks that we encounter subjectively?
First, I imagine there might be plenty of mathematicians and scientists who would take fright at describing their work as "certain" (at least, the good ones!).
Second, as you point out, "music studies" are very broad, and they encompass some disciplines within the hard sciences. The study of acoustics, or of the role of music in neuroscience or other medical concerns, can be subject to the scientific method. Even there, though, the scientist collides with cultural issues quickly: acoustics leads to psychoacoustics, which gets the objective researcher into the realm of subjective perception. Studies of the effect of music on the brain must contend with various musical traditions and experiences that affect people differently.
But yes, it's true that pretty much all the rest of musicology is some form of ethnography—a review of the practices of human cultures—and musicologists do themselves, their subjects, and their audience no favors when they forget it or pretend that it is not. Some disciplines, like so-called "ethnomusicology," wear this awareness on their sleeves, and conscientiously ground their musical observations within a wholistic survey of the surrounding culture—its histories, traditions, beliefs, resources, physical cultures, environmental impact, etc. But every really good music historian and theorist, even every performer—every musicologist worth their salt—bears in mind that the music they're talking about is a cultural artifact, the product of people, peoples, histories, economics, environments, beliefs, and ideologies.
Sometimes, if the scope of a discipline is narrow enough, the parameters are taken for granted. A Beethoven specialist can sit down to discuss a symphony without having to start with "Now, to really understand this we have to understand the impact Napoleon had on Europe, and to understand that we have to look at the Hundred Years' War..." And I can take a baroque orchestra gig and expect to be told exactly what pitch and temperament we'll be tuning to and which bow to bring, but take a modern symphony gig expecting these defaults to go without saying. But anyone who, even briefly and unconsciously, confuses these shorthand assumptions for universal truths—anyone who forgets, say, that "the dominant resolves to the tonic" holds true only for a certain scope of time and culture—runs all kinds of risks when they venture into the fringes of their defined scope. If I approach the music of Heinrich Biber without an awareness of his Bohemian boyhood I might miss some of his influences. If I play the music of Manuel Quiroga without understanding the mid-century surge of Galician nationalism, I miss the significance of his Galician muñeira as a political symbol.
All of which is to say: No, the study of music is not a "science." It is, perhaps, a "soft science," but it does very little to measure and explain the universe we live in, and much more to measure and explain the human beings living in it.
But—can it deal in "certainties"? Sure. As long as the certainties are observational and ethnographic. We can observe people making music; we can observe the notes they wrote. We can say, without hesitation, how Fux conceptualized counterpoint. We can point to a collection of dots on a page and call it a "C major chord," as long as we know we're talking about an idea that was constructed along with the dots themselves. We can be just as "certain" as any history or ethnography can be: we can simply observe and report what other humans do.
Comment: Thanks for your answer its quite elaborative over musicology. I do sometime feels that the one who study music too much unable to make or compose but the one who feels and connect with music better can surely make or compose remarkable and impactful music. and the one who can follow trends and market can sell music better without even creating good composition so do had questions in mind about theories certainties. and you did explain pretty good that things in music that are observable ethnographic are certainly adaptable among all ,thanks.


Creating a Form Uploader?

Question: Sorry if this an extremely newby question but I am a beginner and still trying to learn how to navigate through the site.  Anyway, I am trying to create a form uploader.  For example, I want someone to go to their profile page, hit upload, and then a form with 5 or so fields come up where they can fill things out and then upload it to the main content page.
Here is a use case that I am thinking of:  I have a picture that my little sister drew, and I want her to add a description, the title of her picture and date it.  When I hit upload there will be a upload image field and three text fields for the title, date and description.  Then I want it to display on the homepage.
Sorry if that was a really tedious description for a really simple function.  I appreciate all the help though!  Thanks in advance for all your time and help.
Pete
Answer: The simplist way is to give your users permission to add a node. This would be done through admin/people/permissions.
To get a node to automatically appear on the front page, the publishing options for the content type need to default to 'Promoted to front page'. Set this up when you are creating your content type.
If you want to create a custom form, the method (perhaps not for newbies) is:
(1) Create a module (.INFO and .MODULE files).
(2) Implement hook_menu (in your new module) to create a url and page where the form is to reside.
(3) Add a function to render the HTML of the form using drupal_get_form.
(4) Add a form builder function and construct your form using an array called $form (see form API for details).
(5) Add a submit button at the end of your form.
(6) To make the form look the way you want it to there are several methods: (i) create a theme function to add to the elements of $form; (ii) use #prefix and #suffix properties to add additional HTML and CSS ids/classes to the rendered form; (iii) manipulate the many ids/classes, rendered by drupal_get_form, with CSS; (iv) use the #markup properties to add additional HTML and CSS ids/classes to the rendered form (not recommended).
(7) Add a validation function, if needed.
(8) Add a submit function using node_save (for nodes) and drupal_write_record (for fields) to insert your form values into the relevant database tables: node, field_data_field_my_field etc.

Creating a Form Uploader?


$x + \frac1y = y + \frac1z = z + \frac1x$, then value of $xyz$ is?

Question: If $x,y,z$ are distinct positive numbers, such that $$x + \frac1y = y + \frac1z = z + \frac1x $$ then value of $xyz$ is?
$$A)\ 4\quad  B)\ 3\quad C)\ 2\quad  D)\ 1$$
My attempt:
1.I equaled the equation to '$k$'. Using the AM-GM inequality, I found that $k>2$ (the equality does not hold because all are distinct). However, this, I couldn't put to much use.
2. For the next attempt, I substituted the values of $x$ and $y$ in terms of $z$ and $k$ in $xyz$. What I am getting is $xyz=zk^2 - k - z$. That's the farthest I could do..Please, help.
Comment: FYI: If you remove the condition that $x,y,z$ are positive, then there are infinitely many solutions of the form $(x,y,z) = (a,\tfrac{1}{1-a},\tfrac{a-1}{a})$ where $a \neq 0,1$ which all satisfy $xyz = -1$.
Comment: One of the solution which is following the above conditions is $(-1,\frac12,2)$ for which $xyz=-1$
Comment: @JimmyK4542 Nice counter example.
Comment: See wolframe alpha https://www.wolframalpha.com/input/?i=x%2B1%2Fy%3Dy%2B1%2Fz%3Dz%2B1%2Fx
Comment: $xyz$ can be $1$ or $-1$ simply because the equations are stable under transformation $x$ to $1/y$ ;$y$ to $1/x$ ;$z$ to $1/z$ . Therefore, $xyz$ is sent to $1/xyz$ by this transformation.If $xyz$ is constant, it must be that $(xyz)^2=1$ hence $xyz=1$ or $xyz=-1$
Comment: http://math.stackexchange.com/questions/2062159/if-x-frac1y-y-frac1z-z-frac1x-then-prove-x-y-z
Answer: Other answers have shown that the question is flawed. For fun, let's remove the condition that $x,y,z$ are positive, but keep the requirement that $x,y,z$ are distinct, and try to find all solutions $(x,y,z)$.
Trivially, $x,y,z \neq 0$. If we set $x+\dfrac{1}{y} = y+\dfrac{1}{z} = z + \dfrac{1}{x} = k$, for som real number $k$, then
\begin{align}
x &= k - \dfrac{1}{y}
\\
y &= k - \dfrac{1}{z}
\\
z &= k - \dfrac{1}{x}
\end{align}
If we substitute equation (3) into (2) and then substitute that into (1), we get $$x = k-\dfrac{1}{k-\dfrac{1}{k-\tfrac{1}{x}}}.$$
By unraveling this fraction, we eventually get the equation $$(k^2-1)(x^2-kx+1) = 0.$$
If $k \neq \pm 1$, then the solutions $x$ will satisfy $$x^2-kx+1 = 0 \iff x = k - \dfrac{1}{x} = z,$$ and we won't have distinctness.
If $k = 1$, then $z = 1-\dfrac{1}{x} = \dfrac{x-1}{x}$ and $y = 1-\dfrac{1}{z} = -\dfrac{1}{x-1}$.
So the solutions in this case are $(x,y,z) = \left(x,-\dfrac{1}{x-1},\dfrac{x-1}{x}\right)$, all of which satisfy $xyz = -1$.
If $k = -1$, then $z = -1-\dfrac{1}{x} = -\dfrac{x+1}{x}$ and $y = -1-\dfrac{1}{z} = -\dfrac{1}{x+1}$.
So the solutions in this case are $(x,y,z) = \left(x,-\dfrac{1}{x+1},-\dfrac{x+1}{x}\right)$, all of which satisfy $xyz = 1$.
Therefore, the only solutions where $x,y,z$ are distinct are all of the form $(x,y,z) = \left(x,-\dfrac{1}{x-1},\dfrac{x-1}{x}\right)$ for $x \neq 0,1$ or $(x,y,z) = \left(x,-\dfrac{1}{x+1},-\dfrac{x+1}{x}\right)$ for $x \neq 0,-1$. (It's easy to check that these satisfy the distinctness condition.) Also, the only possible values of $xyz$ are $\pm 1$.
Answer: By multiplying the first equation by $yz$, the second by $xz$, and the equation connecting the first and third expression by $xy$, we get
$$xyz+z = y^2z+y$$
$$xyz+x = z^2x+z$$
$$xyz+y = x^2y+x$$
Adding these three, cancelling $x+y+z$ from both sides, and dividing by $xyz$ gives $$\frac{x}{z}+\frac{y}{x}+\frac{z}{y} = 3$$
But by AM-GM, the LHS is $\ge 3$ and so we must have equality in AM-GM, meaning $\frac{x}{z} = \frac{y}{x} = \frac{z}{y}$, and so $x^2 = yz, y^2 = xz, z^2 = xy$. Dividing the first by the second gives $\frac{x^2}{y^2} = \frac{y}{x}$ and so $x^3 = y^3 \implies x=y$. Similarly, $y=z$. This contradicts that $x,y,z$ are distinct, so the question is flawed.
Answer: From the conditions we have:
$$x-y=\frac{y-z}{yz}$$ $$z-x=\frac{x-y}{xy}$$ and $$y-z=\frac{z-x}{xz}$$
Thus, $xyz=1$, but why it  holds?
Comment: but the numbers are different
Comment: @kmitov Indeed, why the value $1$ holds?
Comment: You actually get $xyz=\pm 1$ and the $-1$ happens to be excluded by the assumption of positive $x,y,z$.
Comment: There are solutions of the form $(x,y,z) = (-a,\tfrac{1}{a-1},-\tfrac{a-1}{a})$ and $(x,y,z) = (a,-\tfrac{1}{a-1},\tfrac{a-1}{a})$ for $a \neq 0,1$. These don't satisfy $x,y,z > 0$ though.
Comment: Which says that a condition $x>0$, $y>0$, $z>0$ is unnecessary!
Answer: Note that $x-y=\frac{y-z}{yz}$, $y-z=\frac{z-x}{zx}$ and $z-x=\frac{x-y}{xy}$. Multiply to give $(x-y)(y-z)(z-x)=\frac{(x-y)(y-z)(z-x)}{(xyz)^2}$. As $x$, $y$ and $z$ distinct this means $(xyz)^2=1$. As $x$, $y$ and $z$ positive we must have $xyz=1$.
Comment: This shows that $xyz$ must be either 1 or -1. You also have to show that these values can be attained.
Answer: Since there is a question,
there is an answer.
By inspection,
$x=y=z$
satisfies the equations.
Therefore
$xyz = x^3$.
But the only cube listed is
$1$,
so that must be the answer.
Meta-reasoning strikes again!
Comment: The OP has $x, y, z$ distinct positive numbers.


(Cocos2dx-v3) Android - How to solve "cocos2d.h: No such file or directory"?

Question: In terminal at my cocos2dx project directory,
I typed
$ cocos run test -p android

and comes this error log.
[armeabi-v7a] Compile++ thumb: MyGame_shared <= main.cpp
[armeabi-v7a] Compile++ thumb: MyGame_shared <= AppDelegate.cpp
[armeabi-v7a] Compile++ thumb: MyGame_shared <= HelloWorldScene.cpp
[armeabi-v7a] Compile++ thumb: MyGame_shared <= CharacterSelectScene.cpp
[armeabi-v7a] Compile++ thumb: MyGame_shared <= LanguageManager.cpp
[armeabi-v7a] Compile++ thumb: MyGame_shared <= GameMaster.cpp
[armeabi-v7a] Compile++ thumb: MyGame_shared <= Player.cpp
[armeabi-v7a] StaticLibrary  : libextension.a
In file included from jni/../../Classes/HelloWorldScene.cpp:1:0:
jni/../../Classes/HelloWorldScene.h:4:21: fatal error: cocos2d.h: No such file or directory
 #include "cocos2d.h"
                     ^
compilation terminated.
In file included from jni/hellocpp/main.cpp:1:0:
jni/../../Classes/AppDelegate.h:4:21: fatal error: cocos2d.h: No such file or directory
 #include "cocos2d.h"
                     ^
compilation terminated.
In file included from jni/../../Classes/AppDelegate.cpp:1:0:
jni/../../Classes/AppDelegate.h:4:21: fatal error: cocos2d.h: No such file or directory
 #include "cocos2d.h"
                     ^
compilation terminated.
make: *** [obj/local/armeabi-v7a/objs-debug/MyGame_shared/__/__/Classes/HelloWorldScene.o] Error 1
make: *** Waiting for unfinished jobs....
make: *** [obj/local/armeabi-v7a/objs-debug/MyGame_shared/__/__/Classes/AppDelegate.o] Error 1
make: *** [obj/local/armeabi-v7a/objs-debug/MyGame_shared/hellocpp/main.o] Error 1
In file included from jni/../../Classes/Player.cpp:9:0:
jni/../../Classes/Player.h:12:21: fatal error: cocos2d.h: No such file or directory
 #include "cocos2d.h"
                     ^
compilation terminated.
In file included from jni/../../Classes/GameMaster.cpp:9:0:
jni/../../Classes/GameMaster.h:12:21: fatal error: cocos2d.h: No such file or directory
 #include "cocos2d.h"
                     ^
compilation terminated.
make: *** [obj/local/armeabi-v7a/objs-debug/MyGame_shared/__/__/Classes/Player.o] Error 1
make: *** [obj/local/armeabi-v7a/objs-debug/MyGame_shared/__/__/Classes/GameMaster.o] Error 1
In file included from jni/../../Classes/CharacterSelectScene.cpp:9:0:
jni/../../Classes/CharacterSelectScene.h:12:21: fatal error: cocos2d.h: No such file or directory
 #include "cocos2d.h"
                     ^
compilation terminated.
make: *** [obj/local/armeabi-v7a/objs-debug/MyGame_shared/__/__/Classes/CharacterSelectScene.o] Error 1
In file included from jni/../../Classes/LanguageManager.cpp:2:0:
jni/../../Classes/LanguageManager.h:8:21: fatal error: cocos2d.h: No such file or directory
 #include "cocos2d.h"
                     ^
compilation terminated.
make: *** [obj/local/armeabi-v7a/objs-debug/MyGame_shared/__/__/Classes/LanguageManager.o] Error 1
Error running command, return code: 2.

I found the similar problem in the link
Cocos2d.h No such file or directory
But I didn't know how to
 "add the path to the folder that contains the cocos2d.h header file"

Can anyone tell me steps to solving this problem?
Answer: This is probably one of the very annoying errors that you get once you start your new life with cocos2d-x. There are a couple of things to get a check on.

Import the libcocos2dx from eclipse

Press Ctrl + N
> Android Project from Existing Code
    > yourDirectory\cocos2d-x-3.yourVersion\cocos2d\cocos\platform

Add if that does not help, you need to give absolute paths to your classes and .cpp files in Android.mk which I believe is what you need.
Expand your project list (I have assumed test is your project name)
   > test
     > jni
       > Android.mk

Replace this:
LOCAL_SRC_FILES := hellocpp/main.cpp \
                   ../../Classes/AppDelegate.cpp \
                   ../../Classes/HelloWorldScene.cpp \
                   ../../Classes/GameMaster.cpp \
                   ../../Classes/MyGame_shared.cpp \

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes

With this:
CPP_FILES := $(shell find $(LOCAL_PATH)/../../Classes -name *.cpp)
LOCAL_SRC_FILES := hellocpp/main.cpp
LOCAL_SRC_FILES += $(CPP_FILES:$(LOCAL_PATH)/%=%)
LOCAL_C_INCLUDES := $(shell find $(LOCAL_PATH)/../../Classes -type d)


Are all oval-track races done counter-clockwise? If so, why?

Question: It seems to me that every type of race on an oval track moves in a counter-clockwise direction. Off the top of my head, I know that this happens in:

auto racing of any kind
roller derby
horse racing
speed skating
running races (the 'track' part of 'track & field', I suppose)
greyhound racing

What is the history of this custom? Is there a reason all races are run counter-clockwise? Are there exceptions to this rule (if it can even be called a rule)?
Comment: Re-tagging is certainly welcome - I wasn't sure where to put this.
Comment: The important question is, do they run counter-clockwise in the northern hemisphere only, and clockwise in Australia?
Comment: The BBC just ran an article covering this point: http://www.bbc.co.uk/news/magazine-19047586
Answer: Not all tracks are counter clockwise, The exceptions being the Australian version of NASCAR (AUSCAR) and horse racing is often run clockwise outside the US such as England(St Leger - wikipedia.), Continental Europe, Australia, and Hong Kong. also some of F1 races are clockwise like .
The decision to run horses counterclockwise in the US dates to the American Revolution era. In 1780, the first circular US race track was established by William Whitley near his home in Lincoln County, Kentucky. A staunch supporter of the Revolution, Whitley insisted that horses race counterclockwise, as opposed to clockwise as was the custom at the time in England.
In IAAF (International Association of Athletics Federations)
IAAF Rule 163.1 states:

The direction of running shall be left-hand inside

iaaf
there are explanations for counterclockwise races but none is formal:

International agreement stipulating the direction related to the setting up of equipment to time the finishes and judge dead-heats (close finishes). If all running events are run in the same direction it means that it simplifies the process of setting up the equipment across different venues.
Every NASCAR oval track has only left turns, because the drivers sit on that side of the car. The drivers generally try to keep to the inside of the track (because it is a shorter distance around the track) So by making all left turns, the drivers can better see what is going on around them.
Safety reasons, keeps the driver away from the out side wall (guardrail in the old days).
that spectator will percieve the runners as moving left to right - the same direction our eyes move when we read.
the human body is slightly heavier than the right because of the heart and when running anticlockwise, the body would tend to very slightly incline towards the left, which could be an advantage while running anticlockwise
Most people are right hand/leg dominant.Moving counterclockwise we have a better control and move faster.

Read more: wiki.answers.com,   answers.yahoo.com
You can look on different interesting paper that tool about the directions types in generally and not only in sport - straightdope
Comment: The "NASCAR drivers keep to the inside" line isn't always correct. While it's true that it's shorter, NASCAR drivers don't care about shorter, they care about faster. Usually the race line is outside to inside to outside, allowing the shallowest and lowest-G turn, thus retaining the most speed. On short tracks with no restrictor plates, you'll sometimes see drivers take a very high (outside) line for the entire turn because they can just power through it faster than someone hugging the inside.
Answer: In regards to roller derby, most skaters (like most humans) are right side dominant.  That means right-footed people are more comfortable moving their right foot over their left than their left foot over their right.  Crossing a foot over another automatically changes your direction because of the weight distribution between your inner and outer wheels.  Having your right foot cross over your left makes you turn left.
This post also mentions some other reasons, but I'm not sure I buy all of them.
Answer: In my opinion, the reason for only left turn in races is as follows:
Most of the races take place in the northern hemisphere. Coriolis force affects and will naturally make water, wind, etc turn or swing in the anti-clockwise direction. Going clockwise in the northern hemisphere would be going against nature. Since racing started in the northern hemisphere a trend must have been set.
Comment: it will be nice if you can add source that will support your opinion.
Answer: NASCAR etc always turn to the left due to the centrifugal pull of the motor (the internals of the motor are always turning in that direction). If you go to the right you will be turning against the pull of your engine.  Try it for yourself in your own car. The turn of the motor will push you into the left turn . Against to the right.
Comment: On a rear wheel drive car, the torque from the engine pushes the left rear wheel down and tries to lift the right rear wheel up.  Turning left at speed puts more weight on the right wheels, thus counteracting the lifting effect from the engine and making the car more stable.  Turning right at speed would mean even less weight on the right side and a possible loss of traction.


Failed to create keys in the OLR, rc = 100 on windows server

Question: I am installing Oracle 19c RAC on windows server 2019.
I have 4 servers,
domain controller: pc name = dc
storage: pc name = st
node1: pc name = node1
node2: pc name = node2
I have done all the pre-install checks, and when I install the Grid on node1, i encountered the error below.

2023-04-29 21:47:00: Executing cmd:
C:\software\WINDOWS.X64_193000_grid_home\bin\clscfg -localadd -z  -y
nodecluster: -p
CLUSTER_CLASS:Standalone,NODE_LIST:node1~node2~,MULTICAST: 2023-04-29
21:47:00: Command output:

Invalid site guid (-y)
clscfg -localadd -z  [-avlookup]
-p property1:value1,property2:value2...
-avlookup       - Specify if the operation is during clusterware upgrade
-z   - Specify the site GUID for this node
-p propertylist - list of cluster properties and its value pairs
Adds keys in OLR for the HASD.
WARNING: Using this tool may corrupt your cluster configuration. Do not
use unless you positively know what you are doing.
End Command output 2023-04-29 21:47:00: Failed to create keys in the OLR, rc = 100, Message:   Invalid site guid (-y)  clscfg -localadd -z
 [-avlookup]                  -p
property1:value1,property2:value2...    -avlookup       - Specify if
the operation is during clusterware upgrade   -z   -
Specify the site GUID for this node   -p propertylist - list of
cluster properties and its value pairs   Adds keys in OLR for the
HASD. WARNING: Using this tool may corrupt your cluster configuration.
Do not          use unless you positively know what you are doing.

my hosts setting

10.0.1.66 node1

10.0.1.70 node2
10.0.1.21 nodecluster

10.0.1.22 nodecluster

10.0.1.23 nodecluster
10.0.1.76 node1-vip

10.0.1.80 node2-vip
10.0.100.66 node1-pri-ip

10.0.100.70 node2-pri-ip

10.0.100.99 storage-pri-ip

Anyone can help me on this ?
Answer: This could be a bug. Please try to patch the GI home during installation.
The problem is that the applyru parameter is not supported on windows.
You can try the following installation sequence:

Deinstall the current installation ORACLE_HOME/deinstall/deinstall
If asm disk group has already been configured clean the disks. Recreate them if necessary.
Reinstall GI but do not configure during installation!
Patch the Oracle Home with the latest GI RU.
After patching the Oracle Home you can run the configuration.

I don't think the graphical installer supports installation without configuration. So you will have to do a silent installation with a response file.


List Slicing in Python Without Using Built-In Function?

Question: I'm very new to programming and am currently stuck on a practice problem involving list slicing without using the built-in function, so the idea is that you create your own slice function to be called upon by the user. Below is the question and following that is my attempt to solve it. Any help is appreciated. Thank you!
Python provides slicing functionality for lists, but for this question, you will implement your own function capable of producing list slices (note: you cannot use the slicing operator in your solution). The function should be called slice and take the following three inputs in this specific order:

A list, source, which the slice will be created from. This list cannot be modified by your function.
A positive integer, start, representing the starting index of the slice you will create. If this value is not in the range [0, len(list)-1], your function should return an empty list.
A positive integer, end, representing the ending index of the slice you will create. If this value is not in the range [start, len(list)-1], your function should return an empty list.
If the parameter values are acceptable, your function will return a list that contains the items from source beginning at the index start and ending at the index end (inclusive). This is different from the Python slice operator, as the item at the index end is also included in the new list.

Examples:
mylist = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
slice(mylist, 0, 9) should be ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] slice(mylist, 3, 4) should be ["D", "E"]
slice(mylist, 4, 3) should be [ ]
slice(mylist, 3, 8) should be ["D", "E", "F", "G", "H", "I"]
slice(mylist, 4, 4) should be ["E" ]

My code:
source=int(input("Enter a list: "))
start=int(input("Enter the starting digit: "))
end=int(input("Enter the ending digit: "))

def slice(source,start,end):
        if start is not [0, len(source)-1]:
            print()
        elif end is not [start, len(source)-1]:
            print()
    source.append(0,start)
    source.append(len(source),end)

slice[]

Comment: Nice attempt. What is your question?
Comment: @Mitch I do not see what is nice about this attempt.
Comment: @Mitch Thanks :p the question is above the examples.
Comment: @Ev.Kounis that's constructive and kind thank you
Comment: @kleenexbox, what happens if it is out of index?
Comment: @lmiguelvargasf it's supposed to return an empty list if out of index.
Comment: @kleenexbox Ok, let's start from the top. How are you planning on reading a list with this: `source=int(input("Enter a list: "))`. Break your problems into smaller ones. *Pass a list* could be one of those
Comment: @Ev.Kounis I figured the user needed to input the list? Not sure what you mean
Comment: add `print(source)` below your first line and run it. tell me if it does what you expected
Comment: ok now line 11   source.append(0,start) keeps returing IndentationError that I can't seem to fix @Ev.Kounis
Comment: The first `if` within your function sets the indentation level which is then ignored by `source.append(0,start)`...
Answer: Figured it out myself, thanks for trying to help without being condescending @lmiguelvargasf I really appreciate it.
start = int(input(" Enter the starting index of the slice you will create: "))
end = int(input("Enter the ending index of the slice you will create:  "))
def slice(source, start, end):
    myList = []
    for i in range(start, end+1):
        if start in range(0, len(source)) and end in range(start,     len(source)):
        myList.append(source[i])
return myList

myList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] #This is the source
print(slice(myList,start,end))


Create a mysql conditional insert?

Question: How can I check in table_1 if value_a of column_a (and where value_b of column_b = 'x') already exists in column_a of table_2? If it's not present insert it and create a new row for the missing value_a in table_2?
Update: (What seems to work is this:)
INSERT INTO products
(key, category)
SELECT key, category
FROM accounts
WHERE category = 'vegan'
AND NOT EXISTS (SELECT *
          FROM products
          WHERE accounts.key = products.key);

Comment: Cleanup noise and remove php tag as this is about mysql.
Answer: Why don't you transform the column into a primary key ? You'll just have to handle the duplicate entry error code
EDIT :
The solution here is to use SELECT instead of WHERE (thanks to degr)
INSERT INTO tableA(`id`,`column1`)
SELECT 44,'Value of Column1' -- The values you want to insert
WHERE NOT EXISTS(SELECT * FROM table2 WHERE id=40) -- check that there is no matching with the request
AND 1=1 --additional conditions
AND NOT EXISTS(SELECT * FROM Table3 WHERE id=44);  --additional conditions

Comment: `INSERT` with `WHERE`?
Comment: I can't use it as primary key ... because out of the 500000 records there might be records using the same unique_id
Comment: Ok, so then, you can do a

INSERT INTO tableA(your,columns) VALUES(your,values) WHERE(SELECT COUNT(*) FROM table2 WHERE columnA=uniqueValue) = 0

This will count the occurences in the table 2 and if there is no occurence, it returns 0.
Comment: I'm struggling. Could you provide a more precise code example? I actually do have another where condition ... I want to do it only for certain records. Please see above.
Comment: Thanks Adrien. I'm almost there. The additional WHERE category = 'vegan'; is not working yet. I updated above.
Comment: Philipp,
Do you want to insert only if the value set for category is "vegan" ?
Comment: Yes ... I was hoping to be able to do that
Comment: I'm sure. But please see my edit above. This seems to work

Create a mysql conditional insert?


How to solve this literal equation

Question: I have a literal equation that needs to be solved for $\theta$:
$$mg \sin(\theta) = \mu mg \cos(\theta)\left({ M+m \over m}\right)  $$
Comment: Use $\sin x/\cos x=\tan x$ and the arctangent function.
Comment: Do you mean $mg \sin \theta = umg \cos \theta \cdot \frac{M+m}{m}$?
Comment: @jay: Did I get it right? If so, you can use the "edit" button to see what I did to change the formatting. If not, say what's wrong and someone will fix it.
Comment: What is a «literal equation»?
Comment: @MarianoSuárez-Alvarez It's an equation whose coefficients are letters instead of numbers, I guess. Such as $ax+b=0$, but not $2x-5=0$.
Comment: @jay [I wrote a tutorial / reference for the equation editor](http://meta.math.stackexchange.com/questions/5020/tex-latex-mathjax-basic-tutorial-and-quick-reference).
Answer: A simple rearrangement shows that
$$\tan\theta = \mu\left(1+\frac{M}{m}\right)$$
to obtain numerical values for the equation you'll need the ratio of the masses and the coefficient of friction, in which case you can simply take the arctangent.

How to solve this literal equation


Terminology for blow-ups in algebraic geometry

Question: Definition (from Eisenbud-Harris' Geometry of Schemes): Let $X$ be any scheme, $Y \subset X$ a subscheme. We say that $Y$ is a Cartier subscheme in $X$ if it is locally the zero locus of a single nonzerodivisor.
Given a scheme $X$ and a closed subscheme $Z$, is there a common name for the (closed) locus where the ideal sheaf corresponding to $Z$ is not Cartier? My motivation is as follows.
Let $X$ be a scheme, $Z$ some closed subscheme, and consider the blowup of $Z$ in $X$. $Z$ is known as the "center" of the blowup, and the blowup is guaranteed to be an isomorphism on $U = X \setminus Z$. However, it is certainly possible that there is a larger open subscheme $V$ such that the blowup is an isomorphism over $V$. Indeed, where ever $Z$ is Cartier the blowup will be an isomorphism which is an open subscheme by Nakayama.
For example, take the scheme $X = \operatorname{Spec}(k[x,y,z]/(z^2-xy))$ and $Z$ corresponds to the ideal $(x,z)$. Then the blow-up is an isomorphism except at the point corresponding to $(x,y,z)$. In this case, the center of the blow up is the closed subscheme corresponding to $(x,z)$ and my question is what should we call the point corresponding to $(x,y,z)$?
Comment: Should you replace 'Cartier' with 'locally free'?  The concept of being Cartier only applies to the case that $Z$ is a divisor, right?
Comment: Perhaps this terminology is nonstandard, but I have edited the question to define "Cartier" for an arbitrary subscheme. Of course, being a Cartier subscheme at a point implies that it is locally a divisor (i.e. codimension 1 in some affine open neighborhood).
Comment: Codimension one if $X$ is locally noetherian because you need Krull's principal ideal theorem for this statement.
Comment: I'm more than willing to stipulate to all schemes even being Noetherian and of finite type, but what statement are you referring to?
Comment: Dear rghthndsd, I refered to your sentence "(i.e. codimension 1 in some ..." in your last comment. Please be so kind to add @Cantlong if you want me beware of your comment.
Answer: This question is answered on MathOverflow. A quick summary:
In the case of a blowup, Sándor Kovács recommends calling the closed subscheme of $X$ where the map $\pi : \operatorname{Bl}_X(Z) \rightarrow X$ is not as isomorphism the "true center". There are also several other subschemes discussed there and suggested names for them.


Rails Gem Bundler breaking Dependencies

Question: I recently installed the Bundle gem (stable 2.3.x) with a integrated 3.0 release.  The documentation for installing 2.3.x is weak, so I'm looking for help here.
I've done everything from this article on installing and configuring gem bundler (Installing gem bundler, defining Gemfile, adding preinitializer.rb, requiring bundler_gems/environment.rb):
http://litanyagainstfear.com/blog/2009/10/14/gem-bundler-is-the-future/
I can run script/server successfully, but when I try to access any page via my browser, I get a 500 Internal Server Error claiming many ActionView methods are undefined:
ActionView::TemplateError (undefined method `debug' ...

ActionView::TemplateError (undefined method `javascript_tag' ...

There has to be some gem dependency failing somewhere or something?  Here's my Gemfile (rails 2.3.5):
clear_sources
bundle_path "vendor/bundler_gems"

source "http://gems.github.com"
source "http://gemcutter.org"

gem "rails", "2.3.5"
gem "formtastic"
gem "authlogic"
gem "will_paginate"
gem "cancan"

Any pointers?
Comment: The bundler documentation is horrible.
Answer: So for configuring gem bundler on Rails 2.3.5:
I changed my preinitializer.rb script to this:
# Load the environment constructed from the Gemfile
require "#{File.dirname(__FILE__)}/../vendor/bundler_gems/environment"

module Rails
  class Boot
    def run
      load_initializer
      extend_environment
      Rails::Initializer.run(:set_load_path)
    end

    def extend_environment
      Rails::Initializer.class_eval do
        old_load = instance_method(:load_gems)
        define_method(:load_gems) do
          old_load.bind(self).call
          Bundler.require_env RAILS_ENV
        end
      end
    end
  end
end

And removed any Bundler.require_env definitions from config/environment.rb, and all was good.
http://gist.github.com/286099
Comment: This looks like it might work, but it's complicated. Calling `Bundler.require_env` in a later phase would also work, no need in plugging in exactly at `load_gems` step.
Comment: That worked for me (not sure why, but not complaining).  I also started to get `config.gem: Unpacked gem environment.rb in vendor/gems has no specification file. Run 'rake gems:refresh_specs' to fix this.` errors -- is it save to ignore those?
Comment: Hmm this happened to me as well.  You could try to just run the task, if that doesn't work, someone else posted a hack:

http://stackoverflow.com/questions/2144659/how-to-silence-gem-errors-after-switching-to-bundler

But I think there's a smarter way to fix it.  Maybe just try deleting your Gemfile, then recreating it and running "Gem Bundle" again.  Eh...
Answer: For reference, bundle is now on 0.9.5.  Here is the newest rails 2.3.5 config (you can basically ignore everything else here):
http://gist.github.com/302406
Answer: Most (or all) of these gems are Rails plugins. You should require them during Rails initialization phase. Stick this in your after_initialize:
config.after_initialize do
  Bundler.require_env
end

Comment: What is the best file to put that snipit in? Thanks!
Answer: Updated as Gem Bundler Documentation improves:
http://gembundler.com/rails23.html

Rails Gem Bundler breaking Dependencies


Transforming a multivariate normal

Question:

I don't understand where the part underlined in green comes from.
Answer: $$
\mathbf{X} = \mathbf{M}^{-1}\mathbf{Y}
$$
Such that
$$
x_{i} = c_{ij}y_{j}
$$
Here $c_{ij} = [\mathbf{M}^{-1}]_{ij}$.
So now you can see where the derivative comes from?

Transforming a multivariate normal


How do I add a thumbnail to the teaser of a blog post containing an image?

Question: I am using Drupal 7 and have added an image field to the blog content type.  The image comes in fine when creating the blog post, but when viewing the teaser of the blog entry in the list of user's blogs, there is no thumbnail in the teaser showing that there is an attached image.  Is this possible to have? How do I do it?
Answer: Go to display settings for your content type ('blog post'), and then select teaser ex.:
/admin/structure/types/manage/article/display/teaser
From here you can control which fields will display in your teaser (or full, or other defined formats). Your image field is most likely hidden for your teaser, you'll want to have it displayed and style accordingly.
Comment: Thank you, that did it.  I didn't notice the ability to edit the "teaser" option.


.Net Core 2.2 - Depois de publicar um WebApp, os links não estavam funcionando e o código HTML gerado era o mesmo que o Razor

Question: Estou publicando um WebApp do Net Core (versão 2.2.108) no host SmaterAsp.net no modo "self-contained deployment".
Meu arquivo .CSPROJ se parece com isso:
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
    <UserSecretsId>438bea06-a241-4638-a75d-2c9de371a6b3</UserSecretsId>
    <AssemblyName>ProjectName.UI.Web.Admin</AssemblyName>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
  </PropertyGroup>

Após publicar e executar o WebApp vi que os links não estavam funcionando e o código HTML gerado estava igual ao Razor, desse jeito:
Tickets

Mas o correto deveria ser:
Tickets

Se eu publicar sem os parâmetros abaixo:
<PreserveCompilationContext>true</PreserveCompilationContext>
<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>

Tenho o seguinte erro:
Error - The type 'Attribute' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Private.CoreLib, Version=18.104.22.168, Culture=neutral, PublicKeyToken=

Vocês sabem me dizer o que fiz de errado ou como ajustar isso?
Desde já, agradeço a sua atenção.
Comment: Não endenti... ele está retornando o cshtml como arquivo estático? você está acessando pela rota ou digitando o caminho do arquivo com a extensão?
Comment: Me desculpe Leandro, irei detalhar um pouco mais. Além do projeto WebApp, eu tenho outro projeto que é uma class library de ViewComponents idêntico a esse [projeto](https://aspnetmonsters.com/2016/07/2016-07-16-loading-view-components-from-a-class-library-in-asp-net-core/) que eu referencio no WebApp. Para aplicações .Net Core 2.2 funcionem no host, necessito publicar em modo self-contained deployment. Quando executo a aplicação no servidor alguns [links](https://imgur.com/fWVsj0u) (inspecionando o cod.) não são convertidos para HREF.
Comment: mas se você quer um link, o seu tag-helper está errado, não tem o `asp-area=""` seria só
`Tickets`
Answer: Dê uma olhada se está adequadamente importando a lib cm as tagHelpers. Dê uma olhada neste artigo: https://www.koskila.net/how-to-fix-microsoft-aspnetcore-mvc-taghelpers-not-being-rendered/. Talvez possa ajudar a compreender o problema. Desconfiei de que talvez faltassem estes imports.
Veja se possui um arquivo _ViewImports.cshtml na pasta "Views" com o conteúdo:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Para ser mais específico e ajudar com erros comuns que possam ocorrer, segue o link da documentação relacionada, que trata do arquivo _ViewImports.cshtml. Ali ele explica exatamente como funciona, as diretivas para as quais ele dá suporte e também explica o seguinte:

"O arquivo _ViewImports.cshtml para um aplicativo ASP.NET Core MVC
  normalmente é colocado na pasta Pages (ou Views). Um arquivo
  _ViewImports.cshtml pode ser colocado em qualquer pasta, caso em que só será aplicado a páginas ou exibições nessa pasta e em suas
  subpastas. Arquivos _ViewImports são processados começando no nível
  raiz e, em seguida, para cada pasta até o local da página ou da
  exibição em si. As configurações _ViewImports especificadas no nível
  raiz podem ser substituídas no nível da pasta."

https://docs.microsoft.com/pt-br/aspnet/core/mvc/views/layout?view=aspnetcore-2.2#importing-shared-directives
E, como sugere o artigo, a falta deste arquivo leva ao erro informado na pergunta: As TagHelpers não são compiladas.
Agora sim, espero ter ajudado.
Comment: Agora melhorou a resposta, mas seria interessante trazer o conteúdo do link externo para cá também, afinal a sua resposta vai ficar aqui, mas esse endereço pode ser desativado amanhã.
Comment: Oi Leandro, realmente não existe o arquivo _ViewImports.cshtml no projeto ViewComponentsLibrary. Irei ler o artigo que você informou, fazer os ajustes necessários e realizar o testes. O engraçado que executando localmente a situação não ocorre, ocorre só em ambiente de produção. Também irei ajustar a minha pergunta detalhando o que escrevi nos comentários, concordo com você. Obrigado pela atenção.


printing post table data in admin menu page

Question: I am trying to retrieve data from post table into admin menu page. I have written my codes below. it doesn't display records from post table.
    function wdbp_menu_page(){
    add_menu_page(
        __( 'My wpdb', 'wpdb' ),
        'my db',
        'manage_options',
        'customdb',
        'my_menu_page',
        7
    );
}

add_action( 'admin_menu', 'wdbp_menu_page' );
function my_menu_page(){
global $wpdb;
$fivesdrafts = $wpdb->get_results(
    "
        SELECT *
        FROM $wpdb->posts
        WHERE post_status = 'draft'
        AND post_author = 5
    "
);
if ( $fivesdrafts ) {
    foreach ( $fivesdrafts as $post ) {
        setup_postdata( $post );
        ?>

            <a href="<?php the_permalink(); ?>" rel="bookmark" title="Permalink: <?php the_title(); ?>">
                <?php the_title(); ?>

        <?php
    }
} else {
echo "Page not fount";

}
}
Comment: Why use a custom SQL statement and not `WP_Query`? If you run your SQL statement directly on the database (using Terminal or a client) do you get results?
Comment: It works in theme's template page. But it doesn't work in admin pages.
Answer: Recommend using WP_Query and getter functions (rather than print functions), so you don't have to use setup_postdata() (untested):
function my_menu_page() {
    $fivesdrafts = new WP_Query( array(
        'posts_per_page' => -1,
        'post_status'    => 'draft',
        'author'         => 5,
        'no_found_rows'  => true,
    ) );

    if ( ! $fivesdrafts->have_posts() ) {
        echo __( 'Page not found' );
    }

    foreach ( $fivesdrafts->posts as $post ) {
        $title = get_the_title( $post );

        printf(
            '
%s
',
            esc_attr( get_permalink( $post ) ),
            esc_attr( $title ),
            esc_html( $title )
        );
    }
}

Answer: these codes work print mysql table datas into my admin menu page. thanks for
for your reply.
 function my_menu_page(){

global $wpdb;
$fivesdrafts = $wpdb->get_results(
    "
        SELECT *
        FROM slides
        WHERE ID = '1'
    "
);

$sql_results = $fivesdrafts;
if ($sql_results) {
    foreach ($sql_results as $post) {
      echo $post->name;
    }
}

}


MVC Dropdownlist Cascade - how to fire event on third ddl when first ddl selection changes?

Question: I have three DDL's in a view.  I fire a javascript function on 'onchange' of the first DDL to populate the second, and of the second to populate the third.  Works fine.
Problem is, when first DDL is set to unselected i.e. "Select a Value", the second DDL gets fired and sets itself to "Select a Value", but the second DDL 'onchange' event does not fire, so the third DDL remains populated with the data that it got from the previous selection.
How do I get the second DDL to fire an event I can use to refresh the third DDL? Or is there another way?
Code below:
@{
   ViewBag.Title = "CascadingList";
   Layout = "~/Views/Shared/_Layout.cshtml";
}
@{Html.EnableUnobtrusiveJavaScript(true);}

Strategy

  Markets
  <select id="MarketsID" name="Markets" onchange="getShareType()"></select>

  ShareTypes
  <select id="ShareTypesID" name="ShareTypes" onchange="getShare()" ></select>

  Shares
  <select id="SharesID" name="Shares" ></select>

Answer: Try selecting a value for the select after populating it using $('#selectID').val(), if that doesn't work trigger onchange like this ; $('#selectID').trigger('change')
Answer: Thanks - I tried that and went around in circles - but it made me think differently.  Fixed it by adding a call to the function that populates the third DDL in the function that populates the second DDL - that way it always gets called.
    function getShareType() {
    var url = '@Url.Content("~/Strategies/ShareTypeList")/' + $('#MarketsID').val();
    $.getJSON(url, function (data) {
        var items = '<option>Select an Asset Type</option>';
        $.each(data, function (i, shareType) {
            items += "<option value='" + shareType.Value + "'>" + shareType.Text + "</option>";
        });
        $('#ShareTypesID').html(items);
    });
**** Added This ****
    getShare();
}


Finding a distribution where skewness and kurtosis do not depend on each other. Does it even make sense?

Question: I am simulating non-normal data to investigate how this affects some diagnostical methods that assume normality. In particular I'm interested in seeing how skewness and kurtosis affects the results.
I've investigated skewness using the skewed normal distribution as well as the gamma distribution, but would like to change kurtosis on top of that. Unfortunately this doesn't work for these two distributions as the skewness and kurtosis depend on the same parameter.
The best I've found so far was the skewed student t-distribution in the package "skewt" in R. https://cran.r-project.org/web/packages/skewt/skewt.pdf
This seems to, on the surface, do what I would expect: given a constant skew parameter, the visible skewness does not change (the peak remains in place) when I alter degrees of freedom. It presents its own problems however, because I am yet to be able to compute kurtosis for a given value of gamma, and negative kurtosis is impossible to implement.
Are there any other distributions I could use? Does what I ask even make sense? Part of me thinks it does not given the definitions of kurtosis and skewness in terms of moments, but it also seems like it should be doable to maintain a given skew while only "lifting" or "sinking" the tails, as it were.
Comment: Abstractly there is a space of distributions.  If, within that space, you plot a curve, then along the curve the skewness and kurtosis obviously depend on each other.  But if you consider any region of two or more dimensions that doesn't lie along a level set of either skewness or kurtosis, then you have a family of distributions satisfying your requirements.  I hope that helps make it clear that your search for a suitable family of distributions *must* be guided by more than this weak criterion.  Focus instead on distributions likely to be appropriate for you application.
Comment: Discrete distributions are easy to play with and offer great flexibility. And if you must have continuous distributions, you can just add noise. See .https://stats.stackexchange.com/a/483215/102879
Answer:
Finding a distribution where skewness and kurtosis do not depend on each other.

Presumably you mean the standardized third and fourth moments (rather than some of the other measures of skewness and kurtosis).
This is not really possible to do as a general thing because kurtosis is always at least skewness$^2 + 1$. Which means, for example, you simply cannot find any distribution that has, say skewness $3$ that has kurtosis less than $10$ (excess kurtosis less than 7); they're not possible to separate in that sense.
But within the possible region, there are collections of distributions that cover the whole range of possibilities. Perhaps the best known are the Pearson family of distributions. There are many posts about them on the site.
https://en.wikipedia.org/wiki/Pearson_distribution
The Pearson plot (a diagram plotting the regions covered by the family members on the axes of skewness vs kurtosis or skewness$^2$ vs kurtosis) is a convenient way to find the distribution in the family that includes a member with the selected skewness and kurtosis.
There are other families that people use that might suit you better, perhaps, such as the Johnson distributions including the $S_U$ and $S_B$ distributions:
https://en.wikipedia.org/wiki/Johnson%27s_SU-distribution
https://en.wikipedia.org/wiki/Johnson%27s_SU-distribution#Johnson's_SB-distribution
There have been attempts to make distributions that let you tweak the parameters "individually" (at least sort of), but they cannot avoid the fundamental restriction that once you fix skewness, kurtosis has a hard lower bound that's higher than what it would be if skewness were $0$. Equivalently, if you choose kurtosis, there are limits on how big skewness can be.
One example of an attempt to separate out the skewness and kurtosis dials is Tukey's $g$-and-$h$ distribution family, which rely on transformations of normal random variables.
There's some related transformation-based suggestions here
I've seen at least a couple of other such attempts at individual control, but I can't say I found any of them particularly satisfactory for the sort of application you're after; there always seem to be a few less than ideal aspects. I'll try to locate another one of these that I have in mind.
Answer: You could use a distribution on just three points to illustrate arbitrary skewness and kurtosis, so long as the raw kurtosis is at least $1+{}$ the square of the skewness.  Even this gives you more freedom than you need, so you can put one of the points at the mean.
Suppose the skewness is $\gamma$ and the raw kurtosis is $\kappa$.  The following distribution will give this with arbitrary mean $\mu$ and variance $\sigma^2$, though you can set these equal to $0$ and $1$ if you wish.
$$\begin{array}{lcl}
\mathbb P \Big(X = \mu+\frac12\left(\gamma+\sqrt{4\kappa-3\gamma^2}\right)\sigma\Big) &=& \dfrac{\sqrt{4\kappa-3\gamma^2}-\gamma}{2\sqrt{4\kappa-3\gamma^2}(\kappa-\gamma^2)} \\
\mathbb P \Big(X = \mu\Big) &=& 1-\dfrac{1}{(\kappa-\gamma^2)} \\
\mathbb P\Big(X = \mu+\frac12\left(\gamma-\sqrt{4\kappa-3\gamma^2}\right)\sigma\Big) &=& \dfrac{\sqrt{4\kappa-3\gamma^2}+\gamma}{2\sqrt{4\kappa-3\gamma^2}(\kappa-\gamma^2)}\end{array}$$
These locations and probabilities are continuous functions of the parameters, so you can make a small change to one of skewness or kurtosis without changing the other to see the effect on the locations and probabilities of the three points.
Comment: This would be easier to read using $u=\sqrt{4\kappa-3\gamma^2}$, and writing the formulas in terms of $u$.
Comment: @MattF. Something like: $\mathbb P \Big(X = \mu+\frac12\left(\gamma+u\right)\sigma\Big) = \dfrac{u-\gamma}{2u(\kappa-\gamma^2)}$, $\mathbb P \Big(X = \mu\Big) = 1-\dfrac{1}{(\kappa-\gamma^2)}$, $\mathbb P\Big(X = \mu+\frac12\left(\gamma-u\right)\sigma\Big) = \dfrac{u+\gamma}{2u(\kappa-\gamma^2)}$ using $u=\sqrt{4\kappa-3\gamma^2}$


Hikari pool connection not available when SseEmiter is refreshed multiple times by front-end

Question: Im using SseEmiter in Spring Boot application to send notifications to Frontend. Everything works fine, the client receives the initial notification and every other notification sent. Тhe problem occurs when page is refreshed 10 or more times. The hickari pool gets filled up and throw a timeout exception. How can I prevent this behavior and clear the old unused connections in the pool?
Controller class
@RestController
@ResponseStatus(HttpStatus.OK)
@RequestMapping("/notifications")
public class NotificationsController {

    private final NotificationsService notificationsService;
    public NotificationsController(NotificationsService notificationsService) {
        this.notificationsService = notificationsService;
    }

    @CrossOrigin
    @RequestMapping(value = "/subscribe", consumes = MediaType.ALL_VALUE)
    public SseEmitter subscribe() {
        SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE);
        notificationsService.registerEmitter(sseEmitter);
        return sseEmitter;
    }

Emitter handal in Service
private final Map<String, User> emitters = new HashMap<>();

public void registerEmitter(SseEmitter sseEmitter) {
     sendInitEvent(sseEmitter);
     addToEmittersMap(sseEmitter);
}

private void sendInitEvent(SseEmitter sseEmitter) {
    try {
        sseEmitter.send(listNotifications());
        logger.info("Initial event to emitter sent");
    } catch (IOException e) {
        e.getMessage();
    }
}

private void addToEmittersMap(SseEmitter sseEmitter) {
    User user = new User(authService.getUserId(),
            authService.getGins().stream()
            .map(Integer::parseInt)
            .toList(),
            sseEmitter);
    emitters.remove(authService.getUserId());
    emitters.put(authService.getUserId(), user);
    logger.info("Emitter added");
}

@Modifying
@Transactional
public List<NotificationsView> listNotifications() {
    List<NotificationsHistory> events = notificationsRepository.getByGinInAndTsBetween(
            authService.getGins().stream()
                    .map(Integer::parseInt)
                    .toList(),
            Instant.now().minus(60, ChronoUnit.MINUTES),
            Instant.now());
    return notificationsMapper.toDtos(events);
}

Repository class
 @Repository
 public interface NotificationsRepository extends JpaRepository<NotificationsHistory, Integer> {
 }

Update on 09.03.2023
Partialy the problem was solved by changing the upper class so the old SseEmitter is set to "complete" but in one point (30 mins) of work same exception appears.
Change in code
Solution
private void addToEmittersMap(SseEmitter sseEmitter) {
User user = new User(authService.getUserId(),
        authService.getGins().stream()
        .map(Integer::parseInt)
        .toList(),
        sseEmitter);
if(emitters.containsKey(authService.getUserId())){
     emitters.get(authService.getUserId()).emitter().complete();
     logger.info("Old connection completed");
}
emitters.put(authService.getUserId(), user);
logger.info("Emitter added");

}
Error message

SQL Error: 0, SQLState: null 2023-03-08T14:11:13.270+02:00 ERROR
139580 --- [nio-8189-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper
: HikariPool-1 - Connection is not available, request timed out after
30000ms. 2023-03-08T14:11:13.274+02:00 ERROR 139580 ---
[nio-8189-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    :
Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed:
org.springframework.transaction.CannotCreateTransactionException:
Could not open JPA EntityManager for transaction] with root cause
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is
not available, request timed out after 30000ms.   at
com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:696)
~[HikariCP-5.0.1.jar:na]  at
com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:181)
~[HikariCP-5.0.1.jar:na]  at
com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:146)
~[HikariCP-5.0.1.jar:na]  at
com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:128)
~[HikariCP-5.0.1.jar:na]  at
org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]     at
org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:38)
~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]     at
org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:107)
~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]     at
org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:137)
~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]     at
org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:152)
~[spring-orm-6.0.3.jar:6.0.3]     at
org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:421)
~[spring-orm-6.0.3.jar:6.0.3]     at
org.springframework.transaction.support.AbstractPlatformTransactionManager.startTransaction(AbstractPlatformTransactionManager.java:400)
~[spring-tx-6.0.3.jar:6.0.3]  at
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
~[spring-tx-6.0.3.jar:6.0.3]  at
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:595)
~[spring-tx-6.0.3.jar:6.0.3]  at
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:382)
~[spring-tx-6.0.3.jar:6.0.3]  at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
~[spring-tx-6.0.3.jar:6.0.3]  at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
~[spring-aop-6.0.3.jar:6.0.3]     at
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:752)
~[spring-aop-6.0.3.jar:6.0.3]     at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:703)
~[spring-aop-6.0.3.jar:6.0.3]     at
com.lsbo.notifications.notificaations.service.NotificationsService$$SpringCGLIB$$0.registerEmitter()
~[classes/:na]    at
com.lsbo.notifications.notificaations.api.NotificationsController.subscribe(NotificationsController.java:27)
~[classes/:na]    at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:na]  at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
~[na:na]  at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:na]  at
java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
~[spring-webmvc-6.0.3.jar:6.0.3]  at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)
~[spring-webmvc-6.0.3.jar:6.0.3]  at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
~[spring-webmvc-6.0.3.jar:6.0.3]  at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
~[spring-webmvc-6.0.3.jar:6.0.3]  at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080)
~[spring-webmvc-6.0.3.jar:6.0.3]  at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973)
~[spring-webmvc-6.0.3.jar:6.0.3]  at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1010)
~[spring-webmvc-6.0.3.jar:6.0.3]  at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:902)
~[spring-webmvc-6.0.3.jar:6.0.3]  at
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:705)
~[tomcat-embed-core-10.1.4.jar:6.0]   at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:884)
~[spring-webmvc-6.0.3.jar:6.0.3]  at
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
~[tomcat-embed-core-10.1.4.jar:6.0]   at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
~[tomcat-embed-websocket-10.1.4.jar:10.1.4]   at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.springframework.security.web.FilterChainProxy.lambda$doFilterInternal$3(FilterChainProxy.java:231)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$FilterObservation$SimpleFilterObservation.lambda$wrap$1(ObservationFilterChainDecorator.java:399)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$AroundFilterObservation$SimpleAroundFilterObservation.lambda$wrap$1(ObservationFilterChainDecorator.java:297)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator.lambda$wrapSecured$0(ObservationFilterChainDecorator.java:79)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:125)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.access.intercept.AuthorizationFilter.doFilter(AuthorizationFilter.java:100)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:126)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:120)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:131)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:85)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:100)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:179)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter.doFilterInternal(BearerTokenAuthenticationFilter.java:145)
~[spring-security-oauth2-resource-server-6.0.1.jar:6.0.1]     at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:107)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:93)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java:82)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java:69)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:62)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$AroundFilterObservation$SimpleAroundFilterObservation.lambda$wrap$0(ObservationFilterChainDecorator.java:280)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:170)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:233)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:191)
~[spring-security-web-6.0.1.jar:6.0.1]    at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:351)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267)
~[spring-web-6.0.3.jar:6.0.3]     at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.springframework.web.filter.ServerHttpObservationFilter.doFilterInternal(ServerHttpObservationFilter.java:109)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
~[spring-web-6.0.3.jar:6.0.3]     at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
~[spring-web-6.0.3.jar:6.0.3]     at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
~[spring-web-6.0.3.jar:6.0.3]     at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
~[tomcat-embed-core-10.1.4.jar:10.1.4]    at
java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
Comment: First of all, I would check whether any emitters actually get cleared from the map when a new one is registered for a user.
Second, the error you're getting has to do with database connections, but I don't see anything relating to a database call in your provided code. Please provide a sample of this.
Comment: I have editted the post and added the information you requested. Emitters are removed from emmiters map in addToEmittersMap() method. DB call is made every time a new SseEmiter is created to provide notifications stored in DB for period of 60 minutes.
Comment: Your `@Transactional` doesn't do anything as it is an internal method call. Hence you are leaking connections.
Comment: That was not the case. I removed the annotations, they were needed before, because the logic was a bit different in that method. But even when I comment the part that make repository calls the problem appears again.
Тhe problem generation process is as follows:
1. Launch the application
2. Opening a connection through postman with Authorization Bearer Token
3. Close and open the connection repeatedly (10x times).
After which I get the above mentioned error.
Answer: Seams that the problem was generated because open-in-view option in spring configuration was set to true. It has to be set to false.
I found the answer here:
Database connection leak in Spring Boot with SseEmitter
Answer: Setting open-in-view to false could resolve the issue.
spring:
  jpa:
    open-in-view: false

I was wondering why though and this article helped me understand why.
This setting is true by default, which enables Spring to seamlessly take care of the lazy loaded properties of entities. The developer doesn't need to watch out for how these properties are loaded, which facilitates the development. To make this possible, Spring binds a Hibernate Session to the thread for the entire processing of the request, when the request flow includes connecting to the DB. Once the connection is taken from the pool, it remains assigned to the request scope and it's never released to the pool until after the request completes. SSE usually implies long-running requests and when some of them require DB connections, the connection pool may get exhausted.
Setting open-in-view to false changes this behaviour as the DB connection is released to the pool as soon as the DB call completes. There shouldn't be any issues after changing this setting if you don't declare any lazy associations. If there are lazy associations, you have to take care of the lazy loading, e.g. with @EntityGraph on some repository methods.


Whta is the diference in between google maps API and Restrict key?

Question: When we create Google Maps API key for Android Application.We can easily generate a API key by choosing the project Create credentials-->API key.There is option for RESTRICT key for which we have to give SHA1 with package name.What is the difference in betwwen it? And which one to follow?
Answer: For example, Restrict to android app, only application with specific sha1 and packagename can use your api key, similar to iOS apps (only specific bundle identifiers), IP address, web url. You can reduce the impact of a compromised API key.
So, you should create different api key for each platform
Refer to the link below: https://support.google.com/googleapi/answer/6310037?hl=en
Answer: API key is a unique string that allow google to identify who is requesting access to platform and verify that they have permission to do so.
Restrict key is optional but highly recommended since it helps  to keep your account secured prevent malicious user for your project.
You can assign any number of restriction to the API key for your security purpose and it depends on your project whether to apply restriction or not.
There are 4 type of Application restriction:

Http refers:- It will be used to only allow request that originate from the particular website or web app.
IP Address:- This restriction allow call from specific IP address.
Android App:- This type of restriction only allow calls that originate from Android application.You need to specify package name and SHA-1 key.
iOS App:- It only allow request that originate from iOS application

There is also option for API restriction which allow you to specify the API's that can be called using key.


Convert HTML content to PDF including images

Question: I'm using React-quill as a text editor. I want to convert the content from it that includes images into a pdf. Below is the string, I'm getting from editor.

sdfghj

I've used jsPDF but it's only converting plain text into a pdf. If I put an image into the text editor, pdf is showing blank. How do I convert text with more than one images into a pdf?
Note: In the image src, the image is in base64 format.
Answer: You can use html2canvas library
 import html2canvas from 'html2canvas';
 import jsPDF from 'jspdf';

// Function to convert React-quill content to PDF
function convertContentToPDF(content) {
  // Capture React-quill content as an image using html2canvas
  html2canvas(document.getElementById('yourEditorElementId')).then((canvas) => {
    const imgData = canvas.toDataURL('image/png');

    // Generate PDF using jsPDF
    const pdf = new jsPDF();
    pdf.addImage(imgData, 'PNG', 0, 0, 210, 297); // Image dimensions and positioning
    pdf.save('react-quill-content.pdf'); // Save the PDF
  });
}

// Use the function with the React-quill content
convertContentToPDF(yourReactQuillContent);

hope this helps
Comment: Hi Ahmed, thanks for sharing this. I have form and I'm rendering two components based on a radio button. So, second component is React-quill which is setting the data using formik setFieldValue(). And I have a list, inside those, I've view button for each content I save using redux. So, How do I use document.getElementById()? Is there any way I can utilize jsPDF?
Comment: I guess you can use a reference to the element `useRef` and try getting the element with it
Comment: either you make a loop using js, or just get the element by developer tools in the browser, check it, if it's static then just copy paste, if its more than 1 element, make a loop and pass it to js variable and assign it to the above code.
Answer: Here is an approach you can follow using html2canvas and jspdf. I am using the element reference (useRef, the react way) instead of document.getElementById.
For some reason, it was having some issues using third-party images even after setting the CORS flag in html2canvas. But here is a working implementation using a local image
Main:
import React, { useRef } from "react";
import ElementToPDF from "./ElementToPDF";
import myLocalImage from "./image.png";

const MyElement = () => {
  const elementRef = useRef(null);
  return (

Hello, world!

This is an example paragraph.

      <ElementToPDF elementRef={elementRef} />

  );
};

ElementToPDF:
import React, { useRef } from "react";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

const ElementToPDF = ({ elementRef }) => {
  const convertToPDF = () => {
    if (elementRef.current) {
      html2canvas(elementRef.current, { useCORS: true }).then((canvas) => {
        let canvas_img = new Image();
        canvas_img.src = canvas.toDataURL("image/png");
        canvas_img.onload = function () {
          const pdf = new jsPDF("landscape", "mm", "a4");
          pdf.addImage(canvas_img, "PNG", 0, 0, 800, 500); // Image dimensions and positioning
          pdf.save("file2.pdf"); // Save the PDF
        };
      });
    }
  };

  return <button onClick={convertToPDF}>Convert to PDF</button>;
}

Comment: Hi Chinmay, thank you for sharing your insights. html2canvas doesn't allows us to select the content from the pdf because its storing images in the pdf. I want to select the text from pdf after converting the html.


How to set web api project on mvc project (api route return code 404)?

Question: As first I Built MVC application, with controllers and everthing. After that I realised that I need to make mobile application also, so I put new web api project in solution.

I referenced the mvc application, made entity-models, created factory and everything, but when it come down to calling web api controller I get return code 404 not found.

I think that problem is in routing of the project. So here is my WebApiConfig from SHApi project.
<code>    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.EnableCors();
        config.MapHttpAttributeRoutes();
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults:
            new
            {
                controller="StudentOffer",
                action="Get",
                id = RouteParameter.Optional
            },
            constraints: new {controller = @"(?!web).*"}
        );
    }
</code>
And here is my RouteConfig from MVC application.
<code> public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "web/{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
</code>
And here is my RouteConfig from WebApi project.
<code>public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "web/{controller}/{action}/{id}",
            defaults: new { action = "Index", id = UrlParameter.Optional }
        );

        routes.MapHttpRoute(name: "DefaultApi",
            routeTemplate:"api/{controller}/{action}/{id}",
            defaults: new { controller = "City",
            action="Get",
            id = RouteParameter.Optional},
            constraints: new { controller = @"(?!web).*" }
            );
    }
</code>
I can access MVC controllers easily, but web api Impossible.
I tried lot of stuff, but I am sure that I am missing something, so is there anyone with some expirience who can help me, is there any trick to do it like this?
Thank you in Front!
Answer: You need to run single instance of both project, firstly web project, because api project have some dependencies from it, and then start api project as single instance, and then you access them with diferent ports.
You are runing single instance like, right click on project, debug, run as single instance (something like that).