text:
Q: How is a photon created when an electron jumps to a lower orbit? Everyone is taught that when an electron jumps from a high to a lower orbit, the difference in energy is emitted as a photon.
However, how does the photon get created? See more exact phrasing of the question, below.
What is a photon is answered here: What exactly is a photon?
How a photon is made in general, is answered here: How are photons made?
For the latter question, the answers by ACuriousMind and John Rennie appear to be relevant. An exact answer to my question would be nice though, as it seems to be missing on Physics Stack Exchange.
My own reasoning, directly based on reading John Rennie's answer:
A photon has an associated quantum field. Energy gets added into this field (the photon field) when the electron moves to a lower orbit. The energy comes from the lost energy in the electron field -- the two fields transfer energy. The energy added equals that of a photon, hence a photon is created and emitted.
As John Rennie points out "If we transfer energy into the photon field then it appears as a photon".
However this seemingly provides no explanation at all as to how the photon is created, beyond introducing the notion of quantum fields. How is it that energy just "appears as a photon"? What is the best model to explain this?

A: A model which you may find helpful at the level of ordinary quantum mechanics (without field theory) is as follows:
Suppose the electron starts in a state $\psi_1(\vec r)$ with energy $E_1$, and finishes in a state $\psi_0(\vec r)$ with energy $E_0$, and $E_1 > E_0$ if we're talking about emission.
In between start and finish, during the emission process, it is a state $a(t)\psi_1 + b(t) \psi_0$, where $a^2+b^2=1$ and the exact form doesn't concern us. This is not an eigenstate of the time-independent Schroedinger equation and the full description needs to include the different time dependences of the 2 states
$\Psi(\vec r,t)=a(t) e^{-i E_1 t/ \hbar} \psi_1(\vec r)
+b(t)e^{-i E_0 t/\hbar} \psi_0(\vec r) $
Now consider the mean value of, say, the electron's $x$ co-ordinate (or any other if you prefer).  It is $\int \Psi^* x \Psi dV$ which is
$a^2 \int x |\psi_1|^2 dV
+ b^2 \int x |\psi_2|^2 dV
+ab^*e^{i(E_0-E_1)t/\hbar}\int x \psi_1 \psi_0^* dV
+a^*be^{-i(E_0-E_1)t/\hbar}\int x \psi_1^* \psi_0 dV
$
The first two terms are probably zero, by symmetry, unless the potential is asymmetric, and are anyway slowly-varying with time and can be ignored. The third and fourth terms combine to give a term proportional to $\cos((E_1-E_0)t/\hbar)$.
So the mean position of the electron during this intermediate period is oscillating with frequency $\omega = {E_1-E_0 \over \hbar}$. This electron has a charge, so it is behaving like an oscillating dipole. Switching hats from QM to E&M, we remember that oscillating dipoles produce electromagnetic radiation.
The frequency of that radiation is exactly right to balance energy conservation.
So your answer:  photon is created as a chunk of dipole radiation from the charged electron as its mean position oscillates in the intermediate state between the initial and final energy levels.
(There are other ways of thinking about photons, of course. But this is a very nice example of the correspondence principle.)

A: TL;DR: there is a coupling between the electron and the electromagnetic field, which allows the transfer of energy and momentum from one to the other.
Atom, field and interaction
The net Hamiltonian of the atom and the electromagnetic field can be written as
$$H=H_{atom}+H_{em} + H_{int},$$
where interaction term is actually the coupling of the electron to the part of the scalar and vector potentials, which are due to the EM field. One typically starts with solving separately the Hamiltonians for the atom and the EM field. The former gives us the energy levels (while the latter is usually already diagonal, as it describes free field, but there may be variations). The coupling is then included as a perturbation, and the first order contribution mixes the degenerate (and nearly degenerate) states of the atim and the field. E.g., the states with no photons and the atim excited has energy close to the state with the atom in its ground state and a photon present: $E_e=E_g+\hbar\omega_k$. Higher order processes (such as Raman scattering) appear in higher orders of perturbative expansion.
Jaynes-Cummings model
The simplest model of this type is Jaynes-Cummings model, with Hamiltonian:
$$H_{atom}=E_e|e\rangle\langle e| + E_g|g\rangle\langle g|,\\
H_{em}=\hbar\omega_0a^\dagger a,\\
H_{int}=dE (a^\dagger + a)(|e\rangle\langle g|+|g\rangle\langle e|)$$
The interaction term is actually the product of the dipole moment of the atom $d(|e\rangle\langle g|+|g\rangle\langle e|)$ and the electric field due to photons, $E (a^\dagger + a)$. (There are some caveats if one uses thsi model for describing photon emission, I put it for illustartive purposes.)
Not only photons
The approach is by no means unique to photons - many interactions are discussed in this perturbative way.


text:
Q: Update a cookie with a new one when visiting different pages I have a website that has multiple locations and each location has their own set of information. When a user visits the main corp page, the location information will not display. When the user then goes to a location page I have a cookie being set.
        $location_address = get_field('location_address','options');
        $location_city = get_field('location_city','options');
        $location_state = get_field('location_state','options');
        $location_zip_code = get_field('location_zip_code','options');
        $location_phone_number = get_field('location_phone_number','options');

        // cookie will expire when the browser close
        setcookie("locationAddress",$location_address);
        setcookie("locationCity",$location_city);
        setcookie("locationState",$location_state);
        setcookie("locationZipcode",$location_zip_code);
        setcookie("locationPhone",$location_phone_number);

The cookie is showing my location information in the firebug console. However, what is happening is when I go to another location, its grabbing both sets of cookies. I need it to replace the cookie previously set with the new one.
This is my code as well to output the cookie, which seems to be breaking as well:

<?php if(!isset($_COOKIE[$location_address])) { echo "" . $location_address . "";} ?>, <?php if(!isset($_COOKIE[$location_city])) { echo "" . $location_city . "";} ?> <?php if(!isset($_COOKIE[$location_state])) { echo "" . $location_state . "";} ?> <?php if(!isset($_COOKIE[$location_zip_code])) { echo "" . $location_zip_code . "";} ?> | <?php if(!isset($_COOKIE[$location_phone_number])) { echo "" . $location_phone_number . "";} ?>

A: You should set "path" argument in setcookie.
setcookie("locationAddress",$location_address, 0, "/");
setcookie("locationCity",$location_city, 0, "/");
setcookie("locationState",$location_state, 0, "/");
setcookie("locationZipcode",$location_zip_code, 0, "/");
setcookie("locationPhone",$location_phone_number, 0, "/");

A: If I were you I would probably try and set the path for the cookies.
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

also, I spotted a few commas in your code and I fixed the spaghetti code.
 <?php
    echo '

';

    if(!isset($_COOKIE[$location_address]))
       {
          echo $location_address;
       }
    if(!isset($_COOKIE[$location_city]))
       {
          echo $location_city;
       }
    if(!isset($_COOKIE[$location_state]))
       {
          echo $location_state;
       }
    if(!isset($_COOKIE[$location_zip_code]))
       {
          echo $location_zip_code;
       }

    echo '';

    if(!isset($_COOKIE[$location_phone_number]))
       {
          echo $location_phone_number;
       }
    echo '

';
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Two versions of the Inverse Function Theorem. I first learned about the Inverse Function Theorem for $C^1$ functions in Rudin's Principles of Mathematical Analysis in the following form.

Inverse Function Theorem ($C^1$ version): Suppose $E$ is open in $\mathbb{R}^n$ and $f:E\to\mathbb{R}^n$ is a $C^1$ mapping. If $f'(a)$ is invertible for some $a\in E$, and $b=f(a)$, then there exist neighborhoods $U$ of $a$ and $V$ of $b$ such that $f:U\to V$ is invertible and $f^{-1}:V\to U$ is also a $C^1$ mapping.

But I recently encountered the following version for $C^\infty$ functions.

Inverse Function Theorem ($C^\infty$ version): Suppose $E$ is open in $\mathbb{R}^n$ and $f:E\to\mathbb{R}^n$ is a $C^\infty$ mapping. If $f'(a)$ is invertible for some $a\in E$, and $b=f(a)$, then there exist neighborhoods $U$ of $a$ and $V$ of $b$ such that $f:U\to V$ is invertible and $f^{-1}:V\to U$ is also a $C^\infty$ mapping.

Now my question: Can we prove the second one from the first? Or do we have to redo the proof for the second one?

A: Yes, because the first gives a formula for the derivative.
Since $D(f^{-1})(f(x)) = (Df(x))^{-1}$, and the mapping $A \mapsto A^{-1}$ is
smooth, we see that the mapping $x \mapsto D(f^{-1})(f(x))$ is as smooth as
$Df$ (which is $C^\infty$).
Now consider the function $y \mapsto D(f^{-1})(y)$ around $y=f(x)$.
The function $f^{-1}$ is a $C^1$ mapping, hence the
mapping $y \mapsto D(f^{-1})(f(f^{-1}(y)))$ is a $C^1$ mapping.
This in turn implies that $f^{-1}$ is a $C^2$ mapping.
In general, we can use the formula to conclude that if $f^{-1}$ is a $C^k$
mapping then it is a $C^{k+1}$ mapping, from which it follows that $f^{-1}$
is $C^\infty$.


text:
Q: Swift 4.2 EventKit get all Events to the selected calendar on TableView didSelectedRowAt I'm loading all my calendars in a tableview where every calendar is represented in a cell.
Now I want to print all the events of the calendar of the cell when I tap the cell.
The Problem is, with the code you see I get the events of all calendars.
How can I tell the function only to look in the calendar I tapped in tableview?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let calendarTitle = calendars![indexPath.row].title
    print(calendarTitle)
    let calendar = Calendar.current
    print("Current \(calendar)")

    var oneDayAgoComponents = DateComponents()
    oneDayAgoComponents.day = -1
    let oneDayAgo = calendar.date(byAdding: oneDayAgoComponents, to: Date())

    var oneDayFromNowComponents = DateComponents()
    oneDayFromNowComponents.day = 7
    let oneDayFromNow = calendar.date(byAdding: oneDayFromNowComponents, to: Date())

    var predicate: NSPredicate? = nil
    if let anAgo = oneDayAgo, let aNow = oneDayFromNow {
        predicate = eventStore.predicateForEvents(withStart: anAgo, end: aNow, calendars: nil)

    }

    var events: [EKEvent]? = nil
    if let aPredicate = predicate {
        events = eventStore.events(matching: aPredicate)

        for event in events! {
            print(event.title)
        }
    }
}

A: You have to pass the calendar in the calendars parameter of predicateForEvents
let rowCalendar = calendars![indexPath.row]
let calendarTitle = rowCalendar.title
print(calendarTitle)

...

if let anAgo = oneDayAgo, let aNow = oneDayFromNow {
    predicate = eventStore.predicateForEvents(withStart: anAgo, end: aNow, calendars: [rowCalendar])
}

And please declare the data source array as non-optional empty array as you are force unwrapping it anyway
var calendars = [EKCalendar]()


text:
Q: Determination of the critical homogeneous nucleation radius Situation
Consider a supercooled liquid. If a spherical solid crystal appears, the variation of the free Gibbs energy is given by
$\Delta G = -\frac{4}{3}\pi\Delta g r^3 + 4\pi\gamma r^2$
where $\Delta g$ is considered the variation of the Gibbs energy per volume between the liquid and the solid phase, $\Delta g > 0$.
Plot of $\Delta G$:

Problem
My professor asked us to determine the critical radius at which the solid spheres become more favourable energetically and thus, the supercooled liquid begins crystallising. She meant us to find $r^*$.
I think we should rather be looking at $r_0$, since it is the variation of $G$ - only at that point does the $\Delta G$ becomes negative, which is necessary for a process to spontaneously happen.
Multiple sources treat $r^*$ as the minimum radius, but I fail to see how the maximum of $\Delta G$ would be more important that the point at which it becomes negative.
So, which one is the minimum radius the solid sphere has to grow to, in order for the liquid to solidify ?

A: Spontaneous changes in a system always reduce the Gibbs free energy.
If you are to the left of the maximum, i.e. $r \lt r^*$, then the Gibbs free energy is reduced by reducing the value of $r$. That is any particle of a size $r \lt r^*$ will spontaneously shrink.
Conversely, if you are to the right of the maximum, i.e. $r \gt r^*$, then the Gibbs free energy is reduced by increasing the value of $r$. That is any particle of a size $r \gt r^*$ will spontaneously grow.
And a particle with $r$ exactly equal to $r^*$ is stable, though it's an unstable equilbrium.
Response to comment:
It is important not to confuse kinetics with thermodynamics. Suppose we produce a particle with a radius slightly greater than $r^*$. The free energy change for this is positive so the particle won't appear spontaneously.
However in any random system we have continual statistical fluctuations happening, so although the average free energy is well defined on a small scale regions of the system can have a free energy momentarily larger than the average. The probability of this happening is given by the Boltzmann distribution:
$$ P(\Delta G) \propto e^{-\Delta G/kT} $$
So even though it is thermodynamically unfavourable to produce a particle of $r \gt r^*$ some of those particles will be produced as the result of statistical fluctuations. And as soon as those particles are produced they will start to grow and you'll end up with the production of large particles.
The system you describe is an example of a system that is overall thermodynamically unstable but has an activation energy i.e. a barrier that the system has to climb in order to change. In this case that barrier is the energy $\Delta G^*$. Any part of that system that can make it to just over the barrier, i.e. $r$ just greater than $r^*$ will get through the barrier and form a growing particle. That's why $r^*$ is the critical radius.


text:
Q: Fullcalendar Events Attach Each Other
[Is there a way to attach these two events  each other in same row? I tried with groupId, but it is not working.]

A: I ended up merging these two events and separated the colors by using linear-gradient.


text:
Q: eclipse jdt syntax highlighting of constants Anyone know of a simple way of adding syntax highlighting rules to the default syntax coloring in the eclipse java jdt? I would like to show constants of various kinds in a specific colour.
Such as: final members and enum value literals (not the enum type name).
Numbers and strings are already supported, as is static final member.

A: Preferences -> JAVA -> Editor -> Syntax Coloring
And in Element box select static final fields under java you can change your color by what you want for your constant


text:
Q: how we will cache webservice response in spring? In our project we planning to use Java spring framework web service client so just I want to know ,
What are best practices to implement the web service client in spring?
What are performance points need consider while building such client?
Can we cache web service response in spring ?

A: Considering you are aware of implications of caching results (aka having stale data)
your best alternative would be spring great cache abstraction, introduced on Spring 3.1
Spring Cache Abstraction
Have a look there, you can wrap your webservice client calls in a cache method and let spring deal with the caching part for you.
Nicest part is that you have the freedom to choose your cache provider.


text:
Q: Totally Bounded Metric Spaces And Sequences Prove that every sequence in a totally bounded metric space has a Cauchy's subsequence.
$$$$Let $(X, d)$ be a complete metric space and $a_n$ be a sequence then as $a_n$ is a subset of $X$ and as $X$ is totally bounded, so $a_n$ is also totally bounded. Hence chose $\epsilon=\frac{1}{2}$, then there exists a finite number of open balls say $$B_1, B_2, B_3, B_4, ....., B_k$$ of radius $\frac{1}{2}$ which cover $a_n$. Now atleast one of them say $B_{k_0}$ contains infinite number of terms of $a_n$. Now this subsequence of $a_n$ in $B_{k_0}$ is a subset of $a_n$ and hence it is also totally bounded. So for $\epsilon=\frac{1}{4}$ there exists a finite number of open balls say $$C_1, C_2, C_3, C_4, ......, C_m$$ of radius $\frac{1}{4}$ which cover this subsequence. Now against atleast one of these open balls say $C_{m_0}$ contains an infinite number of terms of this subsequence. Continuing in this way in every step chose $x_1$ from $B_{k_0}$, having least index, then chose $x_2$ from $C_{m_0}$ having least index, then we claim that this subsequence of $a_n$ is Cauchy's Subsequence. Now for any given $\epsilon$ chose $N$ such that $$\frac{1}{2^{N-1}} < \epsilon$$. Now as in the $n$th step the ball which contains infinite number of terms of the sequence has radius less than $\frac{1}{2^n}$ and hence $$d(x, y) < \frac{1}{2^{n-1}}$$ for every $x, y$ in that ball. So for every $m, n \geq N$ we have $$d(x_n, x_m) < \frac{1}{2^{N-1}} <\epsilon $$, and hence this sequence has a Cauchy's Subsequence.
$$$$Is My Proof Correct??


text:
Q: 7-dimensional vector Java I am very new to java and I have this assignment which I have been working on very intensivly for the last 14 days.
The assignement is to build a class vector with max. 7 dimensions:
what I came with to make the vector multi-dimensional is that I declared 7 variables
private double x, y,z,i,j,k,f;

which then I will initialize in constructors etc..
Well, my first question: did I build a 7 dimensional vector in this way?
OR,
should I somehow work with arrays for this problem
like declaring an array;
double [][] = data; // which generates a 2D-Vector.

AND,
double [][][][][][][] = data1; //which declare a 7D-Vector??!!!

for any helpful information I will be very thankful
thanks all and
Best regards to you  :)

A:
did I build a 7 dimensional vector in this way?

Yes you have.  A vector is a way of storing a magnitude and direction, which is done by correctly assigning the value and sign of each double.  A vector in 2-space would require two values, and a vector in 7-space would require 7 values, which you have.

should I somehow work with arrays for this problem like declaring an array;

You can, but you don't need a multi-dimensional array.  To store a single vector in a 7-space, you just need an array of length 7:
double[] data = new double[7]; // store a 7D vector

You could then modify your existing code, replacing x with data[0], y with data[1] and so on.

A: You don't need a multidimensional array for a vector. By definition, a vector has only a single column; if it had multiple columns, it would be a matrix, not a vector.
If you want a vector of size n, just create a single-dimensional array of size n. You could use an ArrayList or something like that, but there's less of a point because you (presumably) know the size of the vector in advance. (If that's not the case, ArrayList could be good).
The most interesting part of a Vector class is actually the operations, so use whatever data structure allows you to retain order and conveniently perform your operations. Truthfully, that'll probably be an array of size n.


text:
Q: TNSNAMES.ORA file is missing even after installing ODP.NET from oracle website I am trying to create a new connection for an Entity Data Model, from Visual Studio 2019 Community Edition. I keep getting error

ora-12154: tns:could not resolve the connect identifier specified.

Though I have installed ODP.NET by running ODTforVS2019_193100.vsix but I still  don't see TNSNAMES.ORA created in my C:\Users\harafat\Oracle\network\admin folder


text:
Q: How to create a path when copying in a dockerfile? I'm try to copy some file in my php/dockerfile:
COPY ./supervisord.conf /etc/supervisor                 #work
COPY ../../config/supervisor/* /etc/supervisor/conf.d   #doesn't work

WORKDIR /home/wwwroot/

What should the correct path look like? This is my structure:
|config -> supervisor -> *
|
|docker -> php -> Dockerfile
|              -> supervisord.conf
|

A:
The  path must be inside the context of the build; you cannot
  COPY ../something /something, because the first step of a docker build
  is to send the context directory (and subdirectories) to the docker
  daemon.

https://docs.docker.com/engine/reference/builder/
dockerfile has the context of its own directory, and its unable to go above.
this issue has a few workarounds, for instance:

*

*run the docker build . command on the directory you want to be the context, with -f path/to/Dockerfile

*another one - if you are using docker-compose, you can pass it a different context, for example, if youre structure goes like:

.
├── docker-compose.yml
└── app
   ├── Dockerfile

then in your docker-compose file you can give it:
services:
  app:
    build:
      context: .
      dockerfile: app/Dockerfile

in this case, the context of the dockerfile will be 1 directory above. but thats seems a bit hacky to me.  the correct approach is to put the dockerfile where the files you are trying to copy exists.


text:
Q: How to safely switch from 64bit to 32bit Python on Windows? I have installed 64-bit Python on Windows 7 and used it for a while. Now I need to switch to 32-bit Python because some libraries require 32-bit one. Can I do this easily, while preserving all previously installed libraries and settings?

A: You can use virtualenv to maintain environments that use distinct Python versions.
More directly to your question of keeping the same install-base, the answer is generally "no", you cannot keep the same installs. Some packages are obtained for a specific Python-version/OS/hardware combination (e.g. mypackagePy27Win64.exe) and such packages will have placed 64-bit-specific DLLs on your filesystem. Using virtualenv will let you isolate your new x32 work environment from your existing x64 work environment.


text:
Q: Can you explain this expression in the book (a text-book of convergence "w.L FERRAR" )
The writer present this ideas
( if y is a fixed number graeter than unity, and k is any fixed positive integer, then the sequence $\frac{n^k}{y^n} $ converges to zero
Before we give the proof of this theorem, we try to explain some of the ideas that lead to the proof
i)...... if  l is a fixed number and n is to be thought of as a very large number, then n-l is about as big as n, further, extending this ideas a little, if k is a fixed number and n is to be thought of as a very large number, then
$n(n-1)(n-2).....(n-k)$
is about as big as $n^{k+1}$
(ii) the y of our Problem exceeds unity and we can write
$y^n=(1+p)^n$ p>0
The right-hand side can be expended, when n is a positive integer, by the binomial theorem, and, since each term of the expansion is positive, so if we take $(n>k+1)$
$y^n=(1+p)^n>\frac{n(n-1)....(n-k)}{(k+1)!}p^{k+1}$)
I can't understand  the last expression، so can you explain it?
And also I need more clarification for the partie (i)

A: The last expression comes from the binomial expansion of $(1+p)^n$.
Remember that $$(1+p)^n=\sum^{n}_0\binom{n}i p^i$$
Now since each term on the RHS is positive, the sum is definitely greater than an individual term.
$$\sum^{n}_0\binom{n}i p^i\ge\binom{n}{k+1} p^{k+1}$$ which is what expands into the last expression.
As for the explanation of part (i) it can be understood as
$$\frac{\sum_{r=0}^{k} (n-r)}{n^{k+1}}=\sum_{r=0}^{k} (1-r/n)\rightarrow 1\ as\ n\rightarrow\infty$$. which justifies the approximation.

A: FYI - when people ask for clarification, just edit the post.  No need to keep deleting and redoing it.
To answer your question, if we have $y^n = (1+p)^n$ we can use the binomial theorem, which says that
$$(1+x)^{n} = \sum_{k=0}^{n}\binom{n}{k}x^{k}.$$  In this case, we have
$$y^n = (1+p)^n = \sum_{k=0}^{n}\binom{n}{k}p^{k}.$$  Now, so long as $n > k+1$, and since every term in the sum is positive, we can take just the term with the $k+1$ power and it will be less than the entire sum.  So, we get
\begin{align*}
y^n &= (1+p)^n\\[5pt]
&= \sum_{k=0}^{n}\binom{n}{k}p^{k}\\[5pt]
&=\binom{n}{1}p + \binom{n}{2} + \dotsb + \binom{n}{k+1}p^{k+1} + \dotsb + \binom{n}{n}p^{n}\\[5pt]
&> \binom{n}{k+1}p^{k+1}\\[5pt]
&= \frac{n!}{(k+1)!(n-k-1)!}p^{k+1}\\[5pt]
&= \frac{n(n-1)\dotsb(n-k)}{(k+1)!}p^{k+1}.
\end{align*}
As for part (i), if we think of $n$ as being very large, then $n-1 \approx n$, which means that $n(n-1) \approx n^2$.  Extending this idea, if $k$ is some fixed number, and $n$ is much larger than $k$, then the numbers $$n, n-1, n-2, \dotsc, n-k$$ are all approximately equal to $n$.  So, this gives us $$n(n-1)(n-2)\dotsb(n-k) \approx n^{k+1},$$ because there are $k+1$ terms in the product.


text:
Q: Two variable function on a circle. I've been preparing for my exams and encountered this exercise that I can't figure out:
Let f be a two variable, continuous function on a circle $K$ with the center $({x}_0, {y}_0)$.
$\iint_R f dR$ is equal to 0 for any rectangle $ R \subset K$ that contains point  $({x}_0, {y}_0)$. Prove that  $f({x}_0, {y}_0)=0$.
My intuition: For any arbitrary rectangle, which contains  $({x}_0, {y}_0)$  we can find smaller one, that will also include this specific point. If we take infinitely small rectangle and compute the limit of function's value with respect to rectangle's diagonal we will probably get that $f({x}_0, {y}_0)=0$. This is only my intuition, but now, how do I write a sufficient proof?


text:
Q: I am trying to get values from an JSON file by matching key names, but it does not work with nested keys I am trying to key values from an JSON file by matching key names, but it does not work with nested keys, maybe not the best way to load date this way(if there are better ways to do this let me know).
// .JSON file

{
    "routes":{
        "path":{
            "register":{
                "index": "register"
            },
            "login":{
                "index": "login"
            }
            ...
        }
    }
}

// solution(not working)

const paths = require(`../locales/en-US.json`)
const getByValueByKey = (getPath, value) => {
    for (let key of Object.keys(getPath)) {
        if (getPath[key] === value) {
            return key;
        }
    }
}

getByValueByKey(paths, 'routes.path.login.index')//should return login

A: You can use lodash's get method - https://lodash.com/docs/4.17.15#get.
This is the source code for that method if you want a native implementation:
 /**
     * The base implementation of `_.get` without support for default values.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the property to get.
     * @returns {*} Returns the resolved value.
     */
    function baseGet(object, path) {
      path = castPath(path, object);

      var index = 0,
          length = path.length;

      while (object != null && index < length) {
        object = object[toKey(path[index++])];
      }
      return (index && index == length) ? object : undefined;
    }

    function get(object, path, defaultValue) {
      var result = object == null ? undefined : baseGet(object, path);
      return result === undefined ? defaultValue : result;
    }

A: You can use reduce and get the value.
const result = value.split(".").reduce((acc, curr) => acc && acc[curr], getPath);

const paths = {
  routes: {
    path: {
      register: {
        index: "register",
      },
      login: {
        index: "login",
      },
    },
  },
};

const getByValueByKey = (getPath, value) => {
const result = value.split(".").reduce((acc, curr) => acc && acc[curr], getPath);
  console.log(result);
};

getByValueByKey(paths, "routes.path.login.index"); //should return login


text:
Q: Menu item seperators not visible under GNOME environment (while using "GTK" LAF) I have a Java desktop application (document editor) for where I recently added a menubar, with menus which in turn have menu items. The problem is that - in my GNOME desktop environment (Ubuntu) the menu item separators are not visible at all. They are visible if I switch the application L&F to default Java (metal) LaF or to switch the desktop environment KDE environment on Ubuntu, but the menu item separators are never visible under GNOME environment. Also I am setting the application L&F to "GTK". If I force the L&F to "motif" the file separators can be clearly seen.
Has anyone else ever faced this kind of a problem before on Ubuntu GNOME environment? I am attaching the code below - which is straight forward and don't think there is any problem here.
import java.awt.EventQueue;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {
    static JFrame frame = null;
    static JMenuBar menubar = null;
    static JMenu filemenu = null;
    public static void main (String[] args) throws InterruptedException,
        InvocationTargetException {
        EventQueue.invokeAndWait(new Runnable () {
            @Override
            public void run() {
                createAndShowGUI ();
            }
        });
    }

    private static void createAndShowGUI () {
        /* Set LAF to GTK LAF */
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }

        /* Create frame */
        frame = new JFrame ();
        frame.setLocation(50, 50);
        frame.setSize(400, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        /* Add menu bar */
        addMenuBar ();
    }

    private static void addMenuBar () {
        /* Create menu bar and then file menu*/
        menubar = new JMenuBar ();
        filemenu = new JMenu ("File");

        /* Add three menu items to the file menu */
        JMenuItem newItem = new JMenuItem ("New       ");
        JMenuItem openItem = new JMenuItem ("Open      ");
        JMenuItem exitItem = new JMenuItem ("Exit     ");

        /* Add the menu items to the file menu. Also separate the last item
         * from the first two using a menu item separator */
        filemenu.add(newItem);
        filemenu.add(openItem);

        filemenu.addSeparator();
        filemenu.add(exitItem);

        /* Add the file menu to the menu bar */
        menubar.add(filemenu);

        /* Add menu bar to frame */
        frame.setJMenuBar(menubar);
    }
}

So the question is - do I need to add some more customization when using "GTK" L&F in GNOME environment so that the menu item separators are visible again?
[Edit: the post has now been edited to reflect an sscce. If you want to see the effect of Java LAF then please comment out the lines inside the createAndShowGUI () where the LAF is hardcoded to GTK LAF. The problem goes away with Java LAF but remains when using GTK LAF]


text:
Q: kivy Carousel slides index set how can I set indexes for slides in the carousel? I have a list which I receive from a DB.
[4, 30, 1, 2]

I read a bunch of information but did not understand how this is possible. By standard, the index numbers in the carousel start from 0 and I can get each of these indexes:
on_current_slide: root.current_slide(self._index) # 0, 1, 2, 3

but here's the problem, they do not match the indexes of the records from the database.
class NewsScreen(ScreenManager):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        sql_query = "SELECT id, title, image, date FROM news WHERE id > 0 ORDER BY date"
        id_list = [] # list for id's

        rows = con.execute(sql_query,)
        db.commit()

        for  row in rows:
            slide = NewsCards()
            id_list.append(int(row[0]))
            slide.title_text=str(row[1])
            slide.title_date=str(row[3])
            slide.img_path=str(row[2])

            self.ids.carousel.add_widget(slide)

        print(id_list) # [4, 30, 1, 2]

    # Getting slide index
    def current_slide(self, _index):
        cur_index = _index
        print("Current slide id :", cur_index)

I want to set the indexes in the carousel slides to match the indexes from the database. Can anyone help?


text:
Q: Error compiling kernel 5.15.2 I'm trying to compile kernel 5.15.2 and running into errors. How to I fix them?
Background
I'm using a new laptop (Asus ROG M16) and for some reasons my wifi and bluetooth don't work on either kernel 5.13 or 5.14. As I update to kernel 5.15, bluetooth and wifi work but then the suspend feature becomes broken (the laptop does not suspend, but instead logs out and gets blank screen, fans run on full speed, and I have to do a hard reset). I'm trying to update to kernel 5.15.2 to see whether the issue is fixed.
Error
At main.c:160:
- SSL error:02001002:system library:fopen:No such file or directory: ../crypto/bio/bss_file.c:69
- SSL error:2006D080:BIO routines:BIO_new_file:no such file: ../crypto/bio/bss_file.c:76
sign-file: : No such file or directory
make[1]: *** [scripts/Makefile.modinst:83: /lib/modules/5.15.2/kernel/arch/x86/crypto/aegis128-aesni.ko] Error 1
make[1]: *** Deleting file '/lib/modules/5.15.2/kernel/arch/x86/crypto/aegis128-aesni.ko'
make: *** [Makefile:1794: modules_install] Error 2

Step to reproduce

*

*Download the kernel from the kernel archives

*Extract the kernel

*Run the following commands on terminal
$ make menuconfig
$ sed -ri '/CONFIG_SYSTEM_TRUSTED_KEYS/s/=.+/=""/g' .config
$ sed -ri '/CONFIG_MODULE_SIG_KEY/s/=.+/=""/g' .config
$ sed -ri '/CONFIG_SYSTEM_REVOCATION_KEYS/s/=.+/=""/g' .config
$ make
$ make modules
$ sudo make modules_install

Other info

*

*Ubuntu 21.10

*Current kernel 5.15.1-051501-generic


text:
Q: Java Scanner, taking user input from console into array list as separate words I am trying to read the user input from the console directly into an array list, separated by each word or entity that has whitespace on either side (the default behavior). The problem is I am stuck inside of a while loop. Scanner.next() keeps waiting for more input, though I know I want to stop feeding input after the user presses return:
Scanner input = new Scanner(System.in);

    System.out.print("Enter a sentence: ");
    do {
        if (words.add(input.next());

    } while (input.hasNext());

    System.out.println(words);

I input a line, except I will have to press CTRL-D to terminate it (IE. signal the end of input). I just want to automatically end it when the return '\n' character is pressed at the end of the sentence.

A: It may be simpler to use split for what you want.
// read a line, split into words and add them to a collection.
words.addAll(Arrays.asList(input.nextLine().split("\\s+")));

A: You could always use the Console class, like this:
Console console = System.console();

System.out.print("Enter a sentence: ");

List<String> words = Arrays.asList(console.readLine().split("\\s+"));

System.out.println(words);

The readline() method should take care of the \n issue.
If you require a Scanner for the type reading capabilities, you can mix both classes:
Scanner scanner = new Scanner(console.reader());

Hope this helps!

A: You could call input.hasNextLine and input.nextLine to get a line, and then create a new Scanner for the line you got and use the code that you have now.  Not the cheapest solution, but an easy way to implement it until you come up with a better one :-)


text:
Q: what happens to symbolic or soft links when you store the filename within the inode? I understand that the whole reason that you do not store the file name within the inode is so that you can use a hard link to point to the inode's number. But in terms of symbolic links, they use the file name in order to access the file rather than the i-number. So would they be accessible to point to a file name that is written within the i-node already?

A: Hard links only work within the same disk.
In order to work across disks, soft links point to a file name that in turn [may] point to an inode.

A: symlinks don't point to files, they are just a bunch of bytes which can replace symlink's own name during lookup.
That is, if 'foo' is a symlink to 'bar', looking up 'foo/crap' will end up looking up 'bar/crap'.
It is trivial to construct examples where following a symlink makes you end up with different files. For instance one can chroot(1) somewhere and then follow a symlink which is either absolute or has several '..'s. Let's say the symlink is named 'crap', contains "/meh" and placed is /mycontainer. Then processes which chroot to /mycontainer and follow 'crap', will end up on /mycontainer/crap from "outside" perspective. Meanwhile processes which did not chroot will end up on /crap.


text:
Q: To calculate intersections between a ray and a mesh Problem description
I want to calculate all intersections between a ray and a surface mesh which was built from points cloud using the function CGAL::advancing_front_surface_reconstruction(). The cost of time matters very much for me. So I want to use the package named Fast Intersection and Distance Computation. But when I built AABBtree from a surface mesh by the function tree(), a bug occurs. The IDE's bugs list shows: '<function-style-cast>' can not transform to CGAL::AABB_face_graph_triangle_primitive<meshCGAL, CGAL::Default, CGAL::Tag_true, CGAL::tag_false> from "initializer list".
I use the kernel named CGAL::Exact_predicates_inexact_constructions_kernel when I reconstruct mesh from points cloud with CGAL::advancing_front_surface_reconstruction(), but a Simple_cartesian<double> kernel is required in the Fast Intersection and Distance Computation. Is that the main reason? How can I use the two program package together?
Code
The code is as follows:
#include<iostream>
#include<vector>
#include<string>
#include<array>
#include<fstream>
#include<algorithm>

#include <CGAL/Simple_cartesian.h>
#include<CGAL/AABB_tree.h>
#include<CGAL/AABB_traits.h>
#include<CGAL/AABB_segment_primitive.h>
#include<CGAL/Surface_mesh.h>
#include <CGAL/AABB_face_graph_triangle_primitive.h>

#include<CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include<CGAL/Advancing_front_surface_reconstruction.h>
#include<CGAL/Surface_mesh.h>
#include <CGAL/boost/graph/IO/polygon_mesh_io.h>
#include<CGAL/Polygon_mesh_processing/corefinement.h>
#include<CGAL/polygon_mesh_processing/remesh.h>

using std::cout;
using std::cin;
using std::endl;
using std::string;

namespace PMP = CGAL::Polygon_mesh_processing;

typedef std::array<std::size_t, 3> Facet;
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::Point_3 Point_3;
typedef CGAL::Surface_mesh <Point_3> Mesh;

typedef CGAL::Simple_cartesian<double> K;
typedef K::FT FT;
typedef K::Point_3 pointCGAL;
typedef K::Vector_3 vectorCGAL;
typedef K::Ray_3 rayCGAL;
typedef CGAL::Surface_mesh<pointCGAL> meshCGAL;
typedef boost::graph_traits<meshCGAL>::face_descriptor face_descriptor;
typedef boost::graph_traits<meshCGAL>::halfedge_descriptor halfedge_descriptor;

typedef CGAL::AABB_face_graph_triangle_primitive<meshCGAL> Primitive;
typedef CGAL::AABB_traits<K, Primitive> Traits;
typedef CGAL::AABB_tree<Traits> Tree;
typedef boost::optional<Tree::Intersection_and_primitive_id<rayCGAL>::Type> Ray_intersection;

struct Construct {
    Mesh& mesh;
    template <typename PointIterator>
    Construct(Mesh& mesh, PointIterator b, PointIterator e) :mesh(mesh) {
        for (; b != e; ++b) {
            boost::graph_traits<Mesh>::vertex_descriptor v;
            v = add_vertex(mesh);
            mesh.point(v) = *b;
        }
    }

    Construct& operator=(const Facet f) {
        typedef boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor;
        typedef boost::graph_traits<Mesh>::vertices_size_type size_type;
        mesh.add_face(vertex_descriptor(static_cast<size_type>(f[0])),
            vertex_descriptor(static_cast<size_type>(f[1])),
            vertex_descriptor(static_cast<size_type>(f[2])));
        return *this;
    }

    Construct& operator*() { return *this; }
    Construct& operator++() { return *this; }
    Construct& operator++(int) { return *this; }
};

int main() {

    //load sv
    Mesh sv;
    std::cout << "load sv49..." << std::endl;
    std::ifstream fin("./svPoints/sv49.txt");
    std::vector<Point_3> points;
    std::vector<Facet> facets;
    std::copy(std::istream_iterator<Point_3>(fin),
        std::istream_iterator<Point_3>(),
        std::back_inserter(points));
    fin.close();

    //convert sv to Surface_mesh, repair
    Construct construct(sv, points.begin(), points.end());
    CGAL::advancing_front_surface_reconstruction(points.begin(), points.end(), construct);//convert sv to surface_mesh
    CGAL::Polygon_mesh_processing::remove_isolated_vertices(sv);//filter out isolated vertices
    if (!CGAL::Polygon_mesh_processing::is_outward_oriented(sv))
        CGAL::Polygon_mesh_processing::reverse_face_orientations(sv);//make sure that the meshes are outer oriented
    CGAL::IO::write_polygon_mesh("sv49.off",sv);

    //build AABBtree of sv
    Tree tree(faces(sv).first, faces(sv).second, sv);
    vectorCGAL orientation(0, 0, 1);
    pointCGAL start = pointCGAL(0, 0, 0);
    rayCGAL ray_query(start, orientation);
    std::vector<Ray_intersection> intersections;
    tree.all_intersections(ray_query, std::back_inserter(intersections));
    if (!intersections.empty()) {
        for (auto intersect : intersections) {
            auto a = intersect->first;
            if (pointCGAL* p = boost::get<pointCGAL>(&a)) {
                cout << *p << endl;
            }
        }
    }
    return 0;
}

Runtime environment
IDE: Visual Studio 2017
CGAL version: 5.3
Solution Configuration: Debug x64
File
File sv49.txt used in the program can download from GitHub, here's link.

Additional problem
When I use kernel CGAL::Exact_predicates_inexact_constructions_kernel instead of kernel Simple_cartesian, the program is compiled without errors. But when I test all intersections between a ray starting at point(-100.0,-50.0,-100.0) in the direction of vector(0.0, 0.0, 1.0) and the mesh named sv in the program, I got 46 intersections. The result is ridiculous. Then I try the kernel CGAL::Exact_predicates_exact_constructions_kernel, the result is also inexact. The result shows all intersections are as follows:
-100 -50 -10
-100 -50 -10
-100 -50 -10
-100 -50 -9
-100 -50 -8
-100 -50 -8
-100 -50 -9
-100 -50 -3
-100 -50 -1
-100 -50 -7
-100 -50 -7
-100 -50 -6
-100 -50 -5
-100 -50 -6
-100 -50 -5
-100 -50 -4
-100 -50 -4
-100 -50 -3
-100 -50 -2
-100 -50 -2
-100 -50 0
-100 -50 -0
-100 -50 -1
-100 -50 -0
-100 -50 -0

True intersections should be (-100, -50, -0) and (-100, -50, -10). The repeated intersections are reasonable, but the others are impossible intersections.

A: After I paint the point (-100,-50,-0) in the mesh sv, I got the reason why the result which seems to be ridiculous come up. Technically, it's not a wrong answer mathematically, it's just not what I was expecting. The ray starting at this point and in the direction of (0, 0, 1) is a ray intersect with many facets on the side of the grid. The CGAL library does a good job of calculating intersections in this case, but I need to filter out the intersections.


text:
Q: hibernate relations in mysql I am trying to map the pojo class to my mysql database, but i always get an error when i want to get users:
java.sql.SQLSyntaxErrorException: Unknown column 'user0_.Report_id' in 'field list'

This is how the database looks like this:
database
And these are the pojo classes:
Order
package com.latinon.reportator.model;

import java.math.BigInteger;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * @author sistemas
 *
 */
@Entity
@Table(name="Order")
public class Order {

private Integer id;
private Date startDate;
private Date endDate;
private BigInteger imperssions;
private String zone;
private int monetization;
private String adUnit;
private String unit;
private String adFormat;
private Double totalAmount;
private Integer platform;
private Double value;
private String valueMesure;
private Set<Device> orderDevices = new HashSet<Device>(0);
private Set<Product> orderProducts = new HashSet<Product>(0);
private Set<Report> orderReport = new HashSet<Report>(0);
private Set<User> orderUsers = new HashSet<User>(0);

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="Order_id")
public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

@Temporal(TemporalType.DATE)
@Column(name="Order_start_date", nullable=false)
public Date getStartDate() {
    return startDate;
}

public void setStartDate(Date startDate) {
    this.startDate = startDate;
}

@Temporal(TemporalType.DATE)
@Column(name="Order_end_date")
public Date getEndDate() {
    return endDate;
}

public void setEndDate(Date endDate) {
    this.endDate = endDate;
}

@Column(name="Order_impressions", nullable=false)
public BigInteger getImperssions() {
    return imperssions;
}

public void setImperssions(BigInteger imperssions) {
    this.imperssions = imperssions;
}

@Column(name="Order_zone")
public String getZone() {
    return zone;
}

public void setZone(String zone) {
    this.zone = zone;
}

@Column(name="Order_monetization",nullable=false)
public int getMonetization() {
    return monetization;
}

public void setMonetization(int monetization) {
    this.monetization = monetization;
}

@Column(name="Order_ad_unit")
public String getAdUnit() {
    return adUnit;
}

public void setAdUnit(String adUnit) {
    this.adUnit = adUnit;
}

@Column(name="Order_unit",nullable=false)
public String getUnit() {
    return unit;
}

public void setUnit(String unit) {
    this.unit = unit;
}

@Column(name="Order_ad_format", nullable=false)
public String getAdFormat() {
    return adFormat;
}

public void setAdFormat(String adFormat) {
    this.adFormat = adFormat;
}

@Column(name="Order_total_amount", nullable=false)
public Double getTotalAmount() {
    return totalAmount;
}

public void setTotalAmount(Double totalAmount) {
    this.totalAmount = totalAmount;
}

@Column(name="Order_platform", nullable=false)
public Integer getPlatform() {
    return platform;
}

public void setPlatform(Integer platform) {
    this.platform = platform;
}

@Column(name="Order_value", nullable=false)
public Double getValue() {
    return value;
}

public void setValue(Double value) {
    this.value = value;
}

@Column(name="Order_value_mesure",nullable=false)
public String getValueMesure() {
    return valueMesure;
}

public void setValueMesure(String valueMesure) {
    this.valueMesure = valueMesure;
}

@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="Order_Device", joinColumns={
        @JoinColumn(name="Order_Device_Order_id")
})
public Set<Device> getOrderDevices() {
    return orderDevices;
}

public void setOrderDevices(Set<Device> orderDevices) {
    this.orderDevices = orderDevices;
}

@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="Order_Product", joinColumns={
        @JoinColumn(name="Order_Product_Order_id")
})
public Set<Product> getOrderProducts() {
    return orderProducts;
}

public void setOrderProducts(Set<Product> orderProducts) {
    this.orderProducts = orderProducts;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "orderId")
public Set<Report> getOrderReport() {
return orderReport;
}

public void setOrderReport(Set<Report> orderReport) {
    this.orderReport = orderReport;
}

@ManyToMany(fetch=FetchType.LAZY, mappedBy="userOrders")
public Set<User> getOrderUsers() {
    return orderUsers;
}

public void setOrderUsers(Set<User> orderUsers) {
    this.orderUsers = orderUsers;
}

@Override
public String toString() {
    return "Order [id=" + id + ", startDate=" + startDate + ", endDate=" + endDate + ", imperssions=" + imperssions
            + ", zone=" + zone + ", monetization=" + monetization + ", adUnit=" + adUnit + ", unit=" + unit
            + ", adFormat=" + adFormat + ", totalAmount=" + totalAmount + ", platform=" + platform + ", value="
            + value + ", valueMesure=" + valueMesure + "]";
}
}

Report pojo:
    package com.latinon.reportator.model;

import java.math.BigInteger;
import java.util.Date;

import javax.persistence.*;

/**
* @author sistemas
*
*/
@Entity
@Table(name="User")
public class Report {

private Integer id;
private BigInteger impressions;
private Date date;
private Double grossRevenue;
private Double latinonRevenue;
private Double userRevenue;
private Double fillRate;
private BigInteger completion25;
private BigInteger completion50;
private BigInteger completion75;
private BigInteger completion100;
private BigInteger requests;
private String zone;
private Double cpm;
private Order orderId;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="Report_id")
public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

@Column(name="Report_impressions")
public BigInteger getImpressions() {
    return impressions;
}

public void setImpressions(BigInteger impressions) {
    this.impressions = impressions;
}

@Temporal(TemporalType.DATE)
@Column(name="Report_date")
public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

@Column(name="Report_gross_revenue")
public Double getGrossRevenue() {
    return grossRevenue;
}

public void setGrossRevenue(Double grossRevenue) {
    this.grossRevenue = grossRevenue;
}

@Column(name="Report_latinon_revenue")
public Double getLatinonRevenue() {
    return latinonRevenue;
}

public void setLatinonRevenue(Double latinonRevenue) {
    this.latinonRevenue = latinonRevenue;
}

@Column(name="Report_user_revenue")
public Double getUserRevenue() {
    return userRevenue;
}

public void setUserRevenue(Double userRevenue) {
    this.userRevenue = userRevenue;
}

@Column(name="Report_fill_rate")
public Double getFillRate() {
    return fillRate;
}

public void setFillRate(Double fillRate) {
    this.fillRate = fillRate;
}

@Column(name="Report_completion_25")
public BigInteger getCompletion25() {
    return completion25;
}

public void setCompletion25(BigInteger completion25) {
    this.completion25 = completion25;
}

@Column(name="Report_completion_50")
public BigInteger getCompletion50() {
    return completion50;
}

public void setCompletion50(BigInteger completion50) {
    this.completion50 = completion50;
}

@Column(name="Report_completion_75")
public BigInteger getCompletion75() {
    return completion75;
}

public void setCompletion75(BigInteger completion75) {
    this.completion75 = completion75;
}

@Column(name="Report_completion_100")
public BigInteger getCompletion100() {
    return completion100;
}

public void setCompletion100(BigInteger completion100) {
    this.completion100 = completion100;
}

@Column(name="Report_request")
public BigInteger getRequests() {
    return requests;
}

public void setRequests(BigInteger requests) {
    this.requests = requests;
}

@Column(name="Report_zone")
public String getZone() {
    return zone;
}

public void setZone(String zone) {
    this.zone = zone;
}

@Column(name="Report_cpm")
public Double getCpm() {
    return cpm;
}

public void setCpm(Double cpm) {
    this.cpm = cpm;
}

@ManyToOne
@JoinColumn(name="Order_Order_id")
public Order getOrderId() {
    return orderId;
}

public void setOrderId(Order orderId) {
    this.orderId = orderId;
}

@Override
public String toString() {
    return "Report [id=" + id + ", impressions=" + impressions + ", date=" + date + ", grossRevenue=" + grossRevenue
            + ", latinonRevenue=" + latinonRevenue + ", userRevenue=" + userRevenue + ", fillRate=" + fillRate
            + ", completion25=" + completion25 + ", completion50=" + completion50 + ", completion75=" + completion75
            + ", completion100=" + completion100 + ", requests=" + requests + ", zone=" + zone + ", cpm=" + cpm
            + ", orderId=" + orderId + "]";
}

}

User pojo:
package com.latinon.reportator.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="User")
@Inheritance(strategy=InheritanceType.JOINED)
public class User {

private int id;
private String login;
private String password;
private String email;
private Set<Domain> userDomains = new HashSet<Domain>(0);
private Set<Order> userOrders = new HashSet<Order>(0);

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="User_id",nullable=false)
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Column(name="User_login", length=45)
public String getLogin() {
    return login;
}

public void setLogin(String login) {
    this.login = login;
}

@Column(name="User_password", length=45)
public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

@Column(name="User_mail", length=45)
public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

@ManyToMany(fetch=FetchType.LAZY)
public Set<Domain> getUserDomains() {
    return userDomains;
}

public void setUserDomains(Set<Domain> userDomains) {
    this.userDomains = userDomains;
}

@ManyToMany(fetch=FetchType.LAZY)
public Set<Order> getUserOrders() {
    return userOrders;
}

public void setUserOrders(Set<Order> userOrders) {
    this.userOrders = userOrders;
}

@Override
public String toString() {
    return "User [id=" + id + ", login=" + login + ", password=" + password + ", email=" + email + "]";
}

}

A: You have in you Report class @Table(name="User"). is this a typo?


text:
Q: How to solve Call to a member function notify() on array? (laravel 5.3) My listener is like this :
<?php

namespace App\Listeners;

use App\Events\CheckoutOrderEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Mail;

class CheckoutOrderListener
{
    public function __construct()
    {
        //
    }
    public function handle(CheckoutOrderEvent $event)
    {
        // dd($event);
        $event->data->notify(New \App\Notifications\CheckoutOrder($event->data));
    }
}

If I run dd($event), the result is like this :

When executed, there exist error : Call to a member function notify() on array
How to solve it?

A: You need to use notify() on a model with Illuminate\Notifications\Notifiable trait, but definitely not on an array.
For example, you can get an instance of a User first:
$user = User::where('email', $event->data['email'])->first();

And then use notify():
$user->notify(....)

A: Alright, I was trying to send email to end-user of the application for activating their account (Provided in registration form ) then i got this Error because i was passing "ID" to notify(), actually it should pass whole details of users.

Solved By changing in Http/Controller/Admin/Auth/RegistrationController.php

And that's my Notification Class: app/Notification/UserActivate.php Look at my
__construct() and toMail($notifiable) methods

I hope my mistake helped you. :)


text:
Q: .bat file executing itself over and over I wrote
ping google.fr -n 2500
in a .txt file, saved as "ping.bat".
When I execute this script, I can see that the command execut itselfs over and over, as if it was into a loop. Ofc I didn't wrote any loop in the txt file.
Does anyone got a solution?
(check picture for more details)
Normal expected behave of the command :http://prntscr.com/cl2z44
Actual behave : Image of the problem

A: Preferably, save the script using another name. Otherwise, ping google.fr -n 2500 would execute itself (ping.bat) in current directory rather than searching ping.exe in PATH variable. For proof, try where ping.
Another approach (nonpreferable): keep ping.bat name but specify ping.EXE google.fr -n 2500 inside your bat script.


text:
Q: Does a CLR Class Library have to be run in Win32? I created a CLR project in VS2017.
Included:

*

*CLR Class Library(C++) .NET Framework 4.5

*C# ConsoleApp

There is a simple ref class defined in the Library.
The class is called from my C# code.
I am fine with its performance but it does not work always.
It depends on how I run it.

*

*"Debug" and "x86" works

*"Debug" and "x64" does not work

*"Release" and "x86" works

*"Release" and "x64" does not work

So in Debug and Release it only works when the CLR Class Library is run in Win32.
Do I make a mistake or is this intended behaviour?
Thanks in advance!

A: Usually the purpose of using C++/CLI language (I assume that's what you mean by "CLR Library") is to use both native and .Net objects. Because of native code, the binary library is tied to either 32-bit or 64-bit platform. Apparently, in your case, this is 32-bit (x86).

A: To answer my question.
Hans Passant wrote:

Changing the solution platform only affects the C++/CLI project, not the C# project. Right-click the C# project > Properties > Build tab to select the jitter you want to use. Untick the "Prefer 32-bit" checkbox for the x64 solution configuration. Again for the Release configuration.

It worked when I unticked "Prefer 32-bit" in the C# project properties under the Build section.
Thanks!


text:
Q: animate color web icon font doesn't work on IE 8 I'm confused about this problem.
I wanna animate color of an icon font, it works fine in all modern browsers, but not in IE 8!
We have a link:

and this is my CSS code:
#newsletter_subbut {
    border: none;
    height: 30px;
    width:40px;
    margin-left: -8px;
    font-size:22px;
    position:absolute;
    display:inline-block;
    padding-top:9px;
    bottom:0px;
    z-index: 1;
}
.icon-web-mail:before {
    font-family: 'batch';
    speak: none;
    font-style: normal;
    font-weight: normal;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    content: "\F14C";
}

and this is my jQuery code:
$('#newsletter_subbut').find("i").stop().animate({color: "#fa2a18"},'slow');

A: IE8 can't animate the color because the browser can't animate the color on its own. You need a script that will do the work for IE8.
@Hadi added a custom color animation script, that's small and light.
I prefer Jquery UI because it will do the trick for you. it's added in my jsfiddle. (see framework and extensions). http://jsfiddle.net/brutusmaximus/667kF/6/
$('#newsletter_subbut').find("i").stop().animate({color: "#fa2a18"},'slow');

Update: you're adding the icon with
i:before { content: \F14C"; }

The Jquery is animating the actual i  of the content :before. But googling its seems that animating pseudo classes isnt supported yet.
http://css-tricks.com/transitions-and-animations-on-css-generated-content/
There is a solution, but that's only suited for the modern browsers.
Solution for you is to add the unicode in the html. see my http://jsfiddle.net/brutusmaximus/667kF/8/

A: I don't know which version of jquery you are using. Anyway, animate color doesn't work for 1.9.1, may work in earlier version. Sometimes IE8 doesn't understand the animate property. You can try like this -
$('#newsletter_subbut').find("i").stop().animate({color: "#fa2a18"}, 1000, function(){ $('#newsletter_subbut').find("i").animate({ color: "#fa2a18" }); });

or
$('#newsletter_subbut').find("i").animate({ color: "#000" }); // your original color
$('#newsletter_subbut').find("i").animate({ color: "#fa2a18" });

i know this is crazy. But it works for me.
and if you are using jquery 1.9.x then - try this fiddle - http://jsfiddle.net/HETuE/ - it works in ie8 as well


text:
Q: A problem on limits of functions Find two functions $ f(x) $ and $ g(x)$ such that
1) $\lim_{x\to 0} g(x)=10$; $\quad\lim_{x\to 10} f(x)=100$ but  $\lim_{x\to 0} f(g(x))$ doesn't exist.
2)  $\lim_{x\to 0} g(x)=10$; $\quad\lim_{x\to 10} f(x)=100$ but  $\lim_{x\to 0+} f(g(x))=10 $ and  $\lim_{x\to 0-} f(g(x))=100 $
3) $\lim_{x\to 0} g(x)=10$; $\quad\lim_{x\to 10} f(x)=100$ but  $\lim_{x\to 0+} f(g(x))=10 $ and  $\lim_{x\to 0-} f(g(x)) $ doesn't exist
I could only do the 1st one and found the other 2 difficult hence any help would be appreciated.
My solution to the 1st one was
$$g(x) =
\begin{cases}
x+10,  & \text{if $x<0$ } \\
10, & \text{if $x\ge 0$ }  \\
\end{cases} \qquad \text{and} \qquad
f(x) =
\begin{cases}
100,  & \text{if $x<10$ or x>10} \\
50, & \text{if $x= 10$ }  \\
\end{cases}
$$
Then:
$$f(g(x)) =
\begin{cases}
100,  & \text{if $x<0$ } \\
50, & \text{if $x\ge 0$ }  \\
\end{cases}$$
 Is it correct? and please help on other 2

A: Example for 1st: Yours
Example for 2nd: Just modify your example by defining $f$ to be 10 when $x$ is 10, instead of 50.
Example for 3rd: Let
$$g(x)=\begin{cases}10+x\cos\frac1x&x<0\\10&x\ge0\end{cases}$$
$$f(x)=\begin{cases}10&x=10\\100&x\ne10\end{cases}$$
See that $g$ does have limit of $10$ at $0$ (for $x\cos\frac1x$ is continuous at $0$) and that $g$ keeps going above and below 10 as $x$ gets arbitrarily close to $0$.
$g\left(-\frac1{2n\pi}\right)<10$ so $f\circ g$ there is $100$.
$g\left(-\frac2{(2n+1)\pi}\right)=10$ so $f\circ g$ there is $10$.
Enlarging $n$ in each case you keep approaching zero. We clearly see that the left hand limit does not exist.
The right hand limit however clearly exists.

A: For the second problem note that your first example has $\lim_{x\to 0^+}f(g(x))=50$ and $\lim_{x\to0^-}f(g(x))=100$, so a minor adjustment helps.
For the third one, try something like
$$ f(x)=\begin{cases}10&\text{if }x=10,\\100&\text{if }x\ne10\end{cases}$$
$$ g(x)=\begin{cases}10&\text{if }x\ge0,\\10+x\sin \frac1x&\text{if }x<0.\end{cases}$$
Then $f(g(x))=10$ for $x>0$ whereas for $x<0$, we $f(g(x))=100$ if $x=-\frac1{n\pi}$ for some $n\in\mathbb N$ and $f(g(x))=10$ otherwise.


text:
Q: Nested function with an increasing argument If, for example, I have a nesting function like
Nest[1 + x^n (#) &, 1, 3]

it gives the result
1 + x^n (1 + x^n (1 + x^n))

I would need the n to increase by one with every step, just like in a sum or product function, so that the result would be
1 + x^1 (1 + x^2 (1 + x^3))

Is there a way to do this in Mathematica? If so, how?

A: Module[{i = 1}, Nest[1 + x^n (#) &, 1, 3] /. n :> i++]

Or (same result)
Fold[1 + x^#2 #1 &, 1, {3, 2, 1}]

A: Taking a different approach it appears that you are seeking to apply Horner's Method to the polynomial
$$\underset{i=0}{\overset{n}{\sum }}x^{\underset{j=0}{\overset{i}{\sum }}j}$$
Taking $\underset{j=0}{\overset{i}{\sum }}j = \frac{1}{2}i(1+i)$ and making use of HornerForm a function can be created to construct the factored polynomial.
f[n_Integer?Positive] := HornerForm@Sum[x^(i (1 + i)/2), {i, 0, n}]

You are seeking f[3]
f[3]
(* 1 + x (1 + x^2 (1 + x^3)) *)

Hope this helps.

A: In case the intermediate result 1 + x^n (1 + x^n (...)) is not required,
n = 3;
First@Nest[{1 + x^#[[2]] #[[1]], #[[2]] - 1} &, {1, n}, n]

Alternative
A simpler formulation under the same assumption as above
n = 3;
Nest[1 + x^(n--) # &, 1, n]

A: I would use Fold.
Fold[1 + x^#2 (#1) &, 1, Range[3, 1, -1]]
(*  1 + x (1 + x^2 (1 + x^3))  *)

A: Two approaches with Replacement.

z = Nest[1 + x^n (#) &, 1, 3]
ReplacePart[z, Position[z, n][[#]] -> Defer@# & /@ Range[3]]

Also inspired by the @Karsten7's answer and @Eldo's Module version:
Module[{r = 3, i = 1},
Quiet@ReplaceRepeated[(1 + x^n), (1 + x^n) -> 1 + x^n (1 + x^n),
MaxIterations -> r - 1] /. n :> i++]

1 + x (1 + x^2 (1 + x^3))


text:
Q: Delete Duplicate records with exact value How to delete duplicate records when both rows the exact same records?
create table item
(id int,
product_name varchar(20),
quantity int,
amount decimal(10,2)
);

insert into item values(1,"Laptop",10,89.9),(1,"Laptop",10,89.9),(2,"Mixer",8,82),(4,"Fridge",9,100);

This is deleting all the records for duplicate id
DELETE FROM item
WHERE ID IN (SELECT id,row_num FROM (SELECT ID, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS row_num FROM item) t
WHERE row_num > 1);

A: I would actually suggest creating a temporary table, inserting the records sans duplicates, then renaming the temp table to the original table name.
CREATE TABLE item2 (
    id int,
    product_name varchar(20),
    quantity int,
    amount decimal(10,2)
);

INSERT INTO item2 (id, product_name, quantity, amount)
SELECT DISTINCT id, product_name, quantity, amount
FROM item;

DROP TABLE item;
ALTER TABLE item2 RENAME TO item;
DROP TABLE item2;

A: Create a duplicate table with a new primary key or unique key
then get all the duplicate records
select id from item  where id =1 HAVING COUNT(*)>1
will get you all the duplicate records with new primary key or unique key
copy the primary key which you want to delete
delete from item where id IN (1,2,3,5..............)


text:
Q: The recipient does not receive any push message even though I'm able to send push notifications to $RECIPIENT when I'm using console.firebase.com.
If I send with spacialdb/fcm, then no push is sent. Even though the reply from the server looks ok. => (:status_code=>200, :response=>"success")
Any idea what might be wrong?
code
require 'fcm'

fcm = FCM.new('$TOKEN')
registration_ids = ['$RECIPIENT']

options = { data: { score: '123' }, collapse_key: 'updated_score' }
response = fcm.send(registration_ids, options)
puts "Sendt: #{response}"

running code
$ ruby fcm.rb

Sendt: {:body=>"{\"multicast_id\":60356242858746826,\"success\":1,\"failure\":0,
\"canonical_ids\":0,
    \"results\":[{\"message_id\":\"0:1528896392320437%e06a962bca0e\"}]}",
:headers=>{"content-type"=>["application/json; charset=UTF-8"],
    "date"=>["Wed, 13 Jun 2018 13:26:32 GMT"], "expires"=>["Wed, 13 Jun 2018 13:26:32 GMT"], "cache-control"=>["private, max-age=0"],
    "x-content-type-options"=>["nosniff"], "x-frame-options"=>["SAMEORIGIN"],
"x-xss-protection"=>["1; mode=block"],
    "server"=>["GSE"], "alt-svc"=>["quic=\":443\"; ma=2592000; v=\"43,42,41,39,35\""],
    "accept-ranges"=>["none"], "vary"=>["Accept-Encoding"],
     "connection"=>["close"]}, :status_code=>200, :response=>"success",
    :canonical_ids=>[], :not_registered_ids=>[]}

A: The example push code on github.com/spacialdb/fcm was just sending a data push. Since I had not configured my iPhone app to listen to that I could not see that I received any.
To send a push notification you need to follow this syntax:
  # See https://developers.google.com/cloud-messaging/http for more details.

    fcm = FCM.new("API_KEY")
    fcm.send(
       registration_ids: ["4sdsx", "8sdsd"],
       { "notification":
          { "title": "Portugal vs. Denmark",
             "text": "5 to 1"
          },
       }
   )

I've created a PR to update the docs at fcm. Hopefully, they'll accept and make it easier for the next guy. :-)


text:
Q: Create Table Union Between Multiple Data Sources I am working in Crystal Reports 2011 and I am trying to merge two tables from two different data sources into one command to use in a report.
I am having a hard time finding any solid examples online of how to accomplish this inside of a command.  I would expect to use a UNION and it look something like:
SELECT *
FROM DSN1.Employee
UNION
SELECT *
FROM DSN2.Employee

The two tables are the exact same, just in different databases that I cannot alter or add to.
Any guidance would be a tremendous help.  Thank you in advance.

A: Dont know exactly what you mean by having a hard time anyway try something like this ....
Explicitly mention the column names in both selects and use UNION ALL, use fully qualified names of your tables something like this....
SELECT Column1, Column2, Column3, ..... <Other Column Names>
FROM [Database_Name1].[Schema1].[Table_Name1]
UNION ALL
SELECT Column1, Column2, Column3, ..... <Other Column Names>
FROM [Database_Name2].[Schema1].[Table_Name2]

using this syntax eliminates most of the possible errors.


text:
Q: Как сделать автовыдачу роли и приветсвтвие Всем прив, я не особо разбираюсь в питоне поэтому спрашиваю, как написать код, чтобы он писал в канал с id 947591418199822356 приветствие нового участника и выдал ему роль с id 935467923143790602 ? заранее спасибо

A: Для этого нужно использовать ивент on_message. Пример кода как такое можно реализовать:
@bot.event
async def on_member_join(member):
    channel = bot.get_channel(947591418199822356)
    await cahnnel.send(f"На сервере новый участник {member.mention}")
    role = member.guild.get_role(935467923143790602)
    await member.add_roles(role)

Этот код будет писать в канал с id 947591418199822356 о том что появился новый участник на сервере, а также он будет выдавать роль с id 935467923143790602


text:
Q: Django request.user Not Resolving SimpleLazyObject I have a method in my Django app that uses a user ID to find an object.  This method is called via an AJAX call.  When logged in to a valid user account, no matter what I try, request.user evaluates as a django.utils.functional.SimpleLazyObject object and fails to retrieve the data I want (SkillEntry matching query does not exist when it absolutely does exist).  I tried the solution in Django: Filtering drafts by user causes error to no avail.
How can I get user to refer to an actual instance of a user object?
View code:
@login_required
def skill_set(request, name):
    skill = Skill.objects.get(slug=name) # Found.
    level = 0
    user = request.user
    if request.method == 'POST':
        if user.is_authenticated():
            entry = SkillEntry.objects.get(user=user.pk, skill=skill) # Not found.
            entry.level = request.POST['level']
            entry.save()
            return HttpResponse(status=200)
    else:
        return HttpResponseForbidden()

JavaScript client-side code:
function setSkill(skill, value) {
  var req = new XMLHttpRequest();
  req.open("POST", "/skill/" + skill + "/set/", true);
  csrftoken = getCookie('csrftoken');
  req.setRequestHeader("X-CSRFToken", csrftoken);
  req.send('level=' + value);
  var elem = document.getElementById('level');
  elem.innerHTML = "My skill level is " + value + ".";
}

Is there perhaps something I need to set in the request to maintain the session info?  I could swear I've done something like this successfully before on a much earlier version of Django.  I'm using 1.4.3.
EDIT:
Here are the model definitions in my models.py:
class Skill(models.Model):
    name = models.CharField(max_length=100)
    slug = models.CharField(max_length=100, blank=True)
    keywords = models.CharField(max_length=120, blank=True, help_text='List of additional keywords this skill should show up for in search')
    description = models.TextField(null=True, blank=True)
    parent = models.ForeignKey('Skill', null=True, blank=True, help_text='Parent skill.  Leave blank if this is a root category.')

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.name)
        super(Skill, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class SkillEntry(models.Model):
    skill = models.ForeignKey('Skill')
    level = models.IntegerField()
    user = models.ForeignKey(User)
    last_updated = models.DateField(auto_now=True)

    class Meta:
        verbose_name_plural = 'Skill Entries'
        ordering = ('skill__name',)

    def __unicode__(self):
        return self.user.username + ' knows ' + self.skill.name + ' at level ' + str(self.level)

A: As rohan said you need not to use user.pk
Change this query
entry = SkillEntry.objects.get(user=user.pk, skill=skill)

TO
    entry = SkillEntry.objects.get(user=user, skill=skill)

Still if it is not working kindly share your models.py


text:
Q: Can IntelliJ auto complete and include simple generics? I have recently switched back to IntelliJ from Eclipse and one thing I am struggling with is the auto complete, especially when declaring Collections. *This is not a question about which IDE is better its just a question on how to perform a task if that task is possible *
In IntelliJ I type
List<String> listOfNames = new ArrayL  (then key stroke **Alt Ctrl Space**)

I get
List<String> listOfNames = new ArrayList

Which saves me typing three letters, not a great saving I am sure you will agree
If I use Eclipse and use the key stroke Ctrl Space on
List<String> listOfNames = new Ar

I get this result including the generics
List<String> listOfNames = new ArrayList<String>()

I am sure I am missing something like a keystroke I can't find or a plugin I need to add.
Thanks

A: type
List<String> listOfNames = new //be aware of the space after new

and press crtl+shift+spacebar, magic happens!


text:
Q: R Error in CRS(x): PROJ4 argument-value pairs must begin with + read a color space image into a variable
img <- stack('BlueMarbleJuly.tif')

project the raster into a nes coordinate system. Project Robinson
img.merc <- projectRaster(img, crs = st_crs(3857)[[2]])

and I get an error

Error in CRS(x) :
        PROJ4 argument-value pairs must begin with +: PROJCRS["WGS 84 / Pseudo-Mercator",
          BASEGEOGCRS["WGS 84",
              DATUM["World Geodetic System 1984",
                  ELLIPSOID["WGS 84",6378137,298.257223563,
                      LENGTHUNIT["metre",1]]],
              PRIMEM["Greenwich",0,
                  ANGLEUNIT["degree",0.0174532925199433]],
              ID["EPSG",4326]],
          CONVERSION["Popular Visualisation Pseudo-Mercator",
              METHOD["Popular Visualisation Pseudo Mercator",
                  ID["EPSG",1024]],
              PARAMETER["Latitude of natural origin",0,
                  ANGLEUNIT["degree",0.0174532925199433],
                  ID["EPSG",8801]],
              PARAMETER["Longitude of natural origin",0,
                  ANGLEUNIT["degree",0.0174532925199433],
                  ID["EPSG",8802]],
              PARAMETER["False easting",0,
                  LENGTHUNIT["metre",1],
                  ID["EPSG",8806]],
              PARAMETER["False northing",0,
                  LENGTHUNIT["metre",1],
                  ID["EPSG",8807]]],
          CS[Cartesian,2],

what does it mean?

A: You are providing projectRaster with a "wkt" representation of a coordinate reference system, but it expects a "proj4" representation. To fix this, you can do
img.merc <- projectRaster(x, crs = "+init=epsg:3857")

As in
library(raster)
f <- system.file("external/test.grd", package="raster")
x <- raster(f)
merc <- projectRaster(x, crs = "+init=epsg:3857")


text:
Q: How do I develop a biexponential fit equation for a data set? I have a data set, its points create an image like the one below:
I want to fit a biexponential fit through the data, but I don't know how to.
I understand that the equation to use is the following:
$$y = a_1 e^{b-1 t} + a_2 e^{b_2 t} \tag{1}$$
I also understand that this is a sum of two exponential equations but what defines each of these variables? How can I give the right values to the variables in the equation from the data I possess?


text:
Q: Optimal length close to Entropy plus 1 For a fixed $\epsilon> 0$, one need to find a probability distribution $\bf{p}=(p_1,p_2,\ldots,p_n)$ and an optimal code (prefix-free) for this distribution such that the average length $L=\sum_{i=1}^{n} p_il_i$ is arbitrarily close to $H(\bf{p})$$+1$, i.e, $L< H+1-\epsilon$.
I tried assigning $p_2=p_3=\ldots=p_N=p,\ p_1= 1-(N-1)p$ and computed the entropy.But I am getting stuck in finding the optimal code length which is given by Huffman Code. Can any one help me with this ?


text:
Q: Alexa skill responses in different languages Is it possible and if so how to respond within a skill with different languages? For example I'm developing a skill for the German skill store which reads various texts from the internet. Those can be any in language and I can determine the language when I'm about to emit the response.
From what I can see the SSML subset Alexa implements does not specify the language in which the response is given. But Alexa's own Kindle skill is able to read me eBooks in either German or English (perhaps Amazon's own skills are special).

A: As said in other answers the right way is to use the <lang> tag in SSML. However since the english voice do not speak German it is quite weird. The right solution is to change the voice using <voice> tag.
Here is an example in German
<speak>
 <voice name="Hans"><lang xml:lang="de-DE">Ich bin ein Berliner</lang></voice>.
I am a Berliner.
</speak>

It is described in this doc https://developer.amazon.com/fr/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#examplefrench-content-in-an-english-skill

A: It looks like this is not possible at the moment: https://forums.developer.amazon.com/questions/55086/specify-output-language-per-intent.html

A: You can use the <lang> tag in SSML for this.
Here is an example in German.
<speak>
 <lang xml:lang="de-DE">Mein Luftkissenfahrzeug ist voller Aale</lang>.
Hello in the default language.
</speak>

Here is a list of supported Amazon Polly languages for Alexa.


text:
Q: Error message running python code in VS code: No module named "openpyxl" So I am using VS code on Mac. I'd like to read .xls file on python. I have installed openpyxl package using code: python3 -m pip install openpyxl. But when I try to run import openpyxl, I get an error: ImportError: No module named openpyxl. When I tried to install the package once more, I got a message: Requirement already satisfied: openpyxl in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages.
So I don't know, why the package can't be imported. Can anyone help me out?


text:
Q: Passing table contents from SQL to HTML through Python and Jinja I have a table in a database on phpLiteAdmin working on SQL and I'm trying to get that table through Python and then sending it to render in HTML where I want to add these columns and rows into a table. What I did was I SELECTED that column of that table and put it in a variable as such:
symbols = db.execute("SELECT symbol FROM table")
what I'm gettin is something like this:
symbols = ['symbol':'item1','symbol':'item2'...]
and I'm sending it to HTML via python and then using Jinja I'm doing a for loop to print them in a table.. But I want to be able to print each element of that column at a time..
when I use the:
{% for symbol in symbols %}
{{symbol["symbol"]}}
{% endfor %}

it prints all the elements in symbols.. but I want to print only 1 and then later after inserting the other columns I want to print the second and then third element..etc
what I get is either:
{'symbol': 'item1'} {'symbol': 'item2'} ...
or
item1 item2 ...
what I want is to print first just:
item1
and then after I do the same for the other columns I want to print item2
I tried everything I know and I tried to find a way to break out of the loop but I'm not getting the result I want; couldn't find any link or tip concerning this particular issue... is it doable? if so how can I implement it?
P.S: this is my first time posting here.. so I'm still kind of new to this thing :)

A: If your data like this, symbols = ['item1','item2','item2',..] then,
{% for symbol in symbols %}
{{symbol}}
{% endfor %}

And if your data is like symbols = ['symbol':'item1'], Then,
{% for i in symbols %}
{{i.symbol}}
{% endfor %}

A: As I've said in the comments, you should be specific about the actual format of the data you are getting; once you've done so, the solution becomes much clearer.
As far as I can tell, your db interface is giving you back a list of dictionaries. So you can iterate through that list, and in each iteration access the dictionary key you want:
{% for symbol in symbols %}
    {{ symbol['symbol'] }}
{% endfor %}


text:
Q: ACS after session start I am trying to create an ASP.NET MVC site that has specific areas protected by Windows Azure ACS. I want the default area to be unprotected (i.e. allow anonymous users) but only the sub areas to be protected.
I have made this happen by removing the authorization element from the system.web section in my Web.config.
<authorization>
     <deny users="?" />
</authorization>

Then adding a protected location for the desired MVC3 area.
<location path="MyArea">
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</location>

However, my old code that used to access the IClaimsIdentity and pull attributes off it for processing used to live in Session_Start event of my Global.asax. Now that the site does not require authentication to access the default area, Session_Start happens without authentication taking place.
What event can I wire up to handle the authentication event of WIF?
I have implemented a sliding session timeout using SessionAuthenticationModule_SessionSecurityTokenReceived and have tried adding my user analysis logic on the OnPostAuthenticationRequest event to no avail.
I was able to get the user after first wiring up to the following event:
FederatedAuthentication.ServiceConfigurationCreated

Then within this event I wire up to this event:
FederatedAuthentication.WSFederationAuthenticationModule.SignedIn

However, within this event the session is null and session_start is never called again. So it appears the session is getting crushed when redirecting to the identity provider.
anon -> Application_start
anon -> Session_start
anon -> Navigate to /MyArea
anon -> Redirected to ACS -> Redirected to idP
anon -> Log in
auth -> Redirected to /MyArea
auth -> FederatedAuthentication.WSFederationAuthenticationModule.SignedIn occurs, but session is null!
UPDATE: I still have not found a place where both Session and Authentication exist. I am using Unity to detect the user on demand. I'd love it if there was an event that does it as it happens but my work around still works.

A: You've got a few options depending on when and how you want to execute your logic (after login, when creating the session token, after receiving it). The SessionAuthenticationModule_SessionSecurityTokenReceived event should work correctly, but subscribing to it can be tricky. This is how you can do it:
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ...

        FederatedAuthentication.FederationConfigurationCreated += (s, e) =>
        {
            FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenCreated += SessionAuthenticationModule_SessionSecurityTokenCreated;
            FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenReceived += SessionAuthenticationModule_SessionSecurityTokenReceived;
            FederatedAuthentication.WSFederationAuthenticationModule.SessionSecurityTokenCreated += WSFederationAuthenticationModule_SessionSecurityTokenCreated;
            FederatedAuthentication.WSFederationAuthenticationModule.SecurityTokenValidated += WSFederationAuthenticationModule_SecurityTokenValidated;
            FederatedAuthentication.WSFederationAuthenticationModule.SecurityTokenReceived += WSFederationAuthenticationModule_SecurityTokenReceived;
            FederatedAuthentication.WSFederationAuthenticationModule.SignedIn += WSFederationAuthenticationModule_SignedIn;
        };
    }

    void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
    {
        Debugger.Break();
    }

    void SessionAuthenticationModule_SessionSecurityTokenCreated(object sender, SessionSecurityTokenCreatedEventArgs e)
    {
        Debugger.Break();
    }

    void WSFederationAuthenticationModule_SessionSecurityTokenCreated(object sender, SessionSecurityTokenCreatedEventArgs e)
    {
        Debugger.Break();
    }

    void WSFederationAuthenticationModule_SecurityTokenValidated(object sender, SecurityTokenValidatedEventArgs e)
    {
        Debugger.Break();
    }

    void WSFederationAuthenticationModule_SecurityTokenReceived(object sender, SecurityTokenReceivedEventArgs e)
    {
        Debugger.Break();
    }

    void WSFederationAuthenticationModule_SignedIn(object sender, EventArgs e)
    {
        Debugger.Break();
    }
}

All of this code goes in the Global.asax file, and you want to set up the events after the FederationConfigurationCreated event raises (this is when the SessionAuthenticationModule and WSFederationAuthenticationModule will be available). I've added a Debugger.Break in each event handler. Leave them there and debug your application to see when each event is being triggered. This will allow you to decide when and where you want to add your logic.

A: use the [Authorize] attribute on the controllers/actions that you want to secure:
[Authorize]
public ActionResult Index()
{
    return View();
}


text:
Q: jsIt gives a bracketing error, but it doesn't appear. Js i am new to javasacript. Besides, I am developing an application with React. I am getting a parsing error today. probably a punctuation error. but I couldn't find where. can you help me ?
export const CategorySuite = ({items}) => {

  return (
{items.map(item => <Item item={item}/>)}

  );
};

Error =>

  13 |
  14 |   return (
> 15 | {items.map(item => <Item item={item}/>)}
     |       ^
  16 |
  17 |   );
  18 | };

A: If you're not returning JSX, you can't use the outer parentheses. Should be just:
return items.map(...)


text:
Q: How to disable lighttpd access log? I'm using lighttpd and access.log is increasing too fast.
Is there a good way to disable access log?
At the lighttpd.conf seems that is possible to disable "mod_accesslog" in the "server.modules", but the comment advices to don't do.
lighttpd 1.4.35

A: You can disable lighttpd logging by commenting the lines as shown in bellow:
#"mod_accesslog"

#accesslog.filename          = "/var/log/lighttpd/access_log"

However, it is not a good idea. Instead, you should configure log rotation and backup.


text:
Q: Installing NVDIA-driver-525 fails, what am I missing? Sorry, I am complete newbie regarding drivers and similar stuff. My Lenovo IdeaPad S145 laptop has the NVIDIA sticker, therefore I assume the hardware is capable of running NVIDIA drivers.I think, below screenshot proves that I am using the NVIDIA driver. Please correct me if I am being wrong here!
But somehow it is not enough (not even after multiple reboot):

My OS is Ubuntu 20.04
What am I missing? Any suggestion is welcome, because even ChatGPT failed to give me a useful answer:-)


text:
Q: How to install Firefox 14.0.1 (or any other latest version) on Ubuntu 10.10?
Possible Duplicate:
How do I install the latest stable version of Firefox?

Here is the deal. My primary OS is Ubuntu 10.10. I like it so far and I don't want to upgrade yet to the latest version.
But, I also want to install the latest stable version of Firefox which is 14.0.1, as it is my favourite browser. What should I do as there are no more updates for Maverick through the official update manager?
I also have installed Opera through the latest version repository and whenever there is a new version I can update it. Isn't there something similar for Firefox?

A: Just go to the firefox download web page and install it directly.

*

*download the archive (firefox-14.0.1.tar.bz2.crdownload)

*unpack and run it:
tar xjf firefox-14.0.1.tar.bz2.crdownload
cd firefox/
./firefox

alternatively, double click on the package and when it unpacks, double click on the firefox executable within.

*you can move the whole firefox directory wherever you want

*you can create a desktop shortcut, in 10.04 you just need to right-click on the desktop and select "create launcher". Point it to the "firefox" file in the newly unpacked "firefox/" directory.

P.S. As someone suggested, moving to a more recent stable release is a good idea. At least to 11.04. The LTS (long term support) releases get regular security updates and bug fixes.


text:
Q: how to check for NO INTERNET in devices below API level 21 This is my MainActivity, I have registerd my network call back in the onstart. In this code onUnavailable() is never called no matter the device is turned on to the internet wifi or not. I want to check for the internet after clicking a button it will proceed to next activity if internet is connected and otherwise not
public class MainActivity extends AppCompatActivity {
    private TextView textView;
    ConnectivityManager.NetworkCallback networkCallback;
    ConnectivityManager manager;
    public static final String TAG = "bantai";
    private NetworkRequest networkRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.internetTextview);
        networkRequest = new NetworkRequest.Builder().build();
        manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

        networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                Log.d(TAG, "onAvailable: ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "onAvailable: "+ Thread.currentThread().getName());
                        textView.setText("onAvailable");
                    }
                });

            }

            @Override
            public void onLosing(@NonNull Network network, int maxMsToLive) {
                super.onLosing(network, maxMsToLive);
                Log.d(TAG, "onLosing: ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "onAvailable: "+ Thread.currentThread().getName());
                        textView.setText("loosing");
                    }
                });
            }

            @Override
            public void onLost(@NonNull Network network) {
                super.onLost(network);
                Log.d(TAG, "onLost: ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "onAvailable: "+ Thread.currentThread().getName());
                        textView.setText("lost");
                    }
                });            }

            @Override
            public void onUnavailable() {
                super.onUnavailable();
                Log.d(TAG, "onUnavailable: ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "onAvailable: "+ Thread.currentThread().getName());
                        textView.setText("unavailable");
                    }
                });            }

            @Override
            public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
                super.onCapabilitiesChanged(network, networkCapabilities);
                Log.d(TAG, "onCapabilitiesChanged: ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "onAvailable: "+ Thread.currentThread().getName());
                        textView.setText("capability");
                    }
                });            }

            @Override
            public void onLinkPropertiesChanged(@NonNull Network network, @NonNull LinkProperties linkProperties) {
                super.onLinkPropertiesChanged(network, linkProperties);
                Log.d(TAG, "onLinkPropertiesChanged: ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "onAvailable: "+ Thread.currentThread().getName());
                        textView.setText("link");
                    }
                });            }

            @Override
            public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {
                super.onBlockedStatusChanged(network, blocked);
                Log.d(TAG, "onBlockedStatusChanged: ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "onAvailable: "+ Thread.currentThread().getName());
                        textView.setText("blocked");
                    }
                });            }
        };
    }

    @Override
    protected void onStart() {
        super.onStart();
        manager.requestNetwork(networkRequest,networkCallback);

    }

    @Override
    protected void onStop() {
        super.onStop();
        manager.unregisterNetworkCallback(networkCallback);
    }

Also ConnectivityManager.requestNetwork(networkRequest, networkCallback, 3000) this command requires Api level 21 + with a timeout of 3 seconds.

A: for checking internet easily use this function, it is responsive on api 16 and above :
in AndroidManifest.xml add :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

now for checking network status :

*

*getActiveNetworkInfo is deprecated on API 29.

*getAllNetworkInfo is deprecated on API 23.
fun isConnected(): Boolean {

 val hasInternet: Boolean

 val connectivityManager =
     ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
     val networkCapabilities = connectivityManager.activeNetwork ?: return false
     val actNw =
         connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
     hasInternet = when {
         actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
         actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
         actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
         else -> false
     }
 } else {
     hasInternet = try {
         if (connectivityManager.activeNetworkInfo == null) {
             false
         } else {
             connectivityManager.activeNetworkInfo?.isConnected!!
         }
     } catch (e: Exception) {
         false
     }
 }
 return hasInternet}


text:
Q: Put dockerfile at top level folder of solution I have a Visual Studio solution with two projects. I would like to have the Dockerfile at the same level as my solution file (sln) instead of having it inside my API project (default behavior). I have tried several options, even adding to my API project:
<PropertyGroup>
    <DockerfileContext>../Dockerfile</DockerfileContext>
</PropertyGroup>

However, Visual Studio is complaining "Error    CTC1023 No Dockerfile could be found. Please make sure you have a Dockerfile called 'Dockerfile' adjacent to the project file"
Is it possible to have Docker integration with Visual Studio and place dockerfile at sln level?

A: Ok, I found the answer, will post it just in case someone face the same situation.
I added the following attribute in the API project csproj file:
<PropertyGroup>
    <!--Other properties ... ->
    <DockerfileFile>../Dockerfile</DockerfileFile>
 </PropertyGroup>

Where ../Dockerfile is the relative path to the dockerfile from the main project.
Now it works.


text:
Q: Фильтрация массива по датам У меня собирается массив из календаря, то есть когда я нажимаю на календаре на дату, то она заносится в массив и выходит такой массив ['дата от', 'дата до'], потом у меня есть еще один массив который берет данные с excel, в нем первый элемент это дата, и мне нужно как-то фильтровать этот массив чтобы там были данные от такой даты - до такой даты
 Вот массив с данными
 и вот массив с началом даты и концом
Нужно вывести массив с данными между этими датами

A: JavaScript может распознать текущую дату из строки вроде "2022-10-2":
const date = new Date("2022-10-2") // Всё ок.

Из этого можно получить временную метку:
const timestamp = date.getTime();

Она в свою очередь легко поддается манипуляциям.
Я точно не знаю строки в каких форматах распорзнаются для получения текущей даты. Однако даже если у Вас есть только месяц и день, можно преобразовать это в строку похожую на ту, которая выше: год-месяц-день
Например:
let label = "06.10";
label = [ "2022", ...label.split(".").reverse() ]
  .join("-"); // "2022-10-06"

const date = new Date(label);

Надеюсь, с тем, чтобы отфильтровать массив временных меток, проблем у Вас не возникнет
Изменено:
new Date() поддерживает такой формат: "06.04.2022", что очень удобно. Но всё-равно меняет день и месяц местами (6 месяц, 4 день). Будьте с этим осторожны)


text:
Q: Is it possible to access Docker containers living in Azure Container Instance(s) via RESTful endpoints? I am trying to proof out the ability to store my Docker container in Azure Container Instance. I currently have my container in Azure Container Instance but I am trying to access it via RESTful endpoints.
I have currently configured my Azure AD account to grant my application access to the Windows Azure Service Management API with the delegate access.
I am also using Postman to create the Bearer token to then pass down to my URL:
POST
https://management.azure.com/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/slack-bots-v2/providers/Microsoft.ContainerInstance/containerGroups/testing/exec?api-version=2018-04-01
I am however getting an error of:
{
    "error": {
        "code": "AuthorizationFailed",
        "message": "The client '<CLIENT_ID>' with object id '<OBJECT_ID>' does not have authorization to perform action 'Microsoft.ContainerInstance/containerGroups/exec/action' over scope '/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/slack-bots-v2/providers/Microsoft.ContainerInstance/containerGroups/testing'."
    }
}
Question(s):

*

*is it possible to access my container instance via RESTful API?

*is there a different Azure AD permission that needs to be set in order to access this?

*has anyone solved a similar problem outside of Azure but maybe with another public cloud provider, (AWS, GCP, and etc)?