text:
Q: Difference between Observer Pattern and Event-Driven Approach I always found the Observer Pattern almost similar to the usual event-driven approach. Actually, I have almost believed that they are actually just different names referring to the same thing. They both use similar concepts to have something as a listener and even in the implementation, they are almost the same thing, that's to have a callback method/function to carry out an action. This is at least in Java.
In other languages say Actionscript/Flex, the events are more user-friendly and may look like it does more than just the observer pattern defines. But still, the concepts sound the same.
But is this really true? Is the Observer Pattern the same thing as the usual event-driven programming style?

A: The Observer Pattern is a very special instance. Event-Driven can mean anything. In most Observer Pattern implementations the Observer is an object watching the observee. When the observee is changed, a method of the observer is called. Strictly speaking this is not an "Event". That means: various different actions on the observee, usually lead to the call of different methods in the observer. The semantics "what" got changed is in the method.
In Event Driven Systems, you basically have one consuming object/method and the message what was changed or what happend is in the Event. That can be anything and is not limitd to the idea of observing something! That means: in an Event Driven System you get new semantics by adding new Event types. In an Observer Pattern you usually add semantics by adding a method to the Observer class. HOWEVER: no one is preventing you to implement an Observer as a special listern to ChangeEvents.

A: One of the great things about the observer pattern is safety. When code changes occur within the observee object, all observants must implement the new changes. If we would have used events instead, the event listener would not react to the implementation of new events. In other words, the observee dictates that events must be handled by the observers.
In one of my projects I came across a situation where one of the observee objects became destroyed and observers needed to be notified, before doing so. The only thing that I had to do was add the notification as a requirment for all of the observers, and fire the event before the observee got destroyed. The beauty here is that the code only compiles if all observers implement a handler for the newly created event, therefore you will less likely forget to change a few of them. In my case I had a decent amount of possible observers, and it is nice to know that I can make changes without creating a few or more hidden bugs.
These qualities makes the observer pattern less flexible than simply throw an event, and let the observers decide for themselfs. But, when using events, beware for the great spaghetti monster that hides around the corner, and only comes out when deadlines are near. There's probably more than a few of you that have, just like me, come across this ugly beast more than once.
In other words, be as pragmatic as possible and still use the right tools for the job. This means using event when you need flexibility and the observer when you need control.

A: When there is a state change at the Publisher or Subject,

*

*Event Driven Architecture (is a message-driven architecture), responsible to deliver message to Subscriber, asynchronously.

*Observer Pattern (is a software design pattern), responsible to command Subscriber to do something, synchronously.

A:
Event-driven programming is a term to define a paradigm. whereas
  Observable pattern is a design solution to make an application
  event-driven.

Cheers!

A: Yes, they are the mainly same.
Events are something like a "built-in" observer pattern template for some languages.
Thus, you wouldn't really implement the observer pattern in a language which supports events as they already provide what you are looking for.
On the other hand, you can write event-driven in languages which lack events by using the observer pattern.

A: I've searched a bit for this same question.
For this thread, I find point from Angel O'Sphere on "What semantics" and point from Spacerat on "Dispatcher" do helps.
That two points are my understanding that distinguish Even-Driver from Observer Pattern. At least from canonical explanation, "Observer Pattern" usually represents an immediate broadcasting once the "Subject" has changed and the "Dispatching" is implemented by calling the interface provided by subscriber or listener. While for Event-Driven, there is always another layer between "Subject and "Observer". Either called "Dispatcher" or using "Event Queue". This provides the "delayed" handling to reduce CPU usage and also provides certain capability on calling different interfaces depends on different event type.

A: I try it very simple, because that helped me once too.
Just think as a Observer and Observable. Instead that the observable marks a setChanged and the observer requests from the observable what has changed, the observable instead broadcasts an object (Event Carried State) with all relevant information about the change to the observers. So there is actually one more instance between the Observer and the Observable.
http://www.grahambrooks.com/event-driven-architecture/patterns/stateful-event-pattern/

A: The diffrence No.1 may be, that Event-Systems always have an eventdispatchthread which decouples observables from its observers so events may not reach the observers immediatly. While real observables call observer methods directly, event driven observables drop their events into an eventqueue. Then the EDT deliveres those events to registered listeners.

A: Synthesizing from multiple answers in this question, this hackernoon article, and my own experience, the key difference between the Observer Pattern and Event-Driven (Pub-Sub, say) Architecture is, in my mind, this:
In the Observer Pattern, the Observed maintains references to its Observers.
Whereas in Pub-Sub, the Broadcaster has no idea who its Listener(s) are. (Or even if anyone is there to listen.) The Listener may expect some data from the Broadcaster, but has no idea exactly where the event comes from. Maybe it comes from multiple classes or remote systems. Maybe not. It doesn't matter to either the Broadcaster or Listener.
Now, that's not to say these things are very different. Also, there are implementations that behave like either or both.
For example, the wisper rubygem allows you to act like either an Observer pattern or a Pub-Sub pattern depending on your need. You can even use both together if you like.

A: The basic difference in both is coupling and synchronous behaviour. If we stick with observer pattern, we say there is only one source of signal and it would be synchronous, while on other hand with events, we decouple both parties to work independently and the same time entertain the possibility of having more than one source of events in future without any code changes. Events help us to embrace async as design. All Reactive programming library provide very good support for event driven design.

A: Event-driven is a software paradigm or style of writing code where objects communicate using events. Some languages like C# have native support for events. You can have an object raise an event to which another object listens to. The Observer Pattern is another way to achieve the same result.

A: From Wikipedia :

The observer pattern is a software design pattern in which an object,
  called the subject, maintains a list of its dependents, called
  observers, and notifies them automatically of any state changes,
  usually by calling one of their methods.
It is mainly used to implement distributed event handling systems, in
  "event driven" software. Most modern languages such as Java and C#
  have built in "event" constructs which implement the observer pattern
  components, for easy programming and short code.

The observer pattern is a little more abstract and theoretical.  Events are one (commonly built-in) implementation, however as noted in Angel's answer Events tend to be able to be used in a few other situations apart from what is strictly defined in the observer pattern.


text:
Q: How to make config section configurable We started exploring WSO2 DSS with Cassandra, but didn't find a way to make config section configurable so that this section can be independent of the environment.

<data name="TestDs" transports="http https local">
    <config id="CassandraDS">
        <property name="cassandraServers">0.0.0.0,0.0.0.0,0.0.0.0</property>
        <property name="keyspace">test</property>
        <property name="port">9042</property>
        <property name="username">XXXX</property>
        <property name="password">XXXXX</property>
        <property name="dataCenter">XX</property>
        <property name="consistencyLevel">LOCAL_QUORUM</property>
    </config>
</data>

Is there a way to make it configurable ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to call onConfigurationChanged in Android class Rove3LiveVideoFragment : BaseFragment(){

    @Inject
    lateinit var roveR3LiveVideoFragmentViewModel: RoveR3LiveVideoFragmentViewModel

    @Inject
    lateinit var videoControlWidget: VideoControlWidget

    @Inject
    lateinit var notConnectedWidget: NotConnectedWidget

    @Inject
    lateinit var appPreference: AppPreference

    @Inject
    lateinit var videoFullViewWidget: VideoFullViewWidget

    lateinit var customLoader: CustomLoader

    private lateinit var onFullScreenListener: OnFullScreenListener

    var isChangeScreenButtonClicked = false
    var isPortraitMode = true

    override fun onAttach(context: Context) {
        inject(this)
        super.onAttach(context)
        if (activity is Rove3MainActivity) {
            onFullScreenListener = activity as OnFullScreenListener
        } else {
            throw ClassCastException(
                activity.toString()
                        + " must implement MyListFragment.OnItemSelectedListener"
            )
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_rove_r3_live_video, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initWidget(view_live_vide_page)
        customLoader = CustomLoader(requireContext())
        val wifiManager =
            requireContext().applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
        wifiManager?.let {
            if (wifiManager.isWifiEnabled) {
                roveR3LiveVideoFragmentViewModel.apply {
                    customLoader.show(getString(R.string.title_please_wait))
                    if (appPreference.isAppGoesBackGroundExceptHomePage) {
                        appPreference.isAppGoesBackGroundExceptHomePage = false
                        getRove3CameraConnectionStatus(true)
                    } else {
                        getRove3CameraConnectionStatus(false)
                    }
                    observe(stateLiveData, ::getR3ConnectedInLiveVideFragment)
                }
            } else {
                notConnectedView()
            }
        }

    }

    private fun initWidget(view: View) {
        videoControlWidget.apply {
            initView(view)
            addWidget(this)
            activity?.let {
                it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
            }
            observe(onClicked, ::onClickedButton)
        }
        notConnectedWidget.apply {
            initView(view)
            addWidget(this)
        }
        videoFullViewWidget.apply {
            initView(view)
            activity?.let {
                it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
            }
            addWidget(this)
            observe(onClicked, ::onFullVideoViewControllClick)
        }
    }

    private fun onFullVideoViewControllClick(callToAction: VideoFullViewWidget.CallToAction) {
        when (callToAction) {
            is VideoFullViewWidget.CallToAction.PortraitMode -> {
                activity?.let {
                    it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
                }
                showVideoView(false)
                isChangeScreenButtonClicked = true
            }
        }
    }

    private fun onClickedButton(callToAction: VideoControlWidget.CallToAction) {
        when (callToAction) {
            is VideoControlWidget.CallToAction.LandScapeMode -> {
                activity?.let {
                    it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
                }
                isChangeScreenButtonClicked = true
                showVideoView(true)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d("CALLBACKK", "onPause")
    }

    private fun getR3ConnectedInLiveVideFragment(state: BaseViewModel.LiveVideFragmentState) {

    }

    private fun notConnectedView() {
        customLoader.hide()
        notConnectedWidget.show()
        view_surface.visibility = View.GONE
        videoControlWidget.hide()
    }

    private fun showLiveVideoWhenR3Connected() {
        notConnectedWidget.hide()
        view_surface.visibility = View.VISIBLE
        videoControlWidget.show()
    }

    private fun addWidget(widget: Widget) {
        lifecycle.addObserver(widget)
    }

    private fun showVideoView(isFullVideoView: Boolean) {
        onFullScreenListener.onFullSreen(isFullVideoView)
        if (isFullVideoView) {
            videoControlWidget.hide()
            videoFullViewWidget.show()
            val params = view_surface.layoutParams as RelativeLayout.LayoutParams
            params.width = ViewGroup.LayoutParams.MATCH_PARENT
            params.height = ViewGroup.LayoutParams.MATCH_PARENT
            view_surface.layoutParams = params

        } else {
            val params = view_surface.layoutParams as RelativeLayout.LayoutParams
            params.width = ViewGroup.LayoutParams.MATCH_PARENT
            params.height =
                (240 * requireContext().applicationContext.resources.displayMetrics.density).toInt()
            view_surface.layoutParams = params
            videoControlWidget.show()
            videoFullViewWidget.hide()
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.d("ORIENTAIONNNNNN", "ORIENTATIONCHANGE")
        requireActivity().let {
            if (isChangeScreenButtonClicked) {
                Log.d("ORIENTAIONNNNNN", "BUTTONCLICKED")
                stopAutoOrientationFor3Seconds()
            } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                Log.d("ORIENTAIONNNNNN", "LANDSCAPE")
                onFullScreenListener.onFullSreen(false)
                it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
                showVideoView(true)
                isPortraitMode = false
            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                Log.d("ORIENTAIONNNNNN", "POTRIAT")
                onFullScreenListener.onFullSreen(true)
                it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
                showVideoView(false)
                isPortraitMode = true
            }
        }
    }

    private fun stopAutoOrientationFor3Seconds() {
        val handler = Handler()
        handler.postDelayed(object : Runnable {
            override fun run() {
                run {
                    isChangeScreenButtonClicked = false
                    activity?.let {
                        it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
                    }
                }
            }
        }, 5000)
    }

}

This is my Activity call back
  override fun onFullSreen(fullscreen: Boolean) {
            if (fullscreen) {
                nav_view.visibility = GONE
                window.decorView.systemUiVisibility = (android.view.View.SYSTEM_UI_FLAG_IMMERSIVE
                        or android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)

                window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
                if (supportActionBar != null) {
                    supportActionBar!!.hide()
                }
                Log.d("ORIENTAIONNNNNN", "FULLVIEW")
                requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            } else {
                nav_view.visibility = VISIBLE
                Log.d("ORIENTAIONNNNNN", "HALFVIEW")
                window.decorView.systemUiVisibility = android.view.View.SYSTEM_UI_FLAG_VISIBLE
                window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
                if (supportActionBar != null) {
                    supportActionBar!!.show()
                }
                requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            }
        }

This is my fragment i have button click for full screen and also screen rotation on sensor  on button click its working fine i am able to rotate screen because we are not depending on onConfigurationChanged method while when rotate device manually then first time when i launch app and try to rotate then portrait to landscape then onConfigurationChanged method calling but when i try to rotate to landscape to portrait then onConfigurationChanged method is not calling please help me what i am doing wrong i am following mvvm pattern  .

A: Sorry it was my mistake i got solution for this question .
when i move                 it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR this line of code at end in fragment onconfig change method its work fine


text:
Q: How to think of Lagrangians? I am struggling to come up with the "right" way to think of Lagrangians. For example, in Hamiltonian mechanics the Hamiltonian is simply the total energy of the system. In classical mechanics, taking
$$L = T - V$$
as the Lagrangian is intuitive, as it measures the amount of "active motion" in the system. However, in the general case where there is no standard Lagrangian, what is the right way to think of it? Is the idea of measuring "active motion" still the right picture to have?

A: The Lagrangian is a function that yields the correct equations of motion (EoM) through Euler-Lagrange equations (EL), that is how you should see it.
In Classical Mechanics a possible form for the Lagrangian is
$$L=T-U\tag{1}$$
Where $T$ is the kinetic energy and $U$ a (generalized, i.e. velocity dependent) potential. That's not the whole story, though. Any other function yielding the correct EoM can be regarded as a Lagrangian (see this example by Qmechanic).
Of course it is more reasonable to use the Lagrangian $(1)$ for all purposes but keep in mind that as long as it gives the correct EoM, any function can be a Lagrangian.
In fact, this can be better understood if you think that lagrangians are built using the EoM as the starting point. The Lagrangian $(1)$ has such form because it is the (simplest) function yielding Newton's second law, i.e. the EoM in classical mechanics.
The Lagrangian
$$L=T-e\varphi+\frac{e}{c}A_i\dot{q}^i\tag{2}$$
where $\varphi$ and $\vec{A}$ are the scalar and the vector potential, yields the Lorentz equations for a charged particle in a EM field i.e. it is the Lagrangian of such system.
Things get even more evident in the framework of field theory, consider e.g. the Lagrangian (density) of electromagnetic field
$$\mathcal{L}=-\frac{1}{16\pi}F_{\mu\nu}F^{\mu\nu}-J_{\mu} A^{\mu}.$$
This should provide enough motivation to consider the Lagrangian "just" the function the gives the correct EoM.

A:
However, in the general case where there is no standard Lagrangian, what is the right way to think of it?

In non-relativistic classical mechanics the Lagrangian is always:
$$
L=T-V\;,\tag 1
$$
where $T$ is the kinetic energy and $V$ is the potential energy (or "generalized potential" if it is velocity dependent as well). (Also, I suppose I should really be saying "a Lagrangian" rather than "the Lagrangian," since we can always add a total time derivative to the definition of the Lagrangian and the equations of motions will remain the same.)
The Lagrangian formalism is correct, because it can be used to generate the equations of motion via:
$$
\frac{d}{dt}\frac{\partial L}{\partial \dot q}-\frac{\partial L}{\partial q} = 0
$$
If the forces on the system can not be suitably described via a potential ($V$) then you cannot use the Lagrangian formalism and instead have to revert back to a different formalism that only uses the kinetic energy, something like:
$$
\frac{d}{dt}\frac{\partial T}{\partial \dot q}-\frac{\partial T}{\partial q} = F\;,
$$
where you can see that if we have something like $F=-\partial V/\partial q$ (or more generally $F=-\partial V/\partial q+\frac{d}{dt} \partial V/\partial \dot q$) we recover the previous equation .

Another source I read claimed it should be thought of some consequence of Noether's theorem

Not sure what this means. If you can cite the source that might be helpful. I can try to make sense of this, but I'm not sure what you really mean... For example, the Hamiltonian is often introduced when the system is time-translation invariant, and this introduction can be seen as a special case of Noether's theorem (w.r.t variation in the time parameter). But not sure what you mean by introducing the Lagrangian itself (not the Hamiltonian) via Noether's theorem. Are you quite sure about what the source "claimed"?

Update:
By the way, Eq (1) above also holds for classical electrodynamics with scalar and vector potentials: $(\phi, \vec A)$. In this case the potential $V$ is given by:
$$
V = e\phi - \frac{e}{c}\dot {\vec q}\cdot {\vec A}
$$

Update:
As pointed out in the linked answer, the form of the Lagrangian changes if we need to account for relativistic kinematics.
In relativistic mechanics, the free Lagrangian is not just $T$, nor is the free Hamiltonian just $T$. Rather, both have factors of $\gamma$ so that they transform appropriately. The Lagrangian transforms such that the action is invariant. The Hamiltonian transforms like the zeroth component of a four vector.
Relativistically, we work with the free Lagrangian $L_0$ that is given by:
$$
L_0 = -mc^2/\gamma\;,
$$
where $m$ is the rest mass.
In the latter case, the free action is invariant since:
$$
S = \int dt L_0 = -mc^2\int dt\sqrt{1-v^2/c^2} = -m\int \sqrt{c^2dt^2 - |d\vec x|^2} = -m\int ds\;,
$$
is just proportional to the invariant world line arc length.
However, if we ignore Lorentz invariance and want to make a connection to non-relativistic classical mechanics, we can add a constant $mc^2$ to the Lagrangian $L_0$ and see that:
$$
mc^2 + L_0 = T/\gamma\;,
$$
where $T = (\gamma - 1)mc^2$ reduces to the non-relativistic kinetic energy in the limit that the velocity is much less than the speed of light.

A: On how to think of Lagrangians:
In this answer I will discuss:
-Calculus of Variations in Statics
-Calculus of Variations in Dynamics
-Generalizing: Lagrangian other than in classical mechanics.
As a starting point I recommend the following discussion: Geometric derivation of the Euler-Lagrange equation by Preetum Nakkiran
The usual way to arrive at the Euler-Lagrange equation is to apply a process that involves integration by parts. On completion of that process you have a differential equation; the Euler-Lagrange equation.

At this point I want to discuss what is is about a differential equation that makes it such a powerful instrument.
The solution to a differential equation is geometrically an entire curve. (whereas an equation to find the roots of a polynomial has one or more numbers as solution). In theory of motion: you set up the appropriate differential equation, and the solution of that differential equation, combined with initial conditions, gives you the entire trajectory.
In theory of motion: the differential equation is set up to specify the differential relation for all points along the trajectory concurrently. In that sense a differential equation is both local and global. A differential equation is local in the sense that it operates in the limit of infinitisimally small scale, but at the same time global, in the sense that the equation applies concurrently for the entire trajectory.
Summerizing:
In theory of motion: the solution of a differential equation is a function that describes a trajectory.

For his discussion of the Euler-Lagrange equation Preetum Nakkiran uses a case in Statics as motivating example: the Catenary.
The following reasoning has been independently rediscovered several times. (The first to recognize it was Jacob Bernoulli, in the 1690's. I will get back to that at the end of this answer.)
Take the catenary. Divide it in subsections. Each subsection is in itself an instance of the Catenary problem. You can solve each instance, and concatenate the instances.
There is no lower bound on how far you can subdivide; the logic remains the same. You can subdivide down to infinitismally small subsections, concatenating the results back to the entire length.
This reasoning informs us that it should be possible to derive the Euler-Lagrange equation using differential operations only.
That is what Preetum Nakkiran demonstrates: a derivation of the Euler-Lagrange equation that uses differential operations only.
The differential equation is suffcient: the solution of it is a function that describes the shape of the catenary.

Calculus of Variations in Dynamics
The same reasoning applies in the case of using Calculus of Variations in theory of motion; dynamics.
There is an october 2021 answer by me in which I discuss Hamilton's stationary action

Hamilton's stationary action expresses the physical property that at each moment in time the rate of change of kinetic energy matches the rate of change of potential energy.
$$ \begin{array}{rcl}
F & = & ma \\
\int_{s_0}^s F \ ds  & = & \tfrac{1}{2}mv^2 - \tfrac{1}{2}mv_0^2   \\
-\Delta E_p & = & \Delta E_k
\end{array} $$
Recapitulating:
-Work done is defined as the integral of Force with respect to position coordinate.
-Potential energy is defined as the negative of work done.
-Kinetic energy ($\tfrac{1}{2}mv^2$) is obtained by evaluating the integral of $ma$ with respect to position coordinate.
To verify: take the derivative of kinetic energy with respect to position coordinate
$$ \frac{d(\tfrac{1}{2}mv^2)}{ds} = \tfrac{1}{2}m\left( 2v\frac{dv}{ds} \right) = m\frac{ds}{dt}\frac{dv}{ds} = m\frac{dv}{dt} = ma  \tag{1} $$

Lagrangians other than in classical mechanics
The stationary of Hamilton's stationary action expresses that a condition is imposed on a particular conversion process. At each point in time (operating at the infinitismal scale):
For any rate of decrease in potential energy there is a corresponding rate of increase in kinetic energy, and conversely for any rate of increase in potential energy there is a corresponding rate of decrease of kinetic energy.
When the trial trajectory is such that the rate of change of kinetic energy matches the rate of change of potential energy the derivative of Hamilton's action is zero: that is the stationary of stationary action.

In classical mechanics the conversion process is interconversion of kinetic energy and potential energy. The generalization is that you allow a wider scope of interconversion processes. Let there be a quantity A and a quantity B, with the property that for any change in amount of A there is a corresponding change (in opposite direction) in amount of B.
To create a Lagrangian for that you set it up in such a way that when the rate of change of A matches the rate of change of B the derivative of that Lagrangian is zero.

Historical note: Jacob Bernoulli
The Brachistochrone problem had been presented as a challenge by Johann Bernoulli (younger brother of Jacob Bernoulli).
Jacob Bernoulli was among the few mathematicians who were able to figure out that the cycloid curve is the Brachistochrone.
Calculus of Variations was developed decades later, by Euler and Lagrange, so Jacob Bernoulli did not have Calculus of Variations, nor any precursor of it.
Jacob Bernoulli noticed a property of the Brachistochrone problem that offered a pathway to solving it. He presented that observation in the form of a Lemma:

Lemma. Let ACEDB be the desired curve along which a heavy point falls from A to B in the shortest time, and let C and D be two points on it as close together as we like. Then the segment of arc CED is among all segments of arc with C and D as end points the segment that a heavy point falling from A traverses in the shortest time. Indeed, if another segment of arc CFD were traversed in a shorter time, then the point would move along AGFDB in a shorter time than along ACEDB, which is contrary to our supposition.
(Acta Eruditorum, May 1697, pp. 211-217)
Rephrased:
Every infinitisimally short subsection of the curve is itself an instance of the brachistochrone problem. Therefore a differential equation must exist that has the brachistochrone as its solution.


text:
Q: Put tar'd files in a subdirectory I have a directory setup like the following:
folder_x
file.y
file.z

I would like to create a tar file so that when it's extracted the structure will look something like this:
dir_q/folder_x
dir_q/file.y
dir_q/file.z

How could I get this to work by using tar? For reference, the current command that I'm using is:
tar -czf archive.tar.gz file.y file.z folder_x

A: I've never used the --transform option, but I gather it would do what you need:
tar -czf archive.tar.gz --transform 's,^,dir_q/,' file.y file.z folder_x

Realize the use of , instead of / as separator, so we can add a trailing slash.

A: If you don't mind creating the new directory...
mkdir dir_q;tar -C $_ -xzvf archive.tar.gz
alternatively, make a new directory, untar the file to that directory, then re-tar it from the parent directory to include it's name in the extracted version. That way you do not have to remember some super long invocation.


text:
Q: Closed-form of $\int_0^1 \operatorname{Li}_p(x) \, dx$ While I've studied integrals involving polylogarithm functions I've observed that
$$\int_0^1 \operatorname{Li}_p(x) \, dx \stackrel{?}{=} \sum_{k=2}^p(-1)^{p+k}\zeta(k)+(-1)^{p+1},\tag{1}$$
for any integer $p\geq2$. Here $\zeta$ is the Riemann zeta function.
After that I have three questions.

*

*$1^\text{st}$ Question. Is $(1)$ true? If it is, how could we prove it?

*$2^\text{nd}$ Question. If it's a well-known result could you give any reference?

*$3^\text{rd}$ Question. I think there is also a similar closed-form of $\int_0^b \operatorname{Li}_p(x) \, dx$, for any integer $b \geq 1$. What is the closed-form of this integral?

A: A simple integration by parts gives us a very simple recurrence relation:
$$\begin{align}
\int_{0}^{1}\operatorname{Li}_{p}{\left(x\right)}\,\mathrm{d}x
&=\left[x\operatorname{Li}_{p}{\left(x\right)}\right]_{0}^{1}-\int_{0}^{1}x\frac{d}{dx}\left(\operatorname{Li}_{p}{\left(x\right)}\right)\,\mathrm{d}x\\
&=\operatorname{Li}_{p}{\left(1\right)}-\int_{0}^{1}x\cdot\frac{\operatorname{Li}_{p-1}{\left(x\right)}}{x}\,\mathrm{d}x\\
&=\zeta{(p)}-\int_{0}^{1}\operatorname{Li}_{p-1}{\left(x\right)}\,\mathrm{d}x\\
\end{align}$$
From there, the desired statement can be proven via induction in the usual manner.

A: \begin{align}
\int^1_0{\rm Li}_q(x)\ {\rm d}x
=&\sum^\infty_{n=1}\frac{1}{n^q(n+1)}\tag1\\
=&\sum^\infty_{n=1}\left[\frac{(-1)^q}{n+1}+\sum^q_{j=1}\frac{1}{n^j}\operatorname*{Res}_{n=0}\frac{1}{n^{q-j+1}(n+1)}\right]\tag2\\
=&\sum^\infty_{n=1}\left[\frac{(-1)^q}{n+1}+\sum^q_{j=1}\frac{1}{n^j}\cdot\frac{1}{(q-j)!}\cdot\frac{\partial^{q-j}}{\partial n^{q-j}}\frac{1}{n+1}\Bigg{|}_{n=0}\right]\tag3\\
=&\sum^\infty_{n=1}\left[(-1)^q\left[\frac{1}{n+1}-\frac{1}{n}\right]+\sum^q_{j=2}\frac{(-1)^{q-j}}{n^j}\right]\tag4\\
=&(-1)^{q+1}+\sum^q_{j=2}\sum^\infty_{n=1}\frac{(-1)^{q-j}}{n^j}\tag5\\
=&(-1)^{q+1}+\sum^q_{j=2}(-1)^{q-j}\zeta(j)
\end{align}

Explanation:
$(1): \text{Expand the polylogarithm and integrate term by term}$
$(2): \text{Partial fractions}$
$(3): \text{Compute the residue}$
$(4): \text{Rearrange terms}$
$(5): \text{The first sum telescopes; Swap the order of summation for the second}$

A: In several places, we will use $\frac1{k(k+1)}=\frac1k-\frac1{k+1}$.
$$
\begin{align}
\int_0^1\sum_{k=1}^\infty\frac{x^k}{k^p}\mathrm{d}x
&=\color{#C00000}{\sum_{k=1}^\infty\frac1{k^p(k+1)}}\\
&=\sum_{k=1}^\infty\left(\frac1{k^p}-\frac1{k^{p-1}(k+1)}\right)\\
&=\color{#C00000}{\zeta(p)-\sum_{k=1}^\infty\frac1{k^{p-1}(k+1)}}\\
\end{align}
$$
Iterating the recursion in red, we get
$$
\begin{align}
\int_0^1\mathrm{Li}_p(x)\,\mathrm{d}x
&=\sum_{k=0}^{p-2}(-1)^k\zeta(p-k)+(-1)^{p-1}\sum_{k=1}^\infty\frac1{k(k+1)}\\
&=\sum_{k=0}^{p-2}(-1)^k\zeta(p-k)+(-1)^{p-1}
\end{align}
$$


text:
Q: Use another source address on Linux to a specific destination I've a Linux box (CentOS 7) with one interface. Its IP is 10.10.0.2. I have an alias IP address too: 10.20.0.2. I'd like to call a webservice from the alias IP address. How can I achieve this? So add the default source address to a specific ip range?

A: you need to a SNAT rule into you nat table
iptables  -t nat -A POSTROUTING -d DESTIP/PREXFIX -j SNAT --to-source 10.20.0.2

or more specific
iptables  -t nat -A POSTROUTING -d DESTIP/PREXFIX  -p tcp -m tcp --dport 80 -j SNAT --to-source 10.20.0.2


text:
Q: Task time and GC time calculation in Spark UI in Executor section I am trying to understand about  task time and GC time in executor section in Spark Databricks.
For all task it took around 20 mins actual time to complete execution of all tasks. But when I see  it shows in UI as 4.7 hr. I want to understand how Gc time and task time is calculated here because in reality it completed in lot more lesser time than what displayed.

A: Since Tasks run in parallel, the task time can be way higher than the actual time that passed.
As you can see there are 12 active tasks in this screenshot, running in parallel.


text:
Q: isdigit and scanf with infinite loop what is wrong with my program? When I enter a number for the first time, it print the statement inside if, but when I exit the program and re-enter with a char, then it print the statement inside else and the loop never exit when I keep inputting numbers.
#include <stdio.h>
#include <ctype.h>
int main()
{
    int x;
    char y;
    for(x=0;x<4;x++)
    {
            puts("Please enter a number:");
            scanf("%c",&y);
            if(isdigit(y))
            {
                    printf("Y is a digit!\n");
                    break;
            }
            else
            {
                    printf("Y is not a number, please enter another number:\n");
                    scanf("%d",&y);
            }
    }
    return 0;

}

A: I think there is a mistake in your program, particularly in the else part. You used scanf("%d",&y); instead of scanf("%c",&y);.
%d is used for an integer, but the declaration of y is char, so you must use %c.

A: "%c" does not skip leading white-space.
With scanf("%c",&y);, code reads the first char that comes along which on the 2nd pass is likely a '\n' from the previous entry.  To make scanf("%c",&y); slip leading white-space, use:
scanf(" %c",&y); // Note added space.

To read a number into char, use the following as suggested by @Deduplicator.  Note it does not need a leading ' ' as all format specifiers ignore leading white-space except for 3: "%c", "%[", "%n"
scanf("%hhd",&y);

Of course, code could simply use int y.
Note: isdigit() is only valid for 0 to UCHAR_MAX (e.g. 255) and EOF.
int y;
puts("Please enter a number:");
scanf("%d",&y);
if(isdigit(y))


text:
Q: How to Count clicks on element with javascript I just created a animation task like simple game. When you click the start game button a circle will appear on random positions at certain intervals. i have tried my best and struggling to do the following tasks :

*

*Add score +1 while click on the
 (circle) element

*Reduce score -1 while clicking rather than the
 (circle) element

Thanks in advance.. :)

var windowHeight = 0;
var parendElement;

 function startg () {
    parendElement = document.getElementById("box");
    windowHeight = window.innerHeight;
    document.body.style.height = windowHeight + "px";

    var interval = setInterval(function () {
        generateBall();
    }, 1000);
};

function generateBall() {
    var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
    var topPos = Math.floor((Math.random() * windowHeight) - 30);
    var para = document.createElement("p");
    para.style.left = leftPos + "px";
    para.style.top = topPos + "px";
    para.setAttribute("class", 'circle');
    parendElement.appendChild(para);
    removeBall(para);
}
function removeBall(ele) {
    setTimeout(function () {
        parendElement.removeChild(ele);
    }, 1000);
}

var clicks= 0;
clicks = document.getElementById('scores').valueOf();

var ballclk = document.getElementsByClassName('circle');
ballclk.onclick = function (){
    clicks++;
    console.log('clicks');
};
.circle{
    width: 50px;
    height: 50px;
    border-radius: 30px;
    position: absolute;
    background-color: blueviolet;
}
body{
    overflow: hidden;
    position: relative;
}
#box{
    width: 100%;
    height: 100%;
}
.score{
    font-size: 18px;
    color: red;
    font-weight: bold;
}
input[type=text]
{
    padding: 5px 5px;
    font-weight: 600;
    font-size: 15px;
    width: 90px;
}
button{
    padding: 4px;
}

<button onclick="startg()">Start Game</button>
Score
<input type="text" value="0" name="scores" id="scores">

A: To expand on Mykola's answer, not only do you need to set the value in the field itself, but you also need to create the  onclick event as you're creating the ball in generateBall() for it to work. Also the return value of valueOf() is the element itself, so you need to access the value then call parseInt() to convert it to a number.
For task #2, you can listen for clicks in the box div, but you need to have your p clicks call stopPropagation() so that their clicks don't bubble to the div, preventing your score from changing.
Modified code below:

var windowHeight = 0;
var parendElement;
var gameStarted = false;
var clicks;

function startg() {
  parendElement = document.getElementById("box");
  gameStarted = true;
  windowHeight = window.innerHeight;
  document.body.style.height = windowHeight + "px";
  clicks = parseInt(document.getElementById('scores').value)

  parendElement.onclick = function() {
    if (gameStarted) {
      document.getElementById('scores').value = --clicks;
    }
  };

  var interval = setInterval(function() {
    generateBall();
  }, 1000);
};

function generateBall() {
  var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
  var topPos = Math.floor((Math.random() * windowHeight) - 30);
  var para = document.createElement("p");
  para.style.left = leftPos + "px";
  para.style.top = topPos + "px";
  para.setAttribute("class", 'circle');
  para.onclick = function(e) {
    e.stopPropagation();
    document.getElementById('scores').value = ++clicks;
    console.log('clicks');
  };
  parendElement.appendChild(para);
  removeBall(para);
}

function removeBall(ele) {
  setTimeout(function() {
    parendElement.removeChild(ele);
  }, 1000);
}
.circle {
  width: 50px;
  height: 50px;
  border-radius: 30px;
  position: absolute;
  background-color: blueviolet;
}
body {
  overflow: hidden;
  position: relative;
}
#box {
  width: 100%;
  height: 100%;
}
.score {
  font-size: 18px;
  color: red;
  font-weight: bold;
}
input[type=text] {
  padding: 5px 5px;
  font-weight: 600;
  font-size: 15px;
  width: 90px;
}
button {
  padding: 4px;
}

    <button onclick="startg()">Start Game</button>
    Score

    <input type="text" value="0" name="scores" id="scores">

A: You have created the p element but you didn't added the click event to it which causes for the
Add this to the generateBall Methods
 para.onclick = function() {
    document.getElementById('scores').value = ++clicks;
    console.log('clicks');
  };

So here is the working fiddle

A: You just need to change input value after each click. So in function generateBall just add :
document.getElementById('scores').value = clicks;

Hope this helps.

A: updated with .stopPropagation() (thank you @xorspark)
Here you go, with -1 for clicks outside the circle, but I don't think this is the right way to do it,
I added 2 instead of 1 to the click event of the circle as a workaround because I couldn't get the selector body:not(.circle) to work.
also (as mentioned by @Mykola_Borysyuk) you should use:
document.getElementById('scores').value = clicks;

instead of
clicks = document.getElementById('scores').valueOf();

because you're taking the value of clicks and putting it in the input, not the other way around.
good start though :)

var windowHeight = 0;
  var parendElement;
  var clicks = 0;
  clicksInput = document.getElementById('scores');

   function startg () {
      parendElement = document.getElementById("body")
      windowHeight = window.innerHeight;
      document.body.style.height = windowHeight + "px";

      var interval = setInterval(function () {
          generateBall();
      }, 1000);
  };

  function generateBall() {
      var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
      var topPos = Math.floor((Math.random() * windowHeight) - 30);
   document.getElementById('box').onclick = function(e){e.stopPropagation();score('-')}
      var para = document.createElement("p");
      para.style.left = leftPos + "px";
      para.style.top = topPos + "px";
      para.setAttribute("class", 'circle');
      parendElement.appendChild(para);
   para.onclick = function(){score('+')}

      removeBall(para);
  }
  function removeBall(ele) {
      setTimeout(function () {
          parendElement.removeChild(ele);
      }, 1000);
  }

  function score(operation) {
   if (operation == '+') {
    clicks++;
    clicksInput.value = clicks;
    console.log('clicks');
   } else {
    clicks--;
    clicksInput.value = clicks;
    console.log('clicks');
   }
  }
.circle{
    width: 50px;
    height: 50px;
    border-radius: 30px;
    position: absolute;
    background-color: blueviolet;
}
body{
    overflow: hidden;
    position: relative;
}
#box{
    width: 100%;
    height: 100%;
}
.score{
    font-size: 18px;
    color: red;
    font-weight: bold;
}
input[type=text]
{
    padding: 5px 5px;
    font-weight: 600;
    font-size: 15px;
    width: 90px;
}
button{
    padding: 4px;
}

<button onclick="startg()">Start Game</button>
Score
<input type="text" value="0" name="scores" id="scores">


text:
Q: Is it possible to wirelessly bring a 2.4GHz signal through a cable? Yes, I know wirelessly != cable.
What I have: A cheap first person view (FPV) car.  The FPV part of it is standalone - essentially a camera connected to a battery-powered WiFi module. The remote control is a 2.4GHz model. You can stream the video over the WiFi to your smartphone screen while using the remote to control the car.
What I would like: A simple way to 'guide' the signal while the car is in a long tube. I want to drive the FPV car into a 10cm diameter cast-iron tube, around some bends, and then still be able to stream video and control the car. Currently, video drops out before the control does, after the first bend and ~5m, with the smartphone and remote both huddled at the entry-point of the tube.
Is there a way to do this? I do not want to open the car and start soldering.  I'd like to know if it was possible to somehow attach a wire to the antenna so the signal is guided through the cable, and position the other end of the cable near the smartphone. On the side of the car, the options are very limited, as that needs to stay small, but on the smartphone-side of the cable I could attach some electronics, if needed. Do not worry about the stiffness of the cable (if, say, coax would be needed,) I can push it along with the car, the car does not have to drag it.
Ideally, the pick-up at the car would not be rigidly attached to the antenna, but allow for some rotatory movement.
can i connect two similar antennas to two ends of a cable to to re-transmit the signal received from one end? this Q&A seems to indicate that the idea is doable in general, but I'd need some details on the best passive-antenna shape for this application.

A: What you are asking is possible in theory but you may find it difficult to achieve in practice with what you are working with.
Yes, you can transmit 2.4GHz signals over a coax cable of the proper type but you can't just hook a wire to the antenna and expect it to work.  There are impedances to match so that your 2.4GHz signal does couple into the coax and travels to your receiver.
Another issue is that 2.4GHz signals don't travel on coax well because at the frequency the attenuation is significant.  That's why you see antennas for devices in this this frequency range very near the radio portion of the device.  It can be done but it takes careful design.


text:
Q: List of most occurrences of element I have a list let's say {1,1,2,2,3,3,3,4,4,4}. I want to find a List of the elements that occur the most often (it has to be a list as there can be a situation like here that 3 and 4 occur most and I need to get that information. How can I achieve this using LINQ?

A: var highCountItems = source
  .GroupBy(item => item)
  .GroupBy(g => g.Count(), g => g.Key)
  .OrderByDescending(counts => counts.Key)
  .First();

int theCount = highCountItems.Key;
var theItems = highCountItems.ToList();

A: By Grouping:
var grp = list.GroupBy(i => i).ToList();
int max = grp.Max(c => c.Count());
var most = grp.Where(d => d.Count() == max)
              .Select(c => c.Key).ToList();

A: First you will have to group the numbers followed by ordering them so you will get the most frequently occurring number on the top.
int[] numbers = { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 };
var groups = numbers.GroupBy(i => i).OrderByDescending(g => g.Count());

foreach (var group in groups)
{
      // group.Key -> Represents the number in the list
}

The groups variable will contain all the groups formed from the numbers list ordered by their occurrence, meaning the first group will be the top most occurring group followed by the next. In case of same occurrences, the groups will be ordered by their occurrence in the list for example 3 & 4 have equal occurrences whereas 3 comes first before 4 and hence the group formation will be in same order.

A: A little complicated
var lst_input = new List<int>(new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 });
        var result = lst_input.Where(x => lst_input.Max(y => lst_input.Count(z => z == y)) == lst_input.Count(z => z == x)).Distinct().ToList();

But the above code is not effective when dealing with a really big array, since finding max is re-run for each element, and we could distinct the list in the first place. Another more efficient way:
var lst_input = new List<int>(new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 });
var tmp = lst_input.Distinct();
var max_val = tmp.Max(y => lst_input.Count(z => z == y));
var result = tmp.Where(x => max_val == lst_input.Count(z => z == x)).ToList();


text:
Q: Ember-CLI Resolver: Class/Sub-class Naming Convention Based on my understanding so far of the Ember-CLI / ES6 Resolver, please help me clarify the correct way to define a class and corresponding sub-class for an object.

Assuming I have an Ember.Object:
file name: orange-widget.js
export default Ember.Object.extend({
    //Code
});

Is it possible to define a sub-class of that only by referencing it in the first line?
e.g. cool-orange-widget.js
export default Ember.OrangeWidget.extend({
    //New Code
});

Or do I need to export OrangeWidget class and then import it into the sub-class?
var OrangeWidget = Ember.Object.extend({
    //Code
});

export default OrangeWidget;

...then
import OrangeWidget from 'orange-widget';

var CoolOrangeWidget = Ember.OrangeWidget.extend({
    //Code
});

export default CoolOrangeWidget;

Which is the correct method?

A: You need to import your base class into a variable and extend from that.
import OrangeWidget from 'orange-widget';

var CoolOrangeWidget = OrangeWidget.extend({
    //Code
});

export default CoolOrangeWidget;


text:
Q: Why wouldn't this vector not contain the zero vector? $[x,y,z]^T$ with $x=1$ supposedly doesn't contain the zero vector according to my study guide for my Linear Algebra midterm. I know that for any vector which is itself a vector space that it will contain itself and thus contain the zero vector. But the solution given to me is only "The plane of vectors $[x,y,z]^T$ with $x = 1$ is not a subspace of $\mathbb{R}^3$ since it does not contain the zero vector. It fails closure of vector addition and scalar multiplication as well."
Which I've done the tests for a subspace of $\mathbb{R}^3$ myself (by the way it's asking if this is a subspace of $\mathbb{R}^3$ just if you're wondering), and to me it looks like I can multiply this vector by $0$, likewise take the negation of itself and get $0$.

A: There is a lot of confusion in what you said but the bottom line is this: The set of column vectors in $\Bbb R^3$ with first entry $1$ cannot contain the zero vector because the zero vector begins with $0$.
It can also not be closed under addition because the sum of two such vectors begins with $2$ not $1$. It can also not be closed with respect to scalar multiplication by reals because scaling by $2$ makes a 2 in the first position.


text:
Q: How to sort each row in a 2d String array in java using Arrays.sort? I am trying to sort each row of a 2d String array in java.
Example:
For example, if an array contains:
ZCD
BFE
DZA

I want it to be sorted as:
CDZ
BEF
ADZ

Code:
private String[] commonCollections;

private int comparisons = 0;

public Comparable[] findCommonElements(Comparable[][] collections){

    for(int i = 0; i < collections.length; i++){
        Arrays.sort(collections[i]);
    }

    for(int i = 0; i <collections[0].length; i++){
        System.out.print(collections[0][i] + "\n");
    }

    return commonCollections;
}

Thanks. With the code above, its not sorting for some reason.

A: Your sorting seems fine. The way you are printing is the issue.
Is this what you want?
public class Main {

    public  static Comparable[][] findCommonElements(Comparable[][] collections){

        for(int i = 0; i < collections.length; i++){
            Arrays.sort(collections[i]);

        }

        return collections;
    }

   public static void main(String[] args) {

    Character [][]input= {{'Z','C','D'},{'B','F','E'},{'D','Z','A' }};

    Comparable[][] output = findCommonElements(input);

    for(int i = 0; i <output.length; i++){
        System.out.print(Arrays.toString(output[i]) + "\n");
    }
  }
}

Which produces this output:
[C, D, Z]  [B, E, F] [A, D, Z]

A: You've almost done it, you can fix your code by debugging.
Here is an approach with java8 streams
    char[][] arr = { { 'Z', 'C', 'D' }, { 'B', 'F', 'E' }, { 'D', 'Z', 'A' } };
    char[][] sorted = IntStream.range(0, arr.length).mapToObj(i -> arr[i]).peek(x -> Arrays.sort(x)).toArray(char[][]::new);
    for (char[] js : sorted)
        System.out.println(Arrays.toString(js));

output
[C, D, Z]
[B, E, F]
[A, D, Z]


text:
Q: Redux state is empty I am following a redux example to create a slice in react-redux, in my console i have no errors and the state has my vessels but it's just empty and doesnt have any data from my axios api call,
my backend is running and the api call is working fine.
vesselSlice :
import { createSlice } from "@reduxjs/toolkit";
import { api } from "../components/pages/screens/HomeScreen";
const vesselSlice = createSlice({
  name: "vessels",
  initialState: {
    vessels: [],
  },
  reducers: {
    getVessels: (state, action) => {
      state.vessels = action.payload;
    },
  },
});
export const vesselReducer = vesselSlice.reducer;
const { getVessels } = vesselSlice.actions;

export const fetchVessels = () => async (dispatch) => {
  try {
    await api
      .get("/vessels")
      .then((response) => dispatch(getVessels(response.data)));
  } catch (e) {
    return console.error(e.message);
  }
};

HomeScreen :
import React, { useEffect } from "react";
import VesselCard from "../../VesselCard";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { vesselSlice } from "../../../features/vesselSlice";
export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/api/vessels/info",
  headers: {
    "Content-Type": "application/json",
  },
});
function HomeScreen() {
  const { vessels, isLoading } = useSelector((state) => state.vessels);
  return (

      Fleet vessels :

        {vessels.map((vessel) => (
          <VesselCard vessel={vessel} />
        ))}

  );
}

export default HomeScreen;

A: You have to actually call the function fetchVessels. In this simple example, I would do it using useEffect:
import React, { useEffect } from "react";
import VesselCard from "../../VesselCard";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { vesselSlice, fetchVessels } from "../../../features/vesselSlice";
export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/api/vessels/info",
  headers: {
    "Content-Type": "application/json",
  },
});
function HomeScreen() {
  const { vessels, isLoading } = useSelector((state) => state.vessels);
  const dispatch = useDispatch();

  // This part:
  useEffect(() => {
    fetchVessels(dispatch);
  }, [dispatch]);

  return (

      Fleet vessels :

        {vessels.map((vessel) => (
          <VesselCard vessel={vessel} />
        ))}

  );
}

export default HomeScreen;


text:
Q: How to receive email for responses to posts on Stack Overflow When I post a question on Stack Overflow, I need to avoid having to log back in just to check to see if there is an answer to my post. The Preferences for my user account on Stack Overflow should have an option to select which types of responses send email.
Otherwise, I have to explicitly log back in and check, which is a waste of time. Note that the forum on www.linuxquestions.org has implemented this already, so why can't Stack Overflow implement something similar?

A: You can configure your email settings across the whole network by going to the preferences section of your user profile on any site:

As Michael Petrotta mentions, there is a link displayed when asking a new question that will open this screen. Email settings used to be displayed in other locations on the site, but they've been relocated as part of an overhaul of how email notifications are handled.


text:
Q: Differing options for UIPageViewController.transitionStyle in Xcode GUI vs Programmatic Enum I'm using a storyboard to build an app where one page requires a UIPageViewController within a ContainerView. Everything works fine, but I'd like to use the scroll transition style rather than the default "page turn" animation.
Looking at the apple docs I get two options - page curl and scroll, but when I open what I assumed would be the corresponding menu in XCode, I get the options below.

Note - regardless of which option I select in this menu, printing self.transitionStyle.rawValue on my subclass of UIPageViewController gives me "0", which corresponds to the pageCurl case of the TransitionStyle enum (see below).

Am I missing something? Does that drop-down refer to some other transitional style?

A: You look at UIViewController's modal transition style not UIPageViewController's one. If you create UIPageViewController in Storyboard you'll see another transition style in "Page View Controller" block in Interface Builder.
About UIViewController's transition style you can read here.


text:
Q: Next page after loads in React Native I'm newbie in React-native , I've just confused on how can I go to next page when the Google API successfully load to my app, mostly in the internet they used onPress but I don't have any onPress just to trigger the event instead i've implement after it successfully login data and will trigger the event, how should I do it?
From Login > Home
Apps.js
import React from 'react';
import Login from './components/login'
import SplashScreen from 'react-native-splash-screen';

const App = () => {
  React.useEffect(() =>{
    SplashScreen.hide()
  },[])
  return (
    <Login/>
  )
}

export default App;

Login.js
import React, { Component } from 'react';
import { View, StyleSheet, ToastAndroid, Button ,Text,Image} from "react-native";
import {
    GoogleSignin,
    GoogleSigninButton,
    statusCodes,
  } from '@react-native-community/google-signin';
  GoogleSignin.configure({
    webClientId: 'testttttttt.........apps.googleusercontent.com',
    offlineAccess: true,
  });
  class Login extends Component {
    constructor(props){
      super(props)
      this.state={
        userGoogleInfo : {},
        loaded: false
      }}
    signIn = async () => {
        try {
          console.log("Processing");
          await GoogleSignin.hasPlayServices();
          const userInfo = await GoogleSignin.signIn();
          this.setState({
            userGoogleInfo : userInfo,
            loaded : true
          })
          // after this it goes to another page Home.js  -----------------------------------------<<<<<<<<<

        } catch (error) {
          if (error.code === statusCodes.SIGN_IN_CANCELLED) {
            console.log("e 1");
          } else if (error.code === statusCodes.IN_PROGRESS) {
            console.log("e 2");
          } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            console.log("e 3");
          } else {
            console.log(error.message);
          }
        }
      };
      render() {
        return (
          <View style={styles.container}>
            <GoogleSigninButton
                style={{ width: 222, height: 48 }}
                size={GoogleSigninButton.Size.Wide}
                color={GoogleSigninButton.Color.Dark}
                onPress={this.signIn}
                />
              {this.state.loaded ?
                <View>
                  <Text>{this.state.userGoogleInfo.user.name}</Text>
                  <Text>{this.state.userGoogleInfo.user.email}</Text>
                  <Image
                style={{ width: 100, height: 100 }}
                source={{uri: this.state.userGoogleInfo.user.photo}}
              />
                </View>
              : <Text>Not SignedIn</Text> }
          </View>
        );
    }
}
const styles = StyleSheet.create({
    container:{
      flex:1,
      backgroundColor:'#000000',
      padding:15,
    },
  });
export default Login;

Home.js
import React from 'react';
import Login from './components/login'
import SplashScreen from 'react-native-splash-screen';
import { View,Text} from "react-native";

const App = () => {
  React.useEffect(() =>{
    SplashScreen.hide()
  },[])
  return (
    <View>
      <Text>fsaf</Text>
    </View>
  )
}

export default App;

A: You can use React Navigation
And once you have a proper setup use push method
navigation.push('YourView')

A: First, you need to add a navigation component to your project. The React Native documentation has a section about it with some libraries suggestions.
The React Navigation is hugely used and has the CommonActions that resolve your problem. After installing the React Navigation you can see this section on the documentation to dispatch the CommonActions to navigate to the Home screen after login success on your try...catch.


text:
Q: how to get a random value from one array to another in java I want to get a random array value from char[] vowel and char[] consonant into char[] firstName and char[] lastName.
My IDE (Eclipse) shows no errors for
firstName[i]=consonant [random.nextInt(consonant.length)];
however when running the code I'll get the error

`Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
0     at _01NameGenerator.main(_01NameGenerator.java:27)`

How shall I fix this statement?
// http://www.javapractices.com/topic/TopicAction.do?Id=62
import java.util.Random;

public class _001NameGenerator {

    public static void main(String[] args) {
        Random random = new Random();

        int firstNameLength = 7; // fixed length, not "random"
        int lastNameLength = 5;

        System.out.println("Your firstname will be "+firstNameLength+" and you lastname "+lastNameLength+" characters long.");

        char[] vowel = {'a', 'e', 'i', 'o', 'u', 'y'};
        char[] consonant = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z'};

        char[] firstName = new char[firstNameLength];
        char[] lastName = new char[lastNameLength];

        boolean wechsel = true;

        for (int i = 0; i < firstNameLength; i++) {

            if (wechsel == true){

                firstName[i]=consonant [random.nextInt(20)];  // length of consonant array
                wechsel = false;

            } else {

                firstName[i]=vowel [random.nextInt(6)]; // length of vowel array
                wechsel = true;
            }

        }

        for (int i = 0; i < lastNameLength; i++) {

            if (wechsel == true){

                lastName[i]=consonant [random.nextInt(20)];
                wechsel = false;

            } else {

                lastName[i]=vowel [random.nextInt(6)];
                wechsel = true;
            }

        }

        System.out.println(firstName + "\n" + lastName);

    }

}

A: char[] firstName = {};
char[] lastName = {};

These two lines generate empty lists, so whenever you try to add something it gives an ArrayIndexOutOfBoundsException: 0.
Since you have the random length above, try this instead:
char[] firstName = new char[firstNameLength];
char[] lastName = new char[lastNameLength];

Also, in case you wouldn't have known the length of the arrays beforehand, you can use an ArrayList, which are created for these kind of purposes.

A: You've initialized firstName and lastName as zero-length arrays. So on your first iteration, you try to assigned a value to firstName[0], but "0" is an invalid index for an empty array, hence the exception.
You should initialize the arrays with lengths:
char[] firstName = new char[firstNameLength];
char[] lastName = new char[lastNameLength];

A: The answer is obvious: both of these arrays are zero length:
    char[] firstName = {};
    char[] lastName = {};

A: You declare firstName and lastName arrays as an empty zero-length arrays. You should declare as follows according to your code:
char[] firstName = new char[firstNameLength];
char[] lastName = new char[lastNameLength];

This prevent you from getting ArrayIndexOutOfBoundsException.


text:
Q: ADB Equivalent for ThreadX I'm interested in looking into the ThreadX RTOS and was wondering if anyone knew if there was an adb type equivalent in ThreadX. I'm imagining using a device with ThreadX and using some adb-like tool to view hte file system or push files to the device.
Is this possible?
Thanks!

A: ThreadX is intended for devices much smaller than anything that runs Android; you must give up on the idea that there will be any debug facility incorporated in your target.  With embedded devices, your debug capabilities are in the development tools which run on a Windows PC (and yes, most embedded tools only run on Windows) attached to the target.  That said, there are excellent debug tools built into any embedded IDEs these days.
If you are interested in ThreadX, get a development board from Renesas that incorporates a debugger link.  These are typically available for less than $50 USD.  The Renesas IDE, E2Studio, has great support for ThreadX.  I also understand that the watch from Pine64 runs ThreadX but I am awaiting that device's arrival and have not used the Nordic tools before so I can't say how well ThreadX is integrated into that.
Finally, and I have no vested interest in this, if you are starting in embedded code you might want to check out FreeRTOS instead of ThreadX.  I can't say it is superior in any technical way; but, if you search here you'll see there is a much bigger community of FreeRTOS users than ThreadX.  To me, they both work fine, its easier to find help with FreeRTOS as a quick search will reveal 10x the postings for FreeRTOS vs ThreadX.

A: Azure RTOS has a component called Azure RTOS TraceX which can be used understand threadx services(threads, queues) usage. This is a windows based tool. I don't have experience using the same but i think it is possible. I think your threadx needs to complied with the Tracex enabled, and it can create tracex event buffer which can then be used with the tool. If you are using Filex and some sort of memory i think theoretically it can be exported easily. Otherwise you can use print dumps or some similar hack to get it. I might try this soon and will update.
NOTE: I haven't used TraceX yet so this is all in theory. But most probably possible


text:
Q: Laravel Angular how to filter date on Carbon String? how can you filter date on a JSON time like created_at like 2016-02-29 19:20:00 ?
The Angular filter only works on timestamp.
How can i change the output to the timestamp?

A: If I understand your question you want to do manipulate the created_at time or w/e time. I would highly suggest using moment.js for this.
Few examples from their page.
moment().format('MMMM Do YYYY, h:mm:ss a'); // February 28th 2016, 2:17:50 am
moment().format('dddd');                    // Sunday
moment().format("MMM Do YY");               // Feb 28th 16
moment().format('YYYY [escaped] YYYY');     // 2016 escaped 2016
moment().format();

A: Same problem with me, below my solution:
In Json:
data[i].itemDate = data[i].itemDate.replace(/(.+) (.+)/, "$1T$2Z")
data[i].itemDate = new Date(data[i].itemDate);

Now you can use Angular filter

A: if you use YYYY-MM-DDTHH:mm:ss.sssZ time format you must be shure in a itemDate in UTC time zone. If your itemDate in GMT+0200 (for example) just drop "Z" from end, it helps to me :)
itemDate.replace(/(.+) (.+)/, "$1T$2")


text:
Q: OSGi - How to get OSGI service from Spring-DM? How to get OSGI service from Spring-DM?

like, Spring Bean..
ApplicationContext.getBean(id)...

A: Inject it using xml like below
 <osgi:reference id="contactDAOService" interface="com.javaworld.sample.osgi.spring.contact.ContactDAO"/>

Then you can even get it from the application context. Better though inject it into another bean.


text:
Q: разработка схемы ip-адресации Можете, пожалуйста, помочь в разработке схемы адресации. Вот у меня 4 филиала по 18,9,9,7 устройств. я беру диапазон 192.168.0.0/26 первому филиалу назначению диапазон 192.168.0.0/27, второму 192.168.0.32/28, третьему 192.168.0.48/28 и вопрос с 4 диапазоном. Какой он будет его диапазон IP адресов?

A: Правильное распределение адресов делается следующим образом.
Филиал 1. 18 устройств. 16 адресов мало, 32 достаточно. Отдаём на подсеть пять последних бит. Получаем подсеть 192.168.0.0/27, т.е адреса 192.168.0.0-192.168.0.31. 192.168.0.0 - адрес подсети, 192.168.0.31 - broadcast.
Филиал 2. 9 устройств. 8 адресов мало, 16 достаточно. Подсети даём четыре последних бита, т.е. выбираем 192.168.0.32/28. Диапазон 192.168.0.32-192.168.0.47. Адрес подсети - 192.168.0.32, broadcast 192.168.0.47.
Филиал 3. То же, что и филиал 2. Подсеть 192.168.0.48/28 (192.168.0.48-192.168.0.63). Адрес подсети 192.168.0.48, broadcast - 192.168.0.63.
Филиал 4. 7 устройств. Тут чуть посложнее. Вроде бы, 8 адресов достаточно. Но один уйдёт на адрес подсети, другой на широковещание. Поэтому придётся брать 16. Подсеть 192.168.0.64/28 (192.168.0.64-192.168.0.79). Адрес подсети 192.168.0.64, broadcast - 192.168.0.79.
Здесь не учитывалось, что если подсетям нужно между собой общаться, то добавится ещё одно устройство - маршрутизатор, которому нужен дополнительный адрес. Впрочем, в данном случае адресов достаточно и маршрутизатору хватит.
Если же это не учебное задание, а реальное, то для упрощения администрирования и для получения возможности безболезненного масштабирования, лучше для филиалов взять подсети 192.168.x.0/24, где x меняется от 1 до 4 и означает номер филиала. В такой адресации разобраться будет проще.


text:
Q: How do I get a keystroke systemwide to trigger an action on  text in a selected item, whether file, mail message, selected text, etc.? In this question I asked how to create a window containing a html rendered preview of text formatted with Markdown. I would also like to be able to have a single keystroke that systemwide will produce these results. I am thinking an Automator service might be the best approach, but it might not be.
I want to be able to select either text or files as input, and pass either the selected text OR the text contained in the file through the Markdown filter and display the resulting HTML in some sort of preview window.
Any pointers? If it can be a single service, great; if not, a service that runs when the Finder is active that accepts files and a separate service that accepts selected text that runs when any other program is active could work.
I'm not looking for the general case here; it's a core feature on the Mac to use the Keyboard Shortcuts pane in System Preferences to assign a global shortcut to an Automator-generated service. I'm looking for a way for a single keystroke to generate a preview of Markdown-rendered text whether it's a selected text file in the Finder or selected text in another program. Spacebar combined with Quicklook could work in Finder and Command-Option-Shift-M could work for selected text, but I a way for one keystroke to serve the function of "Preview Markdown Results" in any context, whether it's text, a file, a selected mail message, etc. Get the text from the selected item, render it, and display it in a window.

A: My solution to mapping keyboard shortcuts to arbitrary services (as well as general workflows, application launches and scripts) is FastScripts.
Try it for free and pay if you feel you can or need more than 10 shortcuts to be active at the same time.


text:
Q: Integer getting default value 0 where it required to be NULL in Java My requirement looks simple, but I feel I'm doing something wrong in code.
All I need is to insert "null" in Oracle Database when nothing is passed from InputText field of UI.
PaymantSpecFormPage.xhtml
<h:inputText id="startWeek" value="#{flowScope.paymentSpecVO.paymStartWk}" styleClass="inputTypeForm" maxlength="4"/>

PaymentSpecVO.java
public class PaymentSpecVO extends BaseVO<PaymentSpec> {
   private Integer paymStartWk;

   public Integer getPaymStartWk() {
      return paymStartWk;
   }
   public void setPaymStartWk(Integer paymStartWk) {
      this.paymStartWk = paymStartWk;
   }
}

And in my DB Table
COLUMN_NAME      DATA_TYPE    NULLABLE    DEFAULT_VALUE
------------     ---------    --------    -------------
PAYM_START_WK    NUMBER(4,0)    Yes             null

And when I enter nothing in inputText, then instead of null, 0 is getting entered in Table, which has different meaning in my business logic, please help me to do necessary code changes.

A:
And when I enter nothing in inputText, then instead of null, 0 is getting entered in table

This problem is recognizable as Tomcat's EL parser not taking into account that you're using Integer instead of int. You need to add the following VM argument to Tomcat startup options:
-Dorg.apache.el.parser.COERCE_TO_ZERO=false

See also:

*

*h:inputText which is bound to Integer property is submitting value 0 instead of null

*Work around for faulty INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL in Mojarra JSF 2.1

It solved my half of problem, and now its storing null values, but while on retrieve it shows 0 again

This problem is recognizable as JDBC under the covers using ResultSet#getInt() instead of ResultSet#getObject(). This is however essentially a different problem than the first one. You didn't tell anything about how your database access layer is setup, so it's hard to point out a concrete solution.

A: I don't know how you are reading that xhtml.
At java layer, you can override either the constructor of PaymentSpecVO or the setter for paymStartWk

A: Try this
    public class PaymentSpecVO extends BaseVO<PaymentSpec> {
    private String paymStartWk;

    public String getPaymStartWk() {
    return paymStartWk;
    }
    public void setPaymStartWk(Integer paymStartWk) {
    this.paymStartWk = paymStartWk+"";
  }
}

But then you might be needing a lot of parsing there.
Edit*
If you enter nothing to your "input Text" the passed value is null but since you're catching it with an Integer, it interprets null to 0.
So when you save it, even after manipulating methods and variables to null , it will store "0" , because basically thats the default value.
Another solution I think is making a custom class that stores Integers
Example :
    public class IntegerVal extends Number {
    private Max_val = 10000000;
    private Min_val = -10000000;
    private String default = null;
    }

you can do whatever implementations you want ,, like returning null,
You can use that as a substitute to the Integer Class you are using , if you dont wanna use String


text:
Q: What does "that place is a real bucket shop and they tend to work only with pikers" mean? I was talking to my attorney, from the esteemed firm of Dewey, Cheetum and Howe, and he made the above remark in response to a financial statement that I had produced earlier.  What did Bernie mean?

A: A "bucket shop" is an unethical business operation:

A fraudulent brokerage operation in which orders to buy and sell are accepted but no executions take place. Instead, the operators expect to profit when customers close out their positions at a loss.

or:

A brokerage that makes trades on a client's behalf and promises a certain price. The brokerage, however, waits until a different price arises and then makes the trade, keeping the difference as profit.

(Investopedia.com notes that the latter definition "comes from more than 50 years ago, when bucket shops would do trades all day long, throwing the tickets into a bucket. At the end of the day they would decide which accounts to award the winning and losing trades to.")
A "piker" is a small-time player, someone who operates cheaply and takes only small risks in a very cautious manner.
So, Bernie is saying that this place is a shady operation that caters to cheap, chintzy, risk-averse individuals and tries to continuously cheat them out of small amounts of money; they will throw in only an occasional small payoff to a customer to offset a part of the overall loss suffered, so as to keep him hooked on the possibility of getting a big payoff.


text:
Q: Stretch canvas to grid I have created a custom canvas which I would need to stretch behind two textblocks.
Heres the entire code
                                    <Grid VerticalAlignment="Top" HorizontalAlignment="Right">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>
                                        <Canvas HorizontalAlignment="Stretch" Height="45" VerticalAlignment="Top" Grid.ColumnSpan="2" >
                                            <Rectangle Height="30" Stroke="Black" Width="70" RadiusY="17.167" RadiusX="17.167" Canvas.Top="15">
                                                <Rectangle.Fill>
                                                    <RadialGradientBrush>
                                                        <GradientStop Color="#FF096016"/>
                                                        <GradientStop Color="#FF0FEF6F" Offset="1"/>
                                                    </RadialGradientBrush>
                                                </Rectangle.Fill>
                                            </Rectangle>
                                            <Ellipse Height="5" Width="5" RenderTransformOrigin="0.5,0.45" Fill="White" Stroke="Gray" Canvas.ZIndex="2" Canvas.Left="33"/>
                                            <Ellipse Height="5" Stroke="Black" Width="5" RenderTransformOrigin="-0.45,0.2" Fill="#FF99A19A" Canvas.Left="17" Canvas.Top="18"/>
                                            <Ellipse Height="5" Stroke="Black" Width="5" RenderTransformOrigin="-0.45,0.2" Fill="#FF99A19A" Canvas.Left="48" Canvas.Top="18"/>
                                            <Path Data="M143.5,193.5 C127.75,210.5 127.75,210.5 127.75,210.5" Height="17" Stretch="Fill" UseLayoutRounding="False" Width="15.75" Canvas.Left="19.75" Canvas.Top="3.5"/>
                                            <Path Data="M128,209 L141.99998,192.16666" Height="17.833" Stretch="Fill" Stroke="#FF99A19A" UseLayoutRounding="False" Width="15" Canvas.Left="20" Canvas.Top="2.167"/>
                                            <Path Data="M143.5,192.16699 L158.08334,210.25" Height="19.083" Stretch="Fill" Stroke="#FF99A19A" UseLayoutRounding="False" Width="15.583" Canvas.Left="35.5" Canvas.Top="2.167"/>
                                        </Canvas>

                                        <TextBlock Height="30" Margin="0,20,0,0" TextAlignment="Right" Name="priceTextblock" Text="{Binding Price}" VerticalAlignment="Top" FontFamily="Calibri" FontWeight="Bold"/>
                                        <TextBlock Width="50" Margin="5,20,0,0" Height="30" TextAlignment="Left" Name="currencyTextblock" Text="{Binding SelectedCurrency.code}" VerticalAlignment="Top" Grid.Column="1" FontFamily="Calibri" FontWeight="Bold"/>
                                    </Grid>

though the horizontal alignment is set to stretch nothing is happening. What am I missing, please help.
Thanks in advance
EDITS
Using Grid instead of canvas
                                    <Grid VerticalAlignment="Top" HorizontalAlignment="Right">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>
                                        <Grid HorizontalAlignment="Stretch" Height="45" VerticalAlignment="Top" Width="70">
                                            <Rectangle Margin="0,15,0,0" Stroke="Black" RadiusY="17.167" RadiusX="17.167">
                                                <Rectangle.Fill>
                                                    <RadialGradientBrush>
                                                        <GradientStop Color="#FF096016"/>
                                                        <GradientStop Color="#FF0FEF6F" Offset="1"/>
                                                    </RadialGradientBrush>
                                                </Rectangle.Fill>
                                            </Rectangle>
                                            <Ellipse Height="5" Margin="33,0,32,0" VerticalAlignment="Top" Stroke="Gray" RenderTransformOrigin="0.5,0.45" Fill="White" Canvas.ZIndex="2"/>
                                            <Ellipse HorizontalAlignment="Left" Margin="17,18,0,22" Stroke="Black" Width="5" RenderTransformOrigin="-0.45,0.2" Fill="#FF99A19A"/>
                                            <Ellipse HorizontalAlignment="Right" Margin="0,18,17,22" Stroke="Black" Width="5" RenderTransformOrigin="-0.45,0.2" Fill="#FF99A19A"/>
                                            <Path Data="M143.5,193.5 C127.75,210.5 127.75,210.5 127.75,210.5" Height="17" Margin="19.75,3.5,34.5,0" Stretch="Fill" UseLayoutRounding="False" VerticalAlignment="Top"/>
                                            <Path Data="M128,209 L141.99998,192.16666" HorizontalAlignment="Left" Height="17.833" Margin="20,2.167,0,0" Stretch="Fill" Stroke="#FF99A19A" UseLayoutRounding="False" VerticalAlignment="Top" Width="15"/>
                                            <Path Data="M143.5,192.16699 L158.08334,210.25" HorizontalAlignment="Right" Height="19.083" Margin="0,2.167,18.917,0" Stretch="Fill" Stroke="#FF99A19A" UseLayoutRounding="False" VerticalAlignment="Top" Width="15.583"/>
                                        </Grid>

                                        <TextBlock Height="30" Margin="0,20,0,0" TextAlignment="Right" Name="priceTextblock" Text="{Binding Price}" VerticalAlignment="Top" FontFamily="Calibri" FontWeight="Bold"/>
                                        <TextBlock Width="50" Margin="5,20,0,0" Height="30" TextAlignment="Left" Name="currencyTextblock" Text="{Binding SelectedCurrency.code}" VerticalAlignment="Top" Grid.Column="1" FontFamily="Calibri" FontWeight="Bold"/>
                                    </Grid>

A: You need to set column width to *. It tells to get all available space
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>


text:
Q: vector plus unique_ptr to an object, memory not freed? So, I'm trying to use vectors together with smart pointers to have easier time with memory management, and... well, I'm having problems.
That's the (greatly shortened) version of my code:
bulletManager.h:
class BulletManager
{
    public:
        BulletManager();
        virtual ~BulletManager();

        void AddBullet(int type, double x, double y, double vx, double vy);
        void EraseAllBullets();
    protected:
    private:
        std::vector<std::unique_ptr<Bullet>> bullets;
};

bulletManager.cpp:
BulletManager::BulletManager()
{
    bullets.reserve(50000);
}
void BulletManager::AddBullet(int type, double x, double y, double vx, double vy)
{
    for(int i=0;i<1000;i++) bullets.push_back(std::unique_ptr<BasicBullet>(new BasicBullet(type, x, y, vx, vy)));
}
void BulletManager::EraseAllBullets()
{
    bullets.clear();
}

The BasicBullet class is a subclass of the abstract Bullet class.
To have easier time seeing the memory usage changes, I've made the AddBullet functions generate 1000 objects and also put "char tab[10000]" in the bullet class.
Now, what happens (according to the Task Manager) is:

*

*Calling AddBullet once -> memory usage increases slightly

*Calling EraseAllBullets after that -> memory usage doesn't drop at all!

*Calling AddBullet a couple of times -> significant memory usage increase

*Calling EraseAllBullets after that -> most memory is freed, but not all!

The effect isn't very big and seems to slow down - the program starts with 10MB of RAM usage and after using only these two functions for a while, with each vector clear the memory usage drops only to 15-20MB.
Am I doing something wrong? Even if that's supposed to happen, I would still prefer if I was able to free all memory that I've allocated.

A: You can't rely on task manager to tell you how much memory your application has allocated/available. When you free the memory it may well be reclaimed by a pool within the C++ runtime for later reuse by your application rather than returned to the OS.

A: You're doing nothing wrong, you just have the wrong assumptions.
The behaviour you're observing can come from two totally different things:

*

*std::vector::clear() is only supposed to delete the objects contained in the vector, not to actually release the memory of the vector itself. As cppreference.com puts it: "Many implementations will not release allocated memory after a call to clear(), effectively leaving the capacity() of the vector unchanged." You can work around this particular issue by using std::vector<...>().swap(vectorToClear); instead of clear(): that swaps a new temporary, empty vector with yours, effectively releasing all the memory yours uses.

*C++'s delete operator does not necessarily return the memory to the system. It just frees the memory so that it is usable again by new, again there is no requirement that the system gets the memory back. There is no workaround to that behaviour, it depends on your runtime (ie. compiler).


text:
Q: Reactivity in nuclear fusion In nuclear fusion, the graph of reactivity is shown as below.
How can we explain that by increasing the temperature after a certain value, the reactivity decreases?

A: The main reason for the peak in the reactivities is a nuclear resonance effect. To show this, it's worth looking into the rich physics of cross-sections (see Bosch & Hale, Nuclear Fusion, 1992).

There are three main factors that affect fusion cross-sections (plotted above with data from Bosch & Hale),
\begin{equation}
\sigma = S(E) \frac{1}{E}\exp{\left(-\frac{B_G}{\sqrt{E}}\right)}\,.
\end{equation}

*

*The factor $\frac{1}{E}$ derives from the effective size of a particle due to its de Broglie wavelength,
\begin{equation}
\text{effective size} \sim \pi \lambda_{\mathrm{dB}}^2  = \pi\frac{h^2}{p^2} =\pi \frac{h^2}{2mE} \propto \frac{1}{E}\,.
\end{equation}

*The exponential factor derives from the tunneling probability through the potential barrier created by the Coulomb repulsion between the reactants, \begin{equation}
\text{tunneling probability} \propto  \exp{\left(-\frac{\pi \alpha Z_1 Z_2  \sqrt{2m_rc^2}}{\sqrt{E}}\right)} \equiv \exp{\left(-\frac{B_G}{\sqrt{E}}\right)}\,,
\end{equation}
where $Z_1$ and $Z_2$ are the atomic numbers of the particles, $m_r$ is the reduced mass of the system, $\alpha={k_e e^2}/{\hbar c}$ is the fine structure constant, and $B_G$ is known as the Gamow constant (well-explained in this wiki entry).

*The factor $S(E)$ is the so-called S-function and was introduced by astrophysicists to capture the remaining, relatively slowly varying nuclear physics contribution to the cross-section. In fact, the S-function varies so slowly that it can be plotted on linear scales (plotted below with data from Bosch & Hale). Hence it is often more useful to compare the S-functions of similar reactions, rather than the cross sections. (For more information about the astrophysical origin of the S-function see this review article by Margaret Burbidge et al., Rev. Mod. Phys., 1957.)

The peaks in the S-functions are due to resonances, which arise only at certain energies when the relative phase and amplitude of the internal bound wavefunction and external traveling wavefunction of the quasi-particle match well and facilitate tunneling. This causes the cross sections and reactivities to peak for DT and $\mathrm{D}\,^3\mathrm{He}$, while the DD reaction is far from resonance in the plotted energy range.

A: At low temperatures the reactants in each of the reactions will not have enough energy on average to overcome electromagnetic repulsion and get close enough so that they can interact via the strong force. But if the temperature is too high then the reactants will have so much energy on average that the strong force cannot bind them together and they will just go past each other. Also, collisions with fast moving particles will break apart reaction products faster than they can be formed. So for each of the reactions there is an ideal temperature - not too hot, not too cold - at which the reaction rate is maximised.


text:
Q: SwiftUI on macOS, how to use custom image symbol on Button? READ THE QUESTION CAREFULLY, THIS IS A MAC APP, systemName is not available on mac os
I'm trying to build a simple application using swiftUI on macOS, however I'm having some trouble displaying some icons.
I have now read everywhere that you need to download the SF Symbols app and export the symbols yourself in order to use them, so I did that, then I added the exported symbol to the .xcassets and now I'm trying to create a button with an image, so here is the code:
import SwiftUI

struct ActionBar: View {

    var body: some View {
        HStack {
            Spacer()
            Button(action: {

            }) {
                Image("Plus")
                    .font(Font.system(size: 24, weight: .light))
                    .foregroundColor(Color.red)
                Text("Test")
            }
        }
        .frame(maxWidth: .infinity)
        .padding()
        .background(Color.init(red: 0.8, green: 0.8, blue: 0.8))
    }
}

struct ActionBar_Previews: PreviewProvider {
    static var previews: some View {
        ActionBar()
    }
}

I have tried many variations, for example:
Image(nsImage: NSImage(name: "Plus"))

but all the information out there, including apples own documentation only talk about UIImage which as far as I understood is part of UIKit which is the iOS version of the UI framework, has anybody gotten this to work on macOS?
Thanks a lot!
Edit: the asset was imported as a Image Symbol Set, Xcode doesn't throw any errors as I just took the svg generated by the SF Symbols app and put it directly on the assets.
Edit 2: I just run into this post which states SVG support is wonky... I tried converting the SVG into a PNG, but xcode does not accept pngs as Symbol sets... so, I guess this feature is just plain broken? which sucks...

A: In MacOS, there are no systemImages available. But NSImage.Name prov ides the alternative option. This link show most of the MacOS system default icons.
This is an example of NSImage.Name :
Icon(NSImage.refreshTemplateName)

Following is the Icon view definition :
struct Icon: View {
    var image: NSImage.Name
    var body: some View {
        Image(nsImage: NSImage(named: image)!)
            .renderingMode(.original)
            .resizable()
            .scaledToFit()
    }
    init(_ image: NSImage.Name){
        self.image = image
    }
}

P.S. Image view does not have a modifier called .font(). Please check its documentation for proper syntax.
Edit: You can skip the extra view by following format.
Image(nsImage: NSImage(name: NSImage.addTemplateName))

The list of NSImage.Names are here

A: you don't need to download or export the symbols yourself, just do this, and it will work in ios and mac catalyst as well as EDIT: macOS Monterey and also macOS 11:
import SwiftUI

struct ContentView: View {
var body: some View {
    HStack {
        Spacer()
        Button(action: {

        }) {
            Image(systemName: "plus")
                .font(Font.system(size: 24, weight: .light))
                .foregroundColor(Color.red)
            Text("Test")
        }
    }
    .frame(maxWidth: .infinity)
    .padding()
    .background(Color.init(red: 0.8, green: 0.8, blue: 0.8))
}
}

A: Here's my solution, but this is very much of a hack, and I don't know if Apple would approve it. So consider this answer for "educational purposes", I guess.
Concept
The main idea is to modify the SVG file exported by the SF Symbols app so that it only contains one instance of the selected symbol instead of the full template, and to use the SVGKit framework to display it, via an NSViewRepresentable object.
Export
Use the SF Symbols app on your Mac and select the symbol you want to use, then do "Export Custom Symbol Template".
Modify
Open the exported SVG file in a text editor, such as Sublime Text or CotEditor.
Delete everything in the file except the header and the "Symbols" field, which should only contain the symbol variation you want to use. Then change the size of the rendered canvas and also align the symbol properly.
For example, if you want to use the "Regular-L" version of the "plus" symbol, your final "plus.svg" file should be like this:
<?xml version="1.0" encoding="UTF-8"?>
<!--Generator: Apple Native CoreSVG 123-->
<!DOCTYPE svg
PUBLIC "-//W3C//DTD SVG 1.1//EN"
       "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="128" height="128">
 <!--glyph: "uni10017C.medium", point size: 100.000000, font version: "Version 15.0d7e11", template writer version: "5"-->

 <g id="Symbols">
  <g id="Regular-L" transform="matrix(1 0 0 1 0 100)">
   <path d="M 67.4316 17.3828 C 70.0684 17.3828 72.2168 15.2832 72.2168 12.7441 L 72.2168 -30.3711 L 114.062 -30.3711 C 116.65 -30.3711 118.848 -32.5684 118.848 -35.1562 C 118.848 -37.793 116.65 -39.9414 114.062 -39.9414 L 72.2168 -39.9414 L 72.2168 -83.1055 C 72.2168 -85.6445 70.0684 -87.7441 67.4316 -87.7441 C 64.8438 -87.7441 62.6953 -85.6445 62.6953 -83.1055 L 62.6953 -39.9414 L 20.8496 -39.9414 C 18.2617 -39.9414 16.0645 -37.793 16.0645 -35.1562 C 16.0645 -32.5684 18.2617 -30.3711 20.8496 -30.3711 L 62.6953 -30.3711 L 62.6953 12.7441 C 62.6953 15.2832 64.8438 17.3828 67.4316 17.3828 Z"/>
  </g>
</g>
</svg>

To sum up:

*

*Keep the header

*Keep the id="Symbols" field

*In the Symbols field, keep only one category, in my example id="Regular-L"

*Change the size in the header, in my example width="128" height="128"

*Align the symbol by changing the last two parameters of the transform field, in my example transform="matrix(1 0 0 1 0 100)" (x 0 and y 100)

Install SVGKit

*

*Close Xcode

*Install SVGKit (https://github.com/SVGKit/SVGKit) using the Cocoapods version

*Open the .xcworkspace file made by Cocoapods

Make a view
Add the modified plus.svg file to your project (not in the assets catalog, just in the project itself)
Make an NSViewRepresentable struct like this:
import SVGKit

struct IconView: NSViewRepresentable {

    let name: String

    func makeNSView(context: Context) -> SVGKFastImageView {
        let img = SVGKImage(named: name)!
        return SVGKFastImageView(svgkImage: img)!
    }

    func updateNSView(_ nsView: SVGKFastImageView, context: Context) {
        // not implemented
    }

}

Use the view
Then use it in your ContentView (give it a frame so that it doesn't fill up the whole window), for example:
struct ContentView: View {
    var body: some View {
        VStack {
            IconView(name: "plus")
                .frame(width: 200, height: 200, alignment: .center)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

A: 2021, SwiftUI 2
sample on SF sybmols symbols library
import SwiftUI

@available(OSX 11.0, *)
public extension Text {
    static func sfSymbol( _ sysName: String) -> Text {
        return Text(Image(systemName: sysName))
    }

    /// You need to use .fixedSize() manually!!!!
    static func sfIcon( _ sysName: String, size: CGFloat) -> Text {
        return Text(Image(systemName: sysName))
            .font(.system(size: size))
    }

    static func sfSymbolAndText(sysName: String, text: String) -> Text {
        return Text("\(sysName.asSfSymbol())\(text)")
    }
}

@available(OSX 11.0, *)
public extension String {
    func asSfSymbol() -> Image {
        Image(systemName: self)
    }
}

usage:
Text.sfIcon("doc.on.doc.fill", size: 13)

Text.sfSymbol("doc.on.doc.fill")

to put SF symbol in the middle of the text:
Text("Start of the text \( "doc.on.doc.fill".asSfSymbol() ) end of the text"


text:
Q: Haskell program coverage I'm trying to use the ghc -fhpc command in order to create a .tix file, but after I enter the command ghc -fhpc filename, nothing appears.
What should I do?

A: You must execute the program. HPC shows the coverage of a particular run, it isn't a static analysis that occurs at compile time.
EDIT
For example.  Does this not work for you?
% cat x.hs
main = getChar >>= print
% ghc -fforce-recomp -fhpc x.hs
[1 of 1] Compiling Main             ( x.hs, x.o )
Linking x ...
% ./x
x
'x'
% ls x.tix
x.tix

If the above doesn't work then you have a tooling issue.
EDIT 2:
If your program isn't terminating normally then the .tix file might not be getting written.  You need a normal termination and not some sort of segfaulted or otherwise-aborted run.


text:
Q: How to call ::TerminateProcess (windows) for a QProcess in Qt? I really need to kill a QProcess and all its childs on windows and I understand windows's API ::TerminateProcess is my best friend. I have tried taskkill but it still does't kill the process.
QProcess::execute("taskkill /f /t ssh.exe");
QProcess::execute("taskkill /f /t rsync.exe"); // no luck

So ::TerminateProcess is the most brute way of killing a processing but how do I get handle of the QProcess that I started so I can use it?
Here is my code.
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    syncProcess = new QProcess(this);

    connect( syncProcess, SIGNAL( finished(int)), this, SLOT( syncFinished(int)) );
}

void MainWindow::sync()
{
    QString rsync_cmd = QString("rsync/rsync -a root@%1:/root '%2'").arg( ip ).arg( destPath );

    syncProcess->start( rsync_cmd );

    _syncInProgress = true;
}

This starts rsync which in turns starts ssh. If user cancels, I want to kill both of them. Even when I called the taskkillabove for both ssh and rsync, they don't get terminated and continue syncing.
So my question is how to get handle of QProcess and more ultimately how can I kill/terminate rsync and ssh processes?
I only want my solution to work on Windows 7, other platforms are not important.
▼Update▼
Here is my code where I am cancelling. I have QProgressDialogwhen user clicks cancel button, the following function gets called where I try to kill the process but it survives.
void MainWindow::syncProgressCancelled()
{

    disconnect( syncProgress.data(), SIGNAL( canceled()), this, SLOT(syncProgressCancelled()) );

    _syncInProgress = false;

    syncProgress->close(); // this just closed toe progress dialog

    // make sure to kill the underlying ssh or rsync if running

//    QProcess::execute("taskkill /f /t ssh.exe");
//    QProcess::execute("taskkill /f /t rsync.exe");

    syncProcess->terminate(); // kill doesn't work either

}

A: If you're starting a non-detached process, then QProcess gives you all the tools you need. You can use either QProcess::kill or QProcess::terminate, as needed. No winapi needed.
int main(int argc, char ** argv) {
  QApplication app(argc, argv);
  QPushButton kill("Kill");
  kill.show();
  QProcess process;
  process.start("rsync ...");
  QObject::connect(&kill, &QPushButton::clicked, &process, &QProcess::kill);
  QObject::connect(&process, &QProcess::finished, &app, &QCoreApplication::quit);
  return app.exec();
}

If you were to start a detached process, then the startDetached method can output a pid that you can use with native api.