text:
Q: Solving Burger's equation with NDSolve at large time I want to solve the following Burger's equation
$$\partial_tu+\partial_x\left(\frac{u^2}{2}\right)=0,~~x\in[0,2\pi],~t>0\\u(x,0)=\frac{1}{3}+\frac{2}{3}\sin(x)$$
with mathematica. Here's my code:
Clear["Global`*"];
{SOL} = NDSolve[{D[u[x, t], t] + u[x, t] D[u[x, t], x] == 0,
    u[x, 0] == 1/3 + 2 Sin[x]/3}, u, {x, 0, 2 Pi}, {t, 0, 2 Pi},
   Method -> {"MethodOfLines",
     "SpatialDiscretization" -> {"TensorProductGrid",
       "MaxStepSize" -> 2 Pi/4000}}];
Plot[u[x, 1.5] /. SOL, {x, 0, 2 Pi}, AxesLabel -> Automatic]

The result looks good at time $t=1.5$:

I wanna solve this equation numerically for larger $t$, for example $t=2\pi$, however when I plot $t=2\pi$ everything goes wrong,

Obviously the exact solution cannot be like that, it seems the above code is no longer working for large $t$, but I don't know how to edit the code to make the numerical results reasonable. May I ask what should I add/change to the code to solve the results for $t=2\pi$? Thanks in advance!
Edit: If we don't use FEM, we can try some other ways, such as the Godunov's scheme, and the code goes like below (The ExactSol in the code is the solution by using other methods, here I used mesh size $\Delta x = \frac{2\pi}{10} ,\frac{2\pi}{20} , \cdots\frac{2\pi}{640}$ to show that this is actually working~)
color[1] = Red; color[2] = Orange; color[3] = Yellow; color[4] = Green; color[5] = Cyan; color[6] = Blue; color[7] = Purple;
For[o = 1, o <= 7, o++,
  f[u_] = u^2/2; T = 2 Pi; h = 0.4 Pi/2^o; k = 2 Pi/1280;
  Godunov[ul_, ur_] = If[ul > ur, Max[f[ul], f[ur]], If[ul <= 0 <= ur, 0, Min[f[ul], f[ur]]]];
  For[m = -2000, m <= 2000, m++, x[m] = h m; u[m, 0] = 1/3 + 2 Sin[x[m]]/3];
  For[n = 0, n < 1280, n++,
   For[m = -1999 + n, m < 1999 - n, m++,
     u[m, n + 1] = N[u[m, n] - k*(Godunov[u[m, n], u[m + 1, n]] - Godunov[u[m - 1, n], u[m, n]])/h];
     ];
   ];
  s[o] = ListLinePlot[Table[u[m, 1280], {m, 0, 5*2^o}], DataRange -> {0, 2 Pi}, PlotStyle -> {color[o], Thickness[0.001]}, Frame -> True, PlotLegends -> {5*2^o "Grids Numerical Solution"}, FrameTicks -> {{{-0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}, True}, {{0, 0.5 Pi, Pi, 1.5 Pi, 2 Pi}, True}}];
 ];
Show[s[1], s[2], s[3], s[4], s[5], s[6], s[7], Plot[ExactSol[x, 2 Pi], {x, 0, 2 Pi}, PlotRange -> {-0.5, 1}, PlotStyle -> {Black, Thickness[0.0015]}, Frame -> True, PlotLegends -> {"Exact Solution"}, FrameTicks -> {{{-0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}, True}, {{0, 0.5 Pi, Pi, 1.5 Pi, 2 Pi}, True}}], PlotRange -> All]

and the result looks nice too :)

A: I am not sure if there are options to improve NDSolve. I tried stiffness method, but that did not help.
But since the inviscid Burgers' equation has analytical solution, then you can use that.

Where $f(x)$ above is your initial condition. Mathematica DSolve  gives this also:
DSolve[{D[u[x, t], t] + u[x, t]* D[u[x, t], x] == 0,
  u[x, 0] == 1/3 + 2 Sin[x]/3}, u[x, t], x, t]

gives
Solve[u[x, t] == 1/3 (1 + 2 Sin[x - t u[x, t]]), u[x, t]]

The problem is that the solution is implicit. The solution $u$ shows on both sides.
But you could generate sample points as follows. Here is at t=1.5
Clear["Global`*"]
epsilon := 0.01;
f[z_] := 1/3 + 2 Sin[z]/3;
u[x_, t_ /; t > 0] := u[x, t] = f[x - u[x, t - epsilon]*t]
u[x_, t_] := u[x, 0] = f[x];
maxTime = 1.5;
data = Table[u[x, t], {t, 0, maxTime, epsilon}];
Plot[Evaluate[Last@data], {x, 0, 2*Pi}, PlotStyle -> Red,  GridLines -> Automatic, GridLinesStyle -> LightGray]

And at t=2

Since the trajectory of that characteristic is (from same link above, Wikipedia)

you can just use implicitplot? May be better and more accurate:
t = 1.5;
f[x_] := 1/3 + 2 Sin[x]/3;
ParametricPlot[{t*f[x] + x, f[x]}, {x, 0, 2*Pi}, AspectRatio -> 1,
 GridLines -> Automatic, GridLinesStyle -> LightGray,
 PlotStyle -> Red]

t = 2;

t = 3;

t = 2*Pi;

A: Similar problems have been discussed in this site for several times:
Solution of Burgers equation with some initial data
1D Euler equations (fluid dynamics) with NDSolve
Circumvent NDSolve::bdord: error for 1-D Euler Equations
In short, PDE related to hyperbolic conservation law whose solution involves shock wave is not well handled by NDSolveat the moment. We can of course add artificial viscosity (as shown in N0va's answer and linked questions above):
mol[n:_Integer|{_Integer..}, o_:"Pseudospectral"] := {"MethodOfLines",
  "SpatialDiscretization" -> {"TensorProductGrid", "MaxPoints" -> n,
    "MinPoints" -> n, "DifferenceOrder" -> o}}

{ufunc, vfunc} =
 NDSolveValue[{With[{μ = 0.001, u = u[x, t], v = v[x, t]},
                    {D[u, t] + 1/2 D[v, x] == μ D[u, x, x],
                     v == u^2,
                    {v == (1/3 + 2 Sin[x]/3)^2,
                     u == 1/3 + 2 Sin[x]/3} /. t -> 0}],
               u[0, t] == u[2 Pi, t]}, {u, v}, {x, 0, 2 Pi}, {t, 0, 20},
              Method -> mol[600, 8]]
(* {1.94787, Null} *)

but as we can see, it's rather tricky.

Remark
I've introduced the intermediate variable v to make the solution
respect the conservation law, otherwise the obtained solution will
probably be undesired. See here
for more info.

So I'd like to show one more solution based on Julia package Trixi. Thanks to ExternalEvaluate, nowadays we can easily call Julia inside Mathematica (Remember to configure your Julia and install the needed packages first):
session = StartExternalSession["Julia"];
eval = ExternalEvaluate[session, #] &;

eval@"using OrdinaryDiffEq, Trixi"; // AbsoluteTiming
(* {33.4249, Null} *)

sol = eval@"
equations = InviscidBurgersEquation1D()
ic(x, t, equation::InviscidBurgersEquation1D)=1/3 + 2/3*sin(x[1])

volume_flux = flux_lax_friedrichs
solver = DGSEM(polydeg=3,surface_flux=flux_lax_friedrichs,
               volume_integral=VolumeIntegralFluxDifferencing(volume_flux))

xmin = 0
xmax = 2*pi
mesh = TreeMesh(xmin, xmax,
                initial_refinement_level=8,
                n_cells_max=10^4)
semi = SemidiscretizationHyperbolic(mesh, equations, ic, solver)

tspan = (0, 20)
ode = semidiscretize(semi, tspan)
sol = solve(ode,  SSPRK43())"; // AbsoluteTiming
(* {18.8699, Null} *)

xcoord =
  eval@"collect(Iterators.flatten(semi.cache.elements.node_coordinates))";
tcoord = eval@"sol.t";
solfunc = ListInterpolation[sol[[;; ;; 4]], Flatten /@ {xcoord[[;; ;; 4]], tcoord}
                            (*, InterpolationOrder -> 1*)];
Manipulate[Plot[solfunc[x, t], {x, 0, 2 Pi}, PlotRange -> {-0.5, 1.5}],
           {t, 0, 2 Pi}]

Notice b.c. isn't explicitly set in Julia code, because the default setting of SemidiscretizationHyperbolic is periodic b.c., which is exactly what we need in this case.
To understand the Julia code, you may want to read
https://github.com/trixi-framework/Trixi.jl/issues/939
https://github.com/trixi-framework/Trixi.jl/issues/958
Finally a comparison of the two solutions above:
Plot[{ufunc[x, 2 Pi], solfunc[x, 2 Pi]}, {x, 0, 2 Pi},
 PlotStyle -> {Automatic, Dashed}]

Update
In 1st solution above TensorProductGrid sub-method is used for spatial discretization. One can use FiniteElement method instead. The advantage of FiniteElement is we don't need to introduce intermediate variable like above (maybe because the ODE (DAE?) solver has done a better job in this case), but the disadvantage is, the behavior of periodic b.c. of FiniteElement is undesired. This issue is discussed in this post. To circumvent this, we need to introduce a ghost layer and set 2 PeriodicBoundaryCondition:
molfem[measure_: Automatic] := {"MethodOfLines",
   "SpatialDiscretization" -> {"FiniteElement",
     "MeshOptions" -> MaxCellMeasure -> measure}};

With[{μ = 0.001, eps = 1/1000},
   solfem = NDSolveValue[{D[u[x, t], t] +
        1/2 D[u[x, t]^2, x] == μ D[u[x, t], x, x], u[x, 0] == 1/3 + 2 Sin[x]/3,
      PeriodicBoundaryCondition[u[x, t], x == 0, TranslationTransform[{2 Pi}]],
      PeriodicBoundaryCondition[u[x, y], x == 2 Pi + eps,
       TranslationTransform[{-2 Pi}]]}, u, {x, 0, 2 Pi + eps}, {t, 0, 20},
     Method -> molfem[0.01]]]; // AbsoluteTiming
(* {34.2291, Null} *)

Let's compare the wave speed at $t=20$.
With[{μ = 0.001},
   solundesired =
    NDSolveValue[{D[u[x, t], t] + 1/2 D[u[x, t]^2, x] == μ D[u[x, t], x, x],
      u[x, 0] == 1/3 + 2 Sin[x]/3, u[0, t] == u[2 Pi, t]},
      u, {x, 0, 2 Pi}, {t, 0, 20},
      Method -> mol[1000, 8]]]; // AbsoluteTiming
(* {1.78104, Null} *)

Plot[{ufunc[x, 20], solfem[x, 20], solfunc[x, 20], solundesired[x, 20]},
     {x, 0, 2 Pi}, PlotStyle -> {Automatic, Dashed, DotDashed}]

A: The answer of Nasser is only in parts correct. The analytic/implicit solution
$$
u(x,t) = f(\xi) = f(x-ut), \quad \xi = x - f(\xi) t
$$
is only the physical solution in the interval $0\le t \le t_b$ with
$$
t_b = \inf_x\left(\frac{-1}{ f'(x)}\right),
$$
for more details consult the already mentioned wikipedia article.
For the initial condition at hand $t_b=3/2$ and it is no coincidence that NDSolve fails at $t\approx 1.5$ since at this point a shockwave is formed at $x\approx3.6$. The physical solution to the Burger's equation for $t>t_b$ is no longer smooth/analytic and only exists in a weak sense. Naive discretization schemes (like finite differences) are notorious for being ill suited for problems like the invicit Burgers equation. I do not know if there are options for NDSolve which can cope with shock formation but one way to weaken the numerical difficulty without changing the qualitative features of the physical solution too much is to introduce a small viscosity term and to study the viscous Burgers equation
$$
\frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} = \nu\frac{\partial^2 u}{\partial x^2},
$$
with the viscosity $\nu>0$. The introduced diffusion smears out the shockwave and makes the solution differentiable this combined with a high resolution allows the "MethodOfLines" option for NDSolve to work. I included proper (periodic) boundary condition to get a well defined problem:
eqs={D[u[x,t],t]+u[x,t] D[u[x,t],x]==\[Nu]*D[u[x,t],x,x],u[x,0]==1/3+2 Sin[x]/3,u[0,t]==u[2\[Pi],t]}

With small diffusion ($\nu=0.01$) it is possible with NDSolve to compute a solution after shock formation:
{sol}=NDSolve[eqs/.\[Nu]->0.01,u,{x,0,2 Pi},{t,0,2},Method->{"MethodOfLines","SpatialDiscretization"->{"TensorProductGrid","MinPoints"->1000, "DifferenceOrder"->"Pseudospectral"}},AccuracyGoal->10,PrecisionGoal->10];

ti={0,1,1.5,2.};
Table[u[x,t],{t,ti}]/.sol;
Plot[%,{x,0,2 Pi},FrameLabel->{"x","u[x,t]"},Frame->True,PlotRange->{{0,2\[Pi]},{-0.5,1.5}},PlotLegends->Placed[Row[{"t=",#}]&/@ti,{Right,Top}]]

without diffusion ($\nu=0$) it is not beyond $t_b=1.5$:
{sol}=NDSolve[eqs/.\[Nu]->0.0,u,{x,0,2 Pi},{t,0,2},Method->{"MethodOfLines","SpatialDiscretization"->{"TensorProductGrid","MinPoints"->1000, "DifferenceOrder"->"Pseudospectral"}},AccuracyGoal->10,PrecisionGoal->10];

ti={0,1,1.5,1.6};
Table[u[x,t],{t,ti}]/.sol;
Plot[%,{x,0,2 Pi},FrameLabel->{"x","u[x,t]"},Frame->True,PlotRange->{{0,2\[Pi]},{-0.5,1.5}},PlotLegends->Placed[Row[{"t=",#}]&/@ti,{Right,Top}]]

The solution to the PDE beyond $t_b$ is no longer naively differentiable after the formation of a shock (for $\nu=0$) which gives rise to the spurious oscillations we can see in the plot above at $t=1.6$. As time progresses the magnitude of those oscillations increase and ultimately destabilize the numerical scheme.
A proper way to solve the invicit Burger's equation numerically would be to deploy shock capturing numerical schemes for conservation equations like specific finite volume or finite element methods which work with a weak formulation and which compute weak, physical solutions to this kind of PDEs.

A: Following the example set by xzczd's answer: an alternative to an external library would be to implement a simple shock capturing finite volume scheme like the one put forward in New High-Resolution Central Schemes for Nonlinear Conservation Laws and Convection–Diffusion Equations, 2000, A. Kurganov and E. Tadmor -- KT FV scheme -- see also this wikipedia article. I have implemented this scheme in Mathematica a few years ago. The scheme is purpose build for hyperbolic conservation laws and includes extensions for the treatment of parabolic conservation laws (e.g. PDEs including diffusion terms). The scheme can be applied directly to non-linear PDEs (initial value problems) of the type
$$
\begin{align}
\partial_t u(t,x)+\partial_x F(t,x,u)&=\partial_x Q(t,x,u,\partial_x u)\\
u(0,x)&=u_0(x)
\end{align}
$$
with a broad range of boundary conditions (ones which can be implemented easily with ghost-cells). Below you find an implementation of the scheme using CompiledFunction for performance.
(** Periodic boundary conditions for ghost cells **)
BCperiodic=Function[{vin},Module[{v},
    v=vin;
    v[[1]]=v[[-5]];(* Subscript[u, -2 ]= Subscript[u, n-3] *)
    v[[2]]=v[[-4]];(* Subscript[u, -1 ]= Subscript[u, n-2] *)
    v[[-3]]=v[[3]];(* Subscript[u, n-1 ]= Subscript[u, 0] *)
    v[[-2]]=v[[4]];(* Subscript[u, n] = Subscript[u, 1] *)
    v[[-1]]=v[[5]];(* Subscript[u, n+1] = Subscript[u, 2] *)
    v
]];

(** Selected MUSCL scheme Flux limiter **)
ϕMinMod=Function[{Δuj,Δujp1},If[Abs@Δujp1==0.,1.,Max[0.,Min[1.,Δuj/Δujp1]]]]; (* MinMod Limiter [https://en.wikipedia.org/wiki/Flux_limiter] *)

(** Main step method **)
ClearAll[KTstepper];
KTstepper[nx_][Δx_,x_,x12_][F_,dFdu_,Q_,BC_,pars___]:=
Compile[{{t,_Real},{v,_Real,1}},
    Module[{
        u,(* Conserved quanties, dim=nx+4 *)
        Δu,(* Differences of conserved quanties, dim=nx+3 *)

        ux,(* Reconstructed slopes, dim =nx+2 *)
        up12T,(* Right intermediate values at the cell interface, dim =nx+1 *)
        um12T,(* Left intermediate values at the cell interfaces, dim=nx+1 *)
        Fp12T,(* Advection flux through the cell interfaces, dim=nx+1 *)
        Fm12T,(* Advection flux through the cell interfaces, dim=nx+1 *)
        λp12T, (* Jacobian eigenvalues (single value) the cell interfaces, dim=nx+1 *)
        λm12T, (* Jacobian eigenvalues (single value)the cell interfaces, dim=nx+1 *)
        a12T,(* Approxmiate velocities at the cell interfaces, dim=nx+1 *)
        H12 ,(* Numerical advection fluxes at the cell interfaces, dim=nx+1 *)

        P12(* Diffusion fluxe through the cell interfaces, dim =nx+1 *)
    },
        (* **** Boundary condition **** *)
        u=BC[Join[{0.,0.},Take[v,{1,nx}],{0.,0.}]];

        (* **** PDE Convection Flux **** *)
        Δu=Differences[u];
        ux=MapThread[0.5*#2(ϕMinMod[#1,#2])&,{Take[Δu,{1,-2}],Take[Δu,{2,-1}]}];(* [KTO2-0, eq. (2.4)*0.5*Δx]: modified to be compatible with generic flux limiters *)
        up12T=Take[u,{3,-2}]-Take[ux,{2,-1}];(* [KTO2-0, eq. (4.5)]: modified to be compatible with generic flux limiters *)
        um12T=Take[u,{2,-3}]+Take[ux,{1,-2}];(* [KTO2-0, eq. (4.5)]: modified to be compatible with generic flux limiters *)

        λp12T=MapThread[dFdu[t,#1,#2,pars]&,{x12,up12T}];
        λm12T=MapThread[dFdu[t,#1,#2,pars]&,{x12,um12T}];
        a12T=MapThread[Max[Max@Abs@#1,Max@Abs@#2]&,{λp12T,λm12T}]; (* [KTO2-0, eq. (3.2)] [KTO2-0, footnote 2] *)

        Fp12T=MapThread[F[t,#1,#2,pars]&,{x12,up12T}];
        Fm12T=MapThread[F[t,#1,#2,pars]&,{x12,um12T}];
        H12=0.5*(Fp12T+Fm12T-a12T*(up12T-um12T)); (* [KTO2-0, eq. (4.4)] *)

        (* **** PDE Diffusion Flux **** *)
        P12=0.5*MapThread[Q[t,#1,#3,#5,pars]+Q[t,#2,#4,#5,pars]&,{
            Join[{x12[[1]]-Δx*0.5},x],
            Join[x,{x12[[-1]]+Δx*0.5}],
            Take[u,{2,-3}],
            Take[u,{3,-2}],
            Take[Δu,{2,-2}]/Δx
        }]; (* [KTO2-0, eq. (4.14)] *)

        (* **** Result **** *)
        Return[Flatten[(-Differences[H12]+Differences[P12])/Δx,1]] (* [KTO2-0,eq.(4.13)] *)
    ], RuntimeOptions->"Speed", CompilationOptions->{"InlineExternalDefinitions"->True,"ExpressionOptimization"->True}
]

(** Solver/time-stepper using NDSolve to solve the ODE (MOL) system of KTstepper *)
ClearAll[KTsolver]
KTsolver/:Options[KTsolver]={AccuracyGoal->Automatic,PrecisionGoal->Automatic,WorkingPrecision->MachinePrecision,Method->Automatic,MaxSteps->Automatic};
KTsolver[OptionsPattern[]][x0_,x1_,n_Integer][F_,dFdu_,Q_,BC_,params___][u0_][t0_,t1_]:=Module[{
    no,
    Δx,xi,xi12,
    v0,
    PDEcompileFkt,PDEfkt,PDEsystem,PDEv,PDEt,PDEsolver,PDEsolution,
    nt,tw,tm},

    (* x0 and x1 are the first and last cell centers *)
    Δx=(x1-x0)/(n-1);
    xi=Table[x0+Δx*i,{i,0,n-1}];
    xi12=Table[x0+Δx*(i-0.5),{i,0,n}];

    v0=u0[#]&/@xi;(* approimate cell averages with mid point value *)

    PDEcompileFkt=KTstepper[n][Δx,xi,xi12][F,dFdu,Q,BC,params];
    PDEfkt[t_?NumericQ,v_]:=PDEcompileFkt[t,v];
    PDEsystem={Equal[PDEv[t0],v0],Equal[Derivative[1][PDEv][PDEt],PDEfkt[PDEt,PDEv[PDEt]]]};

    nt=0;
    tw=-AbsoluteTime[];
    PDEsolver=Inactive[NDSolveValue][PDEsystem,PDEv,{PDEt,t0,t1},
        StepMonitor:>{nt++,tm=PDEt},
        Method->OptionValue[Method],
        AccuracyGoal->OptionValue[AccuracyGoal],
        PrecisionGoal->OptionValue[PrecisionGoal],
        WorkingPrecision->OptionValue[WorkingPrecision],
        MaxSteps->OptionValue[MaxSteps]
    ];
    PDEsolution=Activate@PDEsolver;

    tw+=AbsoluteTime[];
    tm=PDEsolution["Domain"]//Last//Last;

    KTsolution[<|"solution"->PDEsolution,"n"->n,"no"->no,"Δx"->Δx,"xi"->xi,"nt"->nt,"tw"->tw,"t0"->t0,"t1"->t1,"tm"->tm|>]
]

(** Output wrapper **)
ClearAll[KTsolution];
KTsolution[asoc_][key_]:=asoc[key] /; MemberQ[Keys[asoc], key]
KTsolution[asoc_][key_Symbol]:=asoc[ToString@key] /; MemberQ[Keys[asoc], ToString@key]
KTsolution[asoc_][t_]:=With[{sol=asoc["solution"],xi=asoc["xi"]},{xi,sol[t]}\[Transpose]/;!MissingQ[sol]]

MakeBoxes[KTsolution[asoc_Association],StandardForm]/;BoxForm`UseIcons:=Module[{xi,n,no,Δx,nt},
    (* [https://mathematica.stackexchange.com/a/99914] *)
    (* [https://mathematica.stackexchange.com/a/79891] *)
    xi=With[{a=asoc["xi"]},If[MissingQ[a],{},{a[[1]],a[[2]],Skeleton[Length[a]-3],Last@a}]];
    n=With[{a=asoc["n"]},If[MissingQ[a],0,a]];
    nt=With[{a=asoc["nt"]},If[MissingQ[a],0,a]];
    Δx=With[{a=asoc["Δx"]},If[MissingQ[a],Missing,a]];
    BoxForm`ArrangeSummaryBox[KTsolution,
        KTsolution[asoc],
        None,
        {{"n = "<>ToString[n],"Δx = "<>ToString[Δx]},{Row[{"Subscript[x, i] = ",xi}],SpanFromLeft},{"nt="<>ToString[nt],SpanFromLeft}},
        {},
        StandardForm,
        "Interpretable"->True
    ]
]

The only interesting part of the code above is the one for KTstepper as it implements the semi-discrete method-of-lines (MOL) finite volume discretion of Kurganov and Tadmore. KTsolver generates and solves the MOL ODE system using NDSolve and KTsolution is just an output wrapper.
In the above notation the Burger's equation is given by $F(t,x,u)=F(u)=u^2$ and $Q(t,x,u,\partial_x u)=Q(\partial_x u)=\nu \partial_x u$ in case of non-vanishing diffusion $\nu>0$. Apart from initial and boundary (in this example periodic ones) conditions the scheme requires the Eigenvalues of the Jacobian $(\partial F/\partial u)$, which in case of the Burger's equation is simply $\partial F/\partial u = u$. The following code computes three solutions at variable $\nu$:
burgersEq=Sequence[{t,x,u}|->0.5u^2,{t,x,u}|->u,{t,x,u,dudx,nu}|->nu*dudx,BCperiodic];

νi={0,0.01,0.05};
νiSols=Table[KTsolver[AccuracyGoal->6,PrecisionGoal->6][0.,2π,512][burgersEq,ν][x|->1/3+2 Sin[x]/3][0,2π],{ν,νi}]

Manipulate[ListLinePlot[#[t]&/@νiSols,GridLines->Automatic,Frame->True,FrameLabel->{"x","u["<>ToString[NumberForm[t,3]]<>",x]"},PlotLegends->Placed[Row[{"ν=",#}]&/@νi,{Left,Top}],PlotRange->{{0,2π},{-0.5,1.25}},ImagePadding->{{45,10},{35,10}}],{t,0,2π}]

The method works well even on small spatial grids:
ni={64,128,256,512};
niSols=Table[KTsolver[AccuracyGoal->6,PrecisionGoal->6][0.,2π,n][burgersEq,0][x|->1/3+2 Sin[x]/3][0,2π],{n,ni}]

Manipulate[ListLinePlot[#[t]&/@niSols,GridLines->Automatic,Frame->True,FrameLabel->{"x","u["<>ToString[NumberForm[t,3]]<>",x]"},PlotLegends->Placed[Row[{"Subscript[n, x]=",#}]&/@ni,{Left,Top}],PlotRange->{{0,2π},{-0.5,1.25}},ImagePadding->{{45,10},{35,10}}],{t,0,2π}]

Note that the solutions are completely free of spurious oscillations around the shock wave. The reason for this is the fact that the KT FV scheme is shock capturing and second order accurate in $\Delta x$. It employs a MUSCL reconstruction. In my experience with the numerical solution of this kind of conservation laws the KT FV is a very good compromise between simplicity and performance. It works shockingly well and can be implemented in only a few lines of code (most of the code above is just setup, NDSolve options and the output wrapper) using mainly list manipulations. The performance in Mathematica (especially when using the CompiledFunction) is also not bad. If you want to see the method flex its "MUSCLs" have a look into the examples studied in the paper or on wikipedia.


text:
Q: Scaling a point cloud of object and centering it over original object ensuring they do not intersect I have a rabbit point cloud - can be any object though.
I want to get the larger rabbit directly over the smaller one. Think of a matryoshka dol with different layers. The problem is getting the outer layer to fit perfect around the inner layer . The main body might not overlap but the ears do.
Here is my code:
import numpy as np
#IMPORT THE OBJECT POINT CLOUD
c= np.genfromtxt(str('rabbitsmall') + '.txt',autostrip=True)

#Determine the x centre of the original object
xmax = np.amax(c[:,0])
xmin = np.amin(c[:,0])
tx = xmin+(xmax-xmin)/4

#Determine the y centre of the original object
ymax = np.amax(c[:,1])
ymin = np.amin(c[:,1])
ty =ymin+(ymax-ymin)/4

#Determine the z centre of the original object
zmax = np.amax(c[:,2])
zmin = np.amin(c[:,2])
tz = zmin+(zmax-zmin)/2

#CREATE A LARGER VERSION OF THE OBJECT
C = np.zeros((len(c),3))

for i in range(0,len(c)):
               C[i][0]= 1.2*c[i][0]
               C[i][1]= 1.2*c[i][1]
               C[i][2]= 1.2*c[i][2]

#Determine the x centre of the larger object
Xmax = np.amax(C[:,0])
Xmin = np.amin(C[:,0])
TX = Xmin+(Xmax-Xmin)/4

#Determine the y centre of the larger object
Ymax = np.amax(C[:,1])
Ymin = np.amin(C[:,1])
TY =Ymin+(Ymax-Ymin)/4

#Determine the z centre of the larger object
Zmax = np.amax(C[:,2])
Zmin = np.amin(C[:,2])
TZ = Zmin+(Zmax-Zmin)/2

#TRANSLATE THE LARGER OBJECT TO BE OVER THE SMALLER OBJECT. IE THE CENTRES ARE AT THE SAME PLACE
for i in range(0,len(c)):
               C[i][0]= C[i][0]-(TX-tx)
               C[i][1]= C[i][1]-(TY-ty)
               C[i][2]= C[i][2]-(TZ-tz)

np.savetxt('rabbitlarger.txt',C)

A: You don't want to scale it, you want to offset or shell it.
Unfortunately, shelling or offsetting is a little bit trickier than a simple scale.
If I were to try to do it properly, I would first create a Delaunay triangulation of the point cloud, compute the normal for each point using the triangulation (average of adjacent face normals) and then offset each point a certain distance along its normal.
This would probably be good enough for your needs.  If you want something more robust (for example, that can handle when shells cause small holes to completely close up) then I'd suggest something like a distance field that generates a mesh using marching cubes at a certain offset distance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: For $k,m\in\Bbb Z$ show that $m! \mid (k+1)...(k+m)$ how to prove that $m!$ divides product of $m$ consecutive number .
in other hand :
if we have :$k+1,...,k+m$ then $m! | (k+1)...(k+m)$  $(k,m \in \Bbb Z)$

A: Hint: The number $\displaystyle \frac{(k+1)\cdots(k+m)}{m!}$ counts something :)

A: Hint:
Consider the binomial coefficient $\binom{k+m}{m}$.
Good luck!


text:
Q: How to Mock an @Inject Interface I have this Service Interface
public interface ABC {
    public String getAbc();
}

And I have this controller that uses this Service
public class Do {
    @Inject ABC abc;

    public String doAbc() {
       String a = abc.getAbc();
    }
}

In my Unit test, I want to be able to mock out this ABC and Not have to provide an actual implementation. Here is what works:
public class TestDo {
   @Mock
   private Do do;

   @Mock
   private ABC abc;

   @Before
   public void init() {
       MockitoAnnotations.initMocks(this);
       do.abc = abc;
   }

   @Test
   public void testDo() {
       when(do.doAbc()).thenCallRealMethod();
       do.doAbc();
       assertSomething...
   }
}

But what I do not want to do is do.abc = abc;, from all my searches, in order to do @InjectMock, I need to provide a concrete class. Is there a way for me to use the interface but yet able to Inject the mocked interface into do without the need to exposed my ABC inject in Do Class? I want to make ABC a private variable, and still able to inject an interface through Mockito.

A: The example you gave is a perfect case for constructor injection: You can make your dependency private (and even final, which is always preferable when practical) and still build an instance without needing an injection framework:
public class Do {
    private final ABC abc;

    @Inject
    public Do(final ABC abc) {
        this.abc = abc;
    }

    public String doAbc() {
       String a = abc.getAbc();
    }
}

A: public interface ABC {
    public String getAbc();
}

public class Do {

    @Inject
    ABC abc;

    public String doAbc() {
        System.out.println("Injected abc is " + (abc == null ? "null" : "not null"));
        return abc.getAbc();
    }

}

public class TestDo {
    @Mock
    private ABC abc;

    @InjectMocks
    private Do ddo;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void simpleTest() {
        System.out.println(ddo.doAbc());
    }

}

output is:
Injected abc is not null
null


text:
Q: Why was Sisko promoted to captain? In DS9 "Adversary" Sisko is promoted to Captain.

*

*Why was he promoted?

*Doesn't he need a ship to be a captain?

*Is he now the Captain of the Defiant?

As a side note, wouldn't a Captain or higher level officer be present to present him with his pen and give him his new rank?

A: As a military man, I'd like to give some military feedback on rank vs position.
A Captain in Starfleet would be the same as a Captain in the Navy or a Colonel in the other branches. I have seen a Brigadier General take over Division with the expectation that he would be promoted to Major General during his command. The same for a Lieutenant Colonel that took over a Brigade, becoming a full Colonel.
With that being said, Deep Space 9 is more like having command of an outpost or a NATO base somewhere, and there really isn't a rank protocol for that.
Most likely, Commander Sisko was probably assigned to command DS9 because he was a competent leader and a Field Grade officer with both diplomatic and combat experience. His promotion was most likely due to: excellence of service, causing promotion over his peers; plain old fashioned time in service/time in grade (rank); or a combination of the two.
Commanding the Defiant wouldn't have had a direct impact on his promotion, since he was already the commanding officer of DS9 and the Defiant was assigned to DS9. In fact, he probably would have never actually commanded the ship from the bridge. As DS9 senior commander, he would have probably stayed at the Command Center, as a unit commander would stay at the TOC (tactical operations center), and play chess.

A: You are confusing the title of captain with the rank of Captain.  The difference is referenced in the opening paragraph of the Memory Alpha article Captain:

Captain is a military rank, the equivalent of which was used by the service organizations of many civilizations. The title of captain was often used by vessel commanders and, as a naval rank, in many Earth navies and Starfleet, was above commander. As an infantry rank, captains ranked subordinate to a major and above a first lieutenant. The abbreviation for captain was capt.

While that can be one and the same (especially in the Star Trek universe), the title of captain is given to the commanding officer of a vessel, whereas the rank is given to an individual who was promoted from the previous rank (in Starfleet, it would be a promotion from Commander, as Sisko was).
For example, in Star Trek V: The Final Frontier and Star Trek VI: The Undiscovered Country, Captain Kirk held the rank of Captain and was also given the title of captain as commanding officer of the USS Enterprise. At the same time, Captain Spock was not captain of the ship (despite having the rank of Captain), but held the position of First Officer.  Additionally, as user16696 reminded me, Scotty also held the rank of Captain by the time of the last movies.
Similarly, in Star Trek: The Motion Picture, Admiral Kirk was given command of the USS Enterprise so was addressed as "captain" throughout the movie because he was given that title as the commanding officer of the Enterprise.
The Defiant itself also illustrates this difference, although the distinction was not openly addressed until later in the series.  When he brought the Defiant back to DS9, Sisko still held the rank of Commander, but when he was in command of the Defiant, he technically held the position of captain (although no one addressed him as such). Then, early in Season 6 of DS9 ("Behind the Lines"), Lt Commander Dax was assigned as the commanding officer of the Defiant, so was given the title of captain, and she was actually referred to as "captain" by the crew while she was in command.  In fact, there is a dialog between O'Brien and Cadet Nog about this exact situation:

O'Brien: "It's an old naval tradition. Whoever's in command of a ship, regardless of rank, is referred to as 'captain'."
Nog: "You mean if I had to take command, I would be called 'captain,' too?"
O'Brien: "Cadet, by the time you took command, there'd be nobody left to call you anything."

So to address your question more directly, the reason Sisko was promoted to Captain was because he earned the increase in rank through his service to Starfleet and the Federation.  It is not related to the Defiant at all, simply because he already held the title of captain every time he commanded the ship.

A: The best reason I can think is that he had proven himself, and that he'd resolved his issues with Starfleet and his career after the horrific events of the Borg invasion.
His tiff with Picard over the deaths caused at Wolf 359 and the death of Jennifer gave credence to the idea of him having problems with the chain of command.
That being said, by the end of season 3 he had pulled himself together, run the station well, developed a strong relationship with the Bajorans and discovered the wormhole, amongst many other achievements.
Not to mention at the beginning of season 1, DS9 was a posting at the end of Federation territory. It was considered a challenge a but non-essential posting, thus only a commander level candidate was needed.
But by the end of season 3, the Dominion are starting to show their colour, and the importance of DS9 as a stop-off point for the Gamma quadrant and a defensible point against the Dominion advance was becoming evident.
That kinda covers the 'Why' part.
As for doesn't he need a ship, no he doesn't. Scotty and Spock were both Captains under the command of Captain Kirk. Further, as Star Trek Online is quite often considered canon (given credence by the Trek reboot movie and the writers of Star Trek), Starbase 82 is commanded by Captain Ogen.
Finally, technically yes, but he is not the only one to command the Defiant. It is a station resource like the runabouts (which each have their own names too).


text:
Q: IntelliJ Idea: Where are installed the plugins and configuration settings in Mac? I installed for Mac (10.11) and Windows 10

*

*ideaIC-2020.2.3
For both, for the first time about their startup process, I selected and configured the custom plugins, such as Gradle, Git Github etc... Then I imported some projects based in Gradle such as spring-framework and spring-integration.
About Gradle was specified its settings about:

*

*Gradle custom home directory i.e: 6.7 (therefore there is no a wrapper)

Each Project share a common and custom repository.
Well, due a problem:

*

*I deleted and reinstalled/unpacked the IDE.

*The 'projects' were imported again (deleted the original directory and re-created that directory and copied/pasted there again the project) and I did realise the settings remains in the IDE.

Goal
In the re-install process I want see again the dialog where I was able to select the custom plugins at the beginning.
In Windows 10 I was able to find within the hidden AppData directory twice the JetBrains directory in two different directories (Local and Roaming), If I delete both directories. I can accomplish my goal
In MacOS I tried to find something like .jetbrains .idea or .intellij and nothing.
Question
Where are located the configurations settings in Mac?
Note: I am a STS/Eclipse user, so I am starting to play with this IDE. I watched some videos about to learn use this IDE, but I have this situation. In STS/Eclipse is enough delete the workspace directory that contains the .metadata hidden directory and done.

A: Check the Default IDE directories section of the IntelliJ IDEA WebHelp.
There is also the File | Manage Settings | Restore Default Settings... action which will make a back-up copy of your current IDE settings and reset them. So upon restart you will start with defaults.


text:
Q: Aligning pictures using CSS I am trying to make 3 different icons in a webpage align with some text at the bottom, it's a simple webpage for a school assesment but I am stuck at this part:
[]
So I want to put that pencil in the center top and then another icon at the top right side, but I am struggling as it goes to the bottom and doesn't go up. Here's my code:
HTML:

Ferrari's 458 Spider official 0-100 km/h (62 mph) acceleration is 2.9-3.0 seconds, while top speed is 325 km/h (202 mph). It has fuel consumption in combined cycle (ECE+EUDC) of 13.3 L/100 km (21.2 mpg-imp; 17.7 mpg-US) while producing 307g/km of CO2.

Bla bla bla bla bla bla

CSS:
.speed {
    width: 52px;
    height: 55px;
    padding: 15px 0px 10px 190px;;
    display: inline;
}

.pspeed {
    padding: 0px 0px 0px 30px;
    width: 28%;
    text-align: justify;
    margin: 0;
}

.design {
    width: 48px;
    height: 48px;
    padding: 0px 0px 0px 500px;
    position: absolute;
    float: left;
    display: inline;

}

.pdesign {
    padding: 0px 0px 0px 400px;
    width: 28%;
    text-align: center;
    margin: 0;
}

Thank for helping guys!
Fiddle https://jsfiddle.net/dfg4qLfe/
https://jsfiddle.net/dfg4qLfe/embedded/result/

A: Avoid defining different css classes for a very same properties, for example, if you do have certain class for your p tag in your first div, you don't need to define another css class for the second p tag that you have in your next div (if you want both to resemble to each other).
I've manipulated your code, made it cleaner, the CSS Trick in order to have contents aligned in center is this:
.design {
display: block;
margin-left: auto;
margin-right: auto;
}

Checkout the code in here:
Centered

A:
I want to put that pencil in the center top and then another icon at
  the top right side, but I am struggling as it goes to the bottom and
  doesn't go up.

Remove float and modify display property, so image can be displayed in separate line:
.design {
     float: none;
     display: block;
}

Anyway posting JSFiddle would me show you how to do this, consider it next time.
FYI, Twitter-Bootstrap framework and its grid layout would help you a lot, google it.


text:
Q: Estimation of parameter uncertainty via $K$-fold cross-validation Goal: Estimate parameter uncertainty for a given model and dataset.
Normally, I would compute the posterior of the parameters (e.g., via MCMC).
However, suppose I only have access to maximum-likelihood estimates (MLE).
Another standard method is to compute the Hessian at the MLE (essentially, using Laplace approximation of the posterior). However, suppose that computing the Hessian is not feasible.
What I do have is the MLE for different training folds of a $K$-fold cross-validation. Crucially, the MLE will differ across training folds.
Is there a known way (under some assumptions, I guess) that links the variability of these MLEs to the posterior in the full dataset? I haven't done the math yet, but it seems to me that there should be a connection - for example, if we assume that the likelihood function is multivariate normal in each of the $K$ subsamples.
(Note that I am not talking about estimating variability/uncertainty in the test error.)


text:
Q: How do I compile pygame on android tablet? I have tried compiling pygame for Android on a PC in both Linux and Windows and its successful but If I try on Android Tablet ,Qpython return error:

No module called pygame.

While Python for Android in SL4A r5 pygame script returns:

Object has no attribute 'USEREVENT'

What is the cause?

A: Pygame is a SDL wrapper. I doubted that it is available for the android system, since I never heard of SDL for android.
After a quick search I have found the website of the pygame subset for android which looks like something you are looking for.
The tutorial seems to be complete, so I would suggest looking into this.


text:
Q: Proving if triangle with sides $a^n,b^n,c^n$ exists for all $n\in N$ then $a=b$ or $a=b=c$ Given $a\ge b\ge c\ge0$ and number $n\in N$
If there exists a triangle with sides $a^n,b^n,c^n \,\,\,\forall n \in N$ then prove that $a=b$ or $a=b=c$ that is triangle is isosceles.
I vaguely have the idea that since $a^n$ follows exponential growth over $n$, $a^n$ grows faster than $b^n+c^n$ iff $a>b$
However, I dont know how to prove it rigoursly. I tried differentiating but couldn't produce an inequality.
Any hints appreciated.

A: Suppose $a\gt b\ge c$ and put $a=b+d$ with $d\gt 0$
Now for $n\ge 2$ we have $(b+d)^n\gt b^n+ndb^{n-1}$ and if $n\gt \frac cd$ then $$a^n=(b+d)^n\gt b^n+ndb^{n-1}\gt b^n+c^n$$
So we cannot have $a\gt b\ge c$ and we must have $a=b$


text:
Q: Android Change Location Provider not working I've got an App that manages its location manager and location listener in a service.
My location listener is also a new service.
When some parameters match on a location update or a timer has matched, I change the location provider from gps to passive or from passive to gps.
From passive to gps works fine but from gps to passive does not.
This is my code that changes the providers
public void changeGPSProvider(String provider) {
    Log.i("ced", "Change Provider: " + provider);
    if(provider.equals(LocationManager.GPS_PROVIDER) && this.locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        this.locationManager.requestLocationUpdates(provider, 5, 1, this.locationListener);
    } else {
        this.locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 5, 1, this.locationListener);
    }
}

Console prints:

02-05 11:05:45.063: I/GCoreUlr(1049): Successfully inserted location
  02-05 11:05:45.063: I/GCoreUlr(1049): Not calling
  LocationReportingService, hasMoved: false, elapsed millis: 978046,
  request: Phone 02-05 11:05:46.865: I/ced(13235): Change Provider:
  passive

Do you have any idea why? I just see that GPS signal is always working on my device.
Thank you.


text:
Q: Laravel Session Destroy implementation Another newb queestion here
How to apply session timeout in laravel? My app have this instance that when a user logs out. That previous route/s should not be loaded but my app loads it. how to implement in laravel that session destroy in PHP? Any ideas?

A: In routes/web.php add your protected routes in a middleware group so they won't be accessible when logged out.
Route::group(['middleware' => 'auth'], function() {
    Route::get('profile', 'UserController@profile');
});

Then /profile will require users to be logged in. As well as any other routes in that group.
Learn more about sessions here: https://laravel.com/docs/5.4/session
Update
I think I've got what you mean. After doing Auth::logout(); do
return redirect()->back();

What will happen is the browser will try to redirect back to a 'protected' page and the protected page will kick them to the login page. WHen they click on 'back' on the browser, it will still display the login page.


text:
Q: Adding a legend to ggplot when using stat_function I'm trying to add a legend to ggplot to differentiate between a simulated normal distribution and a generated one. Below is my code
set.seed(1)
lambda = .2
n = 40
sim = 10000
means = replicate(sim, expr = mean(rexp(n,lambda)))
ggplot(data.frame(means), aes(x=means)) +
           geom_density() +
           stat_function(fun = dnorm, color = "blue",
                         arg = list(mean = 1/lambda, sd=sqrt(lambda^-2/n))) +
           scale_colour_manual("Legend title", values = c("red", "blue"))

I tried using scale_colour_manual as given another stackoverflow answer but I can't get a legend to show up.
Reference answer
Using legend with stat_function in ggplot2

A: Try:
set.seed(1)
lambda = .2
n = 40
sim = 10000
newvar = rnorm(sim, mean = 1/lambda, sd=sqrt(lambda^-2/n) )
means = replicate(sim, expr = mean(rexp(n,lambda)))
ddf = data.frame(means, newvar)
mm = melt(ddf)
ggplot(mm) +geom_density( aes(value, group=variable, color=variable) )

A: In order to get a legend in ggplot2 you need to map a color variable in the aesthetics:
ggplot(data.frame(means), aes(x = means)) +
  geom_density(aes(color = "a")) +
  stat_function(fun = dnorm, aes(color = "b"),
                arg = list(mean = 1/lambda, sd = sqrt(lambda^-2/n))) +
  scale_colour_manual("Legend title", values = c("a" ="red","b" = "blue"))


text:
Q: ORA-29273: HTTP request failed ORA-06512: at "SYS.UTL_HTTP", line 1130 ORA-29270: too many open HTTP requests Hi I have the below procedure which calls a URL and posts JSON data before inserting or updating the table, it was working earlier.
create or replace FUNCTION post_vacant_list
(p_id IN VARCHAR2)
RETURN clob
IS
    XML CLOB;
    v_data_post CLOB;
    resp utl_http.resp;
    req  utl_http.req;
    v_txt CLOB;
    url varchar2(200);
BEGIN
    url := '10.54.8.210:9200/temp/20';(http)
    xml := JSON_UTIL_PKG.REF_CURSOR_TO_JSON(get_employees(p_id));
    req  := UTL_HTTP.begin_request (url,'POST','HTTP/1.1');
    utl_http.set_header(req, 'Content-Type', 'application/x-www-form-urlencoded');
    utl_http.set_header(req, 'Content-Length', length(xml));
    v_data_post :=xml;
    utl_http.write_text(req, v_data_post);
    resp := UTL_HTTP.get_response(req);
    utl_http.read_text(resp,v_txt);
    utl_http.end_response(resp);
    UTL_HTTP.end_request (req);
    dbms_output.put_line('v_txt'|| v_txt);

 exception

 WHEN UTL_HTTP.TOO_MANY_REQUESTS THEN
  UTL_HTTP.END_RESPONSE(resp);
    when others then
   UTL_TCP.Close_All_Connections;
  RETURN sqlerrm;

    end;

However, now that I get the below error while trying to check for a different set of data (i.e., calling it from a package as above )
ORA-29273: HTTP request failed
ORA-06512: at "SYS.UTL_HTTP", line 1130
ORA-29270: too many open HTTP requests

Can you please help me with the above issue? How do I end the http connection ?
I have tried to add End_response and End_request to my procedure but looks like the issue is still persistent.


text:
Q: How can I know when QProcess wants to read input? I'm implementing a compiler in my Compilers class, I'm using Qt & C++.
After I have generated the machine code from the source code, I'm executing the virtual machine that will execute the code.
I'm facing a problem here, I'm using readyRead() signal to get output from the virtual machine, but how can I know that the virtual machine wants to read data from the user?
I wanna show the user an input dialog each time the machine asks for input.

A: Actually input stream of the process is designed in the way it's not necessary to be real user input. For example if you are redirecting file to the input of your application you have nobody to ask for next portion of input. In this case when you call std::cin >> a there are no signal generated by application or operation system and QProcess doesn't have any way to know that child application is waiting for input.
My suggestion is to use some of simple IPC like anonymous pipes to notify parent process about such events. If it's possible you can use use some specific markup in child process standard output to send such notifications.
If virtual machine you are running is third party application then I think parsing its output searching something informing user that some input is required is the only option.


text:
Q: node.js: writing test cases for social networking like APIs I'm developing APIs for social networking web application for learning perspective. When I started to write test cases I stuck around how to organize/write test cases.I'm initially proceeding like this:
First setup global data base initialization:
I need some users' auth tokens to test my routes so I decide to set up these information at global context. Also there are other information that also need to setup at global context so I'm setting that too.
Then for each route:
I start to write test cases and thought that I would write test cases in
such a way that each route test cases would be independent to each other.
and after completing all test suites:
I thought that I would clean up my data base.

The problems with this approach I'm facing are:
Say I want to test four routes named /users , /users/:id/my_invites , /send_invites, /response_invites. And further suppose I'm only interested in writing test cases for GET request and response for /users , /users/:id/invites and POSTing data in the case of others.
/send_invites, /response_invites definitely trigger some actions on the server side that modifies the data base state.
As we see that these routes effect the state of other routes' data say one user sends invites to another user and gets response true/false, so for that user his request was successful but how to ensure that another user actually received the invitation if we don't checking his received invitation documents(i.e through another route) in the first route test cases. Means /send_invites effects the  /users/:id/my_invites .

because these routes are dependent on each others
So The questions I want to ask are:

how to write test cases for these routes so that each route would be independent ?
I tried with three dummy testing users in the global context and trying all sort of combinations for them in all test suites.My test suit presently deals with more than one routes to check 1 route true functionality.
Can anyone suggest me better solution for writing test cases for the above mentioned scenarios?

May be my question is too long or not clear. Please let me know and help me if you can.

A: My opinion:
First the bases EACH test case should have a fresh new state. That means that before you check one scenario, you want to flush your database and insert your new data prepared to test that case scenario. You can use a real database o mock one with data in-memory or however you prefer.
Second, each endpoint potentially affects a lot of tables in your database. So it's perfectly normal to check the state of your data, independently of the tables to check that the information is correct.
And well mocha and other test frameworks have functions that help you to do that. Like beforeEach and afterEach to set up and tear down your data before each test case.


text:
Q: javascript new date get time cant compare them In my back-end, I update user last activity with:
{ last_active: new Date().getTime() }

And on front-end, I did this:
const statusexpire = props.last_active + 1000 * 60;
const currenttime = new Date().getTime();

useEffect(() => {
  if (currenttime > statusexpire) {
    socket.emit('deletelogged', props.id);
    console.log('deleted' + props.id)
  }
}, [currenttime, props.id]);

But it looks like there's something wrong done, I tried several examples but didn't solve this.
Updating log for console.log(currenttime, statusexpire) just to see output:
1616162621335 "161616127040960000"
UserItem.js:40 1616162621338 "161616262117760000"
UserItem.js:40 1616162621345 "161616127040960000"
UserItem.js:40 1616162621346 "161616262117760000"
UserItem.js:40 1616162621398 "161616127040960000"
UserItem.js:40 1616162621400 "161616262117760000"
UserItem.js:40 1616162621410 "161616127040960000"
UserItem.js:40 1616162621416 "161616262117760000"
UserItem.js:40 1616162621425 "161616127040960000"
UserItem.js:40 1616162621427 "161616262117760000"
UserItem.js:40 1616162621435 "161616127040960000"
UserItem.js:40 1616162621440 "161616262117760000"
UserItem.js:40 1616162621447 "161616127040960000"
UserItem.js:40 1616162621449 "161616262117760000"
UserItem.js:40 1616162621456 "161616127040960000"
UserItem.js:40 1616162621460 "161616262117760000"
UserItem.js:40 1616162621466 "161616127040960000"
UserItem.js:40 1616162621468 "161616262117760000"
UserItem.js:40 1616162621482 "161616127040960000"
UserItem.js:40 1616162621491 "161616262117760000"
UserItem.js:40 1616162621497 "161616127040960000"
UserItem.js:40 1616162621502 "161616262117760000"
UserItem.js:40 1616162621513 "161616127040960000"
UserItem.js:40 1616162621519 "161616262117760000"
UserItem.js:40 1616162621527 "161616127040960000"
UserItem.js:40 1616162621528 "161616262117760000"
UserItem.js:40 1616162621535 "161616127040960000"
UserItem.js:40 1616162621541 "161616262117760000"
UserItem.js:40 1616162621549 "161616127040960000"

A: Seems props.last_active is String.
How about trying
const statusexpire = parseInt(props.last_active) + 1000 * 60;

A: Problem is connected to the fact that props.last_active is not a number but a string so props.last_active + 1000 * 60 returns props.last_active concatenated with 1000 * 60.
To solve it's just necessary to convert props.last_active into an integer before sum it to 1000 * 60:
const statusexpire = parseInt(props.last_active) + 1000 * 60;


text:
Q: How do I implement Search Functionality in a website? I want to implement search functionality for a website (assume it is similar to SO). I don't want to use Google search of stuff like that.
My question is:
How do I implement this?
There are two methods I am aware of:

*

*Search all the databases in the application when the user gives his query.

*Index all the data I have and store it somewhere else and query from there (like what Google does).

Can anyone tell me which way to go? What are the pros and cons?
Better, are there any better ways to do this?

A: Use lucene,
http://lucene.apache.org/java/docs/

Apache Lucene is a high-performance, full-featured text search engine library written entirely in Java. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform.

It is available in java and .net. It is also in available in php in the form of a zend framework module.
Lucene does what you wanted(indexing of the searched items), you have to keep track of a lucene index but it is much better than doing a database search in terms of performance. BTW, SO search is powered by lucene. :D

A: You might want to have a look at xapian and the omega front end. It's essentially a toolkit on which you can build search functionality.

A: It depends on how comprehensive your web site is and how much you want to do yourself.
If you are running a a small website without further possibilities to add a custom search, let google do the work (maybe add a sitemap) and use the google custom search.
If you run a medium site with an sql engine use the search features of your sql engine.
If you run some heavier software stack like J2EE or .Net use Lucene, a great, powerful search engine or its  .Net clone lucene.Net
If you want to abstract your search from your application and be able to query it in a language neutral way with XML/HTTP and JSON APIs, have a look at solr. Solr runs lucene in the background, but adds a nice web interface to it.

A: The best way to approach this will depend on how you construct your pages.
If they're frequently composed from a lot of different records (as I imagine stack overflow pages are), the indexing approach is likely to give better results unless you put a lot of work into effectively reconstructing the pages on the database side.
The disadvantage you have with the indexing approach is the turn around time. There are workarounds (like the Google's sitemap stuff), but they're also complex to get right.
If you go with database path, also be aware that modern search engine systems function much better if they have link data to process, so finding a system which can understand links between 'pages' in the database will have a positive effect.

A: If you are on Microsoft plattform you could use the Indexing service. This integrates very easliy with IIS websites.
It has all the basic features like full text search, ranking, exlcude and include certain files types and you can add your own meta information as well via meta tags in the html pages.
Do a google and you'll find tons!

A: This is somewhat orthogonal to your question, but I highly recommend the idea of a RESTful search.  That is, to perform a search that has never been performed, the website POSTs a query to /searches/.  To re-run a search, the website GETs /searches/{some id}
There are some good documents to be found regarding this, for example here.
(That said, I like indexing where possible, though it is an optimization, and thus can be premature.)

A: If you application uses the Java EE stack and you are using Hibernate you can use the Compass Framework maintain a searchable index of your database. The Compass Framework uses Lucene under the hood.
The only catch is that you cannot replicate your search index. So you need to use a clustered database to hold the index tables or use the newer grid based index storage mechanisms that have been added to the Compass Framework 2.x.


text: Q: How to make Jtable show only certain number of rows? I have 1000 rows to sort in Jtable. After sorting , I only care about first 50 rows and don't want to show other rows. Other questions' answer suggest using Model's setRowCount to limit the count,but doing so will unsort the table and I will never been able to sort by other condition using the whole dataset.


text:
Q: Show that $M_n = \sum_{i=1}^n \alpha_k(X_k -X_{k-1})$ is a square integrable martingale w.r.t. $\{F_n, \ n\in \mathbb{N}\}$. $\textbf{question}$
Let $\{F_n, \ n\in \mathbb{N}\}$ be a filtration and $\{X_n, \ n\in \mathbb{N}\}$ a square integrable martingale w.r.t. $\{F_n, \ n\in \mathbb{N}\}$, with $X_0 = 0$ , and such additionally there exists $C \in (0,\infty)$ such that for all $n \in\mathbb{N}$:
$E((X_n - X_{n-1})^2) \leq C$
Additionally, $\{\alpha_k, \ k \in \mathbb{N}\}$ denotes a sequence of real numbers.
Show that $M_n = \sum_{i=1}^n \alpha_k(X_k -X_{k-1})$ is a square integrable martingale w.r.t. $\{F_n, \ n\in \mathbb{N}\}$.
$\textbf{problem}$
I don't understand how to show $M_n$ is a square integrable martingale $\textbf{with respect to}$ $\{F_n, \ n\in \mathbb{N}\}$.
Do I have to show that $E(M_n^2|F_{n-1})=M_{n-1}^2$ in which case I'll be fine.
Or do I have to show:
$sup_{n \geq 0}E(M_n^2)<\infty$
if so can I write:
$sup_{n \geq 0}E[(\sum_{i=1}^n \alpha_k(X_k -X_{k-1}))^2] \leq sup_{n \geq 0}E[(\sum_{i=1}^n \alpha_k^2(X_k -X_{k-1})^2]\leq M sup_{n \geq 0}E[(\sum_{i=1}^n(X_k -X_{k-1})^2]\leq ME[m(X_m -X_{m-1})^2]\leq MmC\leq \infty$

A: For a process $\{Y_n\}_{n\in\mathcal{N}}$ to be a martingale wrt to a filtration $\mathcal{F}=\{\mathcal{F}_n\}_{n\in\mathcal{N}}$ you have to show that :

*

*$Y_n$ is adapted to $\mathcal{F}$

*$\mathbb{E}[|Y_n|]$ exists for all $n$

*$\mathbb{E}[Y_n|\mathcal{F}_{n-1}] = Y_{n-1}$
So you have to show both basically to answer you question. The inequality shows that your process is $L^1$ for all $n$. The equality that it is a martingale.

Please do not ignore the first bullet point which justify the fact that you can write the left term of my third bullet point.
EDIT:
Sorry I misread the question and realize that only after struggling to prove Bullet 3.
What you have to show is that $\{M_n\}$ is a martingale and justify that it belongs to $L^2$.
Appendix to show integrability of $Mn^2$:
The two following propositions are not equivalent :

*

*$\sup_n \mathbb{E}[M_n^2] < \infty$

*$\mathbb{E}[M_n^2] < \infty,$ $\forall n \in \mathbb{N}$
The first is more restrictive and tells you that as $n$ goes larger, the quantity remain finite which is equivalent to saying that $\lim_{n\rightarrow\infty}\mathbb{E}[M_n^2] < \infty$
The second only tells you that the process is $L^1$ for all integers. So $1 \implies 2$ but nothing else.
To prove (2) $\forall n \in \mathbb{N}$:
$$
\mathbb{E}[(\sum_{k=1}^{n} \alpha_k(X_k - X_{k-1}))^2] \leq \sum_{k=1}^n \alpha_k^2 \cdot \mathbb{E}[\sum_{k=1}^n (X_k - X_{k-1})^2]
$$
From this I let you continue.


text:
Q: Google Colab RAM allocation iam new to google colab and have recently started using it.
Whenever i start colab session iam allocated with some RAM, which is very less out of available limit.(Please see attached image)
Could anyone suggest how to increase this allocated RAM?
enter image description here

A: I believe you're reading it wrong, you are using .72G of the available 12G


text:
Q: Unzipping to a variable I need to process the contents of a zipped file, but I can't change the permissions on the server where my program will be hosted.
This means that I can't download the zip file to the server, so I need to read the contents of the file into a variable without writing it to the file system.
Can I grab the string contents of such variable and get the unzipped contents into a new variable?
So far, I've looked into using the zip php extension, and the pclzip library, but both need to use actual files.
This is what I want to do in pseudo code:
$contentsOfMyZipFile = ZipFileToString();
$myUnzippedContents = libUnzip($contentsOfMyZipFile);

Any ideas?

A: Look at this example.
<?php
$open = zip_open($file);

if (is_numeric($open)) {
    echo "Zip Open Error #: $open";
} else {
while($zip = zip_read($open)) {
    zip_entry_open($zip);
    $text = zip_entry_read($zip , zip_entry_filesize($zip));
    zip_entry_close($zip);
}
print_r($text);
?>

A: I use this in my project:
 function unzip_file( $data ) {
    //save in tmp zip data
    $zipname = "/tmp/file_xxx.zip";

    $handle = fopen($zipname, "w");
    fwrite($handle, $data);
    fclose($handle);

    //then open and read it.
    $open = zip_open($zipname);

    if (is_numeric($open)) {
        echo "Zip Open Error #: $open";
    } else {
        while ($zip = zip_read($open)) {
            zip_entry_open($zip);
            $text = zip_entry_read($zip, zip_entry_filesize($zip));
            zip_entry_close($zip);
        }
    }
    /*delete tmp file and return variable with data(in this case plaintext)*/
    unlink($zipname);
    return $text;
 }

I hope it helps you.


text:
Q: Return type based on optional generic argument I can't transfer the many function overloading examples on SO to my use case:
const createAccessor = <T, >(defaultValue: T) => {

    const value = defaultValue

    function fetch(): T;
    function fetch<TPart>(selector?: (obj: T) => TPart) {
        if (selector)
            return selector(value)

        return value
    }

    return { fetch }
}

const obj = createAccessor({
    part1: { a: 1, b : 2 },
    part2: { name: 'Hans' }
})

// This is how i want to use it:

const fullObject = obj.fetch()              // should return T
const part1 = obj.fetch(o => o.part1)       // should return TPart

(also on ts-playground)
Deleting the first overload allows to compile but the return types are wrong.
What am I missing?

A: The implementation is not one of the public signatures of the function, so only the first overload was showing up.
You have to add the overload for the one returning TPart:
function fetch(): T;
function fetch<TPart>(selector?: (obj: T) => TPart): TPart; // <====
function fetch<TPart>(selector?: (obj: T) => TPart) {
    if (selector)
        return selector(value)

    return value
}

Updated playground
The parts there are as follows:
// First overload signature (part of the public type of the function):
function fetch(): T;
// Second overload signature (also part of the public type of the function):
function fetch<TPart>(selector?: (obj: T) => TPart): TPart;
// Implementation (NOT part of the public type of the function):
function fetch<TPart>(selector?: (obj: T) => TPart) {
    if (selector)
        return selector(value)

    return value
}


text:
Q: Is the ordering of members of a map, seeming to be by addition, reliable? When I create an immutable map with a standard call to Map() or by concatenating the existing maps created that way, in all my tests I get that traversing its members provides them in the order of addition. That's exactly the way I need them to be sorted, but there's not a word in the documentation about the reliability of the ordering of the members of the map.
So I was wondering whether it is safe to expect the standard Map to return its items in the order of addition or I should look for some other implementations and which ones in that case.

A: I don't think it's safe, the order is not preserved starting from 5 elements (Scala 2.9.1):
scala> Map(1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4, 5 -> 5)
res9: scala.collection.immutable.Map[Int,Int] =
  Map(5 -> 5, 1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4)

With bigger maps the order is completely "random", try Map((1 to 100) zip (1 to 100): _*).
Try LinkedHashMap for ordered entries and TreeMap to achieve sorted entries.

A: There is no promise about the order of Map. There is an OrderedMap in scalas collection package. The values in that package are ordered by an implicit Ordering. As quickfix I recommend you to use a list of keys for the ordering of your Map.
var keyOrdering = List[Int]()
var unorderedMap = Map[Int, String]()

unorderedMap += (1 -> "one")
keyOrdering :+= 1

Edit
You could implement your own Ordering and pass it to a SortedMap as well.
Edit #2
A simple example would be the following:
scala> import scala.collection.SortedMap
import scala.collection.SortedMap

scala> implicit object IntOrdering extends Ordering[Int]
     | def compare(a: Int, b: Int) = b - a
     | }
defined module IntOrdering

scala> var sm = SortedMap[Int, String]()
sm: scala.collection.SortedMap[Int,String] = Map()

scala> sm += (1 -> "one")

scala> sm += (2 -> "two")

scala> println(sm)
Map(2 -> two, 1 -> one)

The implicit Ordering is applied to the keys, so IntOrdering might be applied to a SortedMap[Int, Any].
Edit #3
A self ordering DataType like in my comment might look this way:
case class DataType[T](t: T, index: Int)
object DataType{
  private var index = -1
  def apply[T](t: T) = { index += 1 ; new DataType[T](t, index)
}

Now we need to change the Ordering:
implicit object DataTypeOrdering extends Ordering[DataType[_]] {
  def compare(a: DataType[_], b: DataType[_]) = a.index - b.index
}

I hope this is the way you expected my answer.

A: After digging I've found out that there exists an immutable ListMap that behaves exactly as I want it, but according to this table its performance is just awfull. So I wrote a custom immutable implementation that should perform effectively on all operations except removal, where it performs linearly. It does require a bit more memory as it's backed by a standard Map and a Queue, which itself utilizes a List twice, but in the current age it's not an issue, right.
import collection.immutable.Queue

object OrderedMap {
  def apply[A, B](elems: (A, B)*) =
    new OrderedMap(Map(elems: _*), Queue(elems: _*))
}
class OrderedMap[A, B](
  map: Map[A, B] = Map[A, B](),
  protected val queue: Queue[(A, B)] = Queue()
) extends Map[A, B] {
  def get(key: A) =
    map.get(key)
  def iterator =
    queue.iterator
  def +[B1 >: B](kv: (A, B1)) =
    new OrderedMap(
      map + kv,
      queue enqueue kv
    )
  def -(key: A) =
    new OrderedMap(
      map - key,
      queue filter (_._1 != key)
    )
  override def hashCode() =
    queue.hashCode
  override def equals(that: Any) =
    that match {
      case that: OrderedMap[A, B] =>
        queue.equals(that.queue)
      case _ =>
        super.equals(that)
    }
}


text:
Q: Upgraded Amazon EC2 Instance Type, how do I access increased storage? I have an Amazon EC2 Windows 2008 R2 x64 instance that I upgraded from "micro" to "large". I upgraded it by stopping it, then right clicking on the instance in the AWS Management Console and change the instance type. When I booted it up again, it still had only a 30GB HDD, and I could find no unallocated space in the Disk Manager.
Any suggestions would be appreciated!

A: The 30GB you're seeing is the EBS-backed volume that was carried over from your t1.micro instance.
To gain access to the ephemeral disk that comes with the m1.large instance, you need to specify that when you start the instance:
$ ec2-run-instances ami-XXXXXX -k <key> -g <security_group> -b "xvda=ephemeral0" -t m1.large

Keep in mind that this really, truly is ephemeral storage. It will go away, so don't use it for anything other than temporary storage. For anything that matters, use EBS-backed volumes.


text:
Q: Is it "everyone's life" or "everyone's lives"? Which is correct: "everyone's life" or "everyone's lives"?
I know that when the pronoun everyone is used as a subject, it takes singular verb agreement (as in the sentence "Everyone was there"). But this by itself doesn't seem to show that the possessive form "everyone's" always acts like a singular possessive noun.
An example of the reverse situation: when the "singular they" is used as a subject, it takes plural agreement, but the possessive form their can be followed by a singular noun. So the verb agreement that a pronoun takes isn't always the same as the grammatical number of a noun after the possessive forms of the pronoun.

A: Everyone is singular and, therefore, everyone has one life.  Everyone's life is correct.


text:
Q: How do I store data in a json file? For a class project we have to build an online store in 3 parts: html, css and js, the first 2 are done but i'm at a loss about js! We should be able to put the info of one product in a json file, and parse it in html. but tbh i'm not even sure how or where to begin with it, any suggestions are appreciated! Thanks!

A: First you can start by creating your JSON file that has all the information about the store that you want, then you can use JavaScript to read the data in that file. Finally you can use HTML and some binding to parse and show whatever you want. I can help you out if you post some sample code or a jsfiddle.


text:
Q: Proof of Arnold-Liouville's Thm: movement in angular coordinates conditionally periodic I'm reading Arnold's book Mathematical Methods in Classical Mechanics and got stuck on the proof of Liouville's theorem on integrable systems. The proof finishes with Problem 11: Show that the motion on the invariant torus $M_f$ is conditionally periodic.
Unfortunately, I have no idea where to start. Can anyone help me out?
Edit: I think the reasoning is somewhat as follows: The action of the flow of $H$ is linear on $\mathbb{R}^n$ in the $t$-coordinates (but I don't understand yet why). Then we divide out the lattice $\Gamma$ to get a linear action on the torus $T^n \cong \mathbb{R}^n/\Gamma$ in the $\varphi$-coordinates. Now there should be a result that any linear action on a torus is conditionally periodic.

A: By flowing along the Hamiltonian vector fields corresponding to the Poisson commuting functions $f:= (f_1 = H, f_2,\ldots, f_n)$ and restricting attention to a level set $M_f$, we obtain an action of $\Phi:\mathbb{R}^n\times M_f \to M_f$. Let's fix some point $x_0 \in M_f$ and consider the orbit map $\Phi_{x_0}:\mathbb{R}^n \to M_f$ defined by $\Phi_{x_0}(v) = \Phi(v,x_0)$. The stabilizer of this map is a rank $n$ subgroup $\Gamma$ of $\mathbb{R}^n$.
Let $e_1,\ldots, e_n$ be the standard basis of $\mathbb{R}^n$. Note that the flow $\psi^H_t$ corresponding to the Hamiltonian $H$ is given by $\psi^H_t(x)\mapsto \Phi(te_1,x)$.
Now let $v_1,\ldots, v_n$ be a basis for the free abelian group $\Gamma$, and let $A:\mathbb{R}^n\to \mathbb{R}^n$ be the invertible matrix defined by $A e_i = v_i$. The map $\Phi_{x_0}\circ A$ has stabilizer $\mathbb{Z}^n\leq \mathbb{R}^n$ and descends through the quotient to a diffeomorphism $\mathbb{T}^n = \mathbb{R}^n/\mathbb{Z}^n \to M_f$ which defines the circle-valued coordinates $\varphi:=(\varphi^1,\ldots,\varphi^n)$. Since the $\Phi_{x_0}$ is surjective, for any $x \in M_f$ there exists $w \in \mathbb{R}^n$ such that $\Phi_{x_0}(w) =x$. Using this fact and the previous paragraph, we obtain
$$\psi_t^H(x) = \Phi(te_1,x) = \Phi(te_1,\Phi(w,x_0)) = \Phi_{x_0}(te_1 + w) =\Phi_{x}(AA^{-1}(te_1+w)) = [\Phi_{x}\circ A]( tA^{-1}e_1 + A^{-1}w) = [\Phi_{x}\circ A]( \omega t + A^{-1}w),$$
where the vector $\omega:=A^{-1}e_1$. Therefore, $$\dot{\varphi} = \omega$$
as desired.


text:
Q: staff and faculty name and annual salary in descending order In my program did faculty details like name birth date, status.It's just print for faculty.
I got output like this:
John was born on Sun Jan 03 00:00:00 MST 1971: fulltime

Then I want to prints the name and annual salary of each Staff member and Faculty and Salary must be descending order.
I got output like this:
John was born on Sun Jan 03 00:00:00 MST 1971: fulltime
[Barry was born on Tue Jan 02 00:00:00 MST 1973: part-time, Andy was born on Wed Nov 12 00:00:00 MST 1980: full-time,
 Name: Edith  Annual Salary : 7416.666666666666,
 Name: Don  Annual Salary : 5866.666666666667,
 Name: Cathy  Annual Salary : 2900.0]

but i just got staff name and annual salary. I want to print faculty name and annual salary as well.I don't know where Am I wrong?
How can I do that?
Person Class:
public abstract class Person implements Comparable<Person> {
    protected String firstName;
    protected java.util.Date birthdate;

    public Person(String firstName, java.util.Date birthdate) {
        this.firstName = firstName;
        this.birthdate = birthdate;
    }

    public java.util.Date getBirthdate() {
        return birthdate;
    }

    public String getName() {
        return firstName;
    }

    public void setName(String firstName) {
        this.firstName = firstName;
    }

    public void setBirthdate(java.util.Date birthdate) {
        this.birthdate = birthdate;
    }

    public String toString() {
        return " \n" + " Name: " + getName()+ " " + " Annual Salary : " + getSalary();
    }

    public abstract Double getSalary();

    public int compareTo(Person o) {
         Person per =(Person)o;

            if (this.getSalary() > per.getSalary()){
                return -1;
            }else if (this.getSalary() < per.getSalary()){
                return 1;
            }else
                return 0;

  }

}

Faculty class:
public class Faculty extends Person{

    private double monthlySalary;
    private String status;
    public Faculty(String firstName, Date birthdate, double salaryln, String statusln) {
        super(firstName, birthdate);

        this.monthlySalary = salaryln;
        this.status = statusln;
        // TODO Auto-generated constructor stub
    }

@Override

    public Double getSalary() {
        // TODO Auto-generated method stub
        double fsalary = monthlySalary*9.0;
        return fsalary;
    }

    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }

    public double getMonthlySalary() {
        return monthlySalary;
    }

    public void setMonthlySalary(double monthlySalary) {
        this.monthlySalary = monthlySalary;
    }

     public String toString(){
            return getName() + " was born on " + birthdate +  ": " + getStatus();
        }

}

Staff Class:
public class Staff extends Person{

    private double annualSalary;
    private double experience;

    public Staff(String firstName, Date birthdate, double salaryln, double experienceln) {
        super(firstName, birthdate);
        this.annualSalary = salaryln;
        this.experience = experienceln;
        // TODO Auto-generated constructor stub
    }

    @Override
    public Double getSalary() {
        // TODO Auto-generated method stub
        double staffSalary = annualSalary + annualSalary*(30.0-experience)/60.0;
        return staffSalary;
    }

    public double getAnnualSalary() {
        return annualSalary;
    }

    public void setAnnualSalary(double annualSalary) {
        this.annualSalary = annualSalary;
    }

    public double getExperience() {
        return experience;
    }

    public void setExperience(int experience) {
        this.experience = experience;
    }

}

PersonTest Class:
public class PersonTest {

    public static void main(String[] args) throws ParseException {
        // TODO Auto-generated method stub

            String pattern = "MM/dd/yyyy";
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            Date date = format.parse("01/03/1971");
            Faculty faculty = new Faculty("John", date, 2000, "fulltime");
            System.out.println(faculty);

        Person[] ps = new Person[5];

        ps[0] = new Staff("Cathy", format.parse("8/19/1968"), 2000.0, 3.0);
        ps[1] = new Staff("Don", format.parse("4/17/1969"), 4000.0, 2.0);
        ps[2] = new Staff("Edith", format.parse("10/28/1979"), 5000.0, 1.0);
        ps[3] = new Faculty("Andy", format.parse("11/12/1980"), 4000.0, "full-time");
        ps[4] = new Faculty("Barry", format.parse("1/2/1973"), 6000.0, "part-time");

        Arrays.sort(ps);

        System.out.println(Arrays.toString(ps) );
        System.out.println();

    }

}

A: In the Faculty class, you override toString() like so:
// There should be a @Override here.
public String toString(){
    return getName() + " was born on " + birthdate +  ": " + getStatus();
}

This means that when you print the array, which invokes Faculty::toString, it prints what you defined as the String representation of the Faculty object, which is the name with some birth date and status.
If you want to print it using the Person definition, you should stop overriding the toString method and therefore have Faculty default to the superclass's toString method (alternatively, change the name of Faculty::toString to something different) or cast Faculty to Person such that you can access Person::toString and print using that method instead of the overriden version.
Also, if your Person::compareTo is pretty much going to be simple integer comparison, you could just use: return Integer.compare(this.getSalary(), o.getSalary()).
If you find my answer useful, please accept it!


text:
Q: How do I ensure a single Room is created per device, rather than a new instance each time the app launches Perhaps I am missing something because I couldn't find anything about this.  I want to use Android Room to store my data locally on the device.  How do I ensure that it is a single data base, not a new instance each time?  Is it by class name?

A: When you build the Room Database and then access the built database it opens the database (or creates it if it doesn't exist (once unless the App is uninstalled)).
The database itself is a file and is typically stored in the App's data (data/data/the_package/databases), thus the data belongs to the App. The file persists (is effectively permenant).
If your concern is regarding a pre-packaged database (i.e. a database created and typically populated elsewhere (e.g. an SQLite management tool) and is supplied as part of the APK), then the App would copy the database from the APK prior to building/opening it.
As such creating the instance (build followed by access) is in effect opening the file rather than creating a new database everytime.


text:
Q: Can I write Apps in Swift 1 (For iOS 7 and 8) using Xcode 7? Can I write Apps in Swift 1 (For iOS 7 and 8) using Xcode 7? Or will compiled Swift 2 run on iOS 7-9?

A: No, you can not.
Each Version of Xcode includes only one version of the Swift Compiler. Using a newer Xcode Version will force you to adopt the new Swift Syntax.
There is an automatic converter available under Edit -> Convert -> To Latest Swift Syntax.
The iOS Version requirements are not affected by the use of Swift 2 (or Xcode 7). Apps built with Xcode 7 and written in Swift 2 can run on iOS 7 (same conditions/restrictions as before).

A: There will be errors if you attempt to run swift 1 in xcode 7, and yes, swift 2 will run on IOS 7-9


text:
Q: Android->localhost->Java Spring Задача заключается в передаче логина и пароля(Android App) в ,поднятый на Java Spring, localhost,а затем уже забрать из самого Java. Сам я не местный, прошу дать направление поиска.
Код android:
            HttpURLConnection connection = null;
            URL url = new URL("10.0.2.2:8080/home.html");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setConnectTimeout(720000000);
            connection.setReadTimeout(72000000);
            OutputStreamWriter output = new OutputStreamWriter(connection.getOutputStream());
            output.write(json);
            output.flush();
            output.close();
            System.out.println(json);
            //  int HttpResult = connection.getResponseCode();
            connection.disconnect();

код java:
            URL url = new URL("http://10.0.2.2:8080/home.html");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

Вероятно я что то не учёл, с android вообще встретился впервые, со стороны java опыта в таких вещах тоже не густо. Прошу помощи у сообщества)
P.S: Буду искренне рад найти собеседника на данную тему.


text:
Q: How do you search for an embed in discord.js I am attempting to make a simple starboard system on discord.js, and the deleting a message part is stumping me. Currently, if a message gets a star, an embed is created in a starboard channel, and, critically, the footer is the original message's id. I want to make the inverse function (when the star is removed, the embed is deleted) work by finding the embed with that footer and then deleting that embed, but it's not working for some reason. The error I keep getting is "UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined." How do I property define this variable?
  if (reaction.emoji.name === `⭐`) {
    const guild = reaction.message.guild;
    await reaction.fetch();
    const stars = reaction.count;
    if (stars === 0) {
      const embed = guild.messageEmbed.cache.find(embed => embed.footer === reaction.message.id);
      embed.delete
    }
  }
}

A: You have to find the embed from the starboard channel, not from the entire guild.
You can use Channel.messages.fetch and Channel.messages.cache.find to find a specific message. Try this:
if (reaction.emoji.name === `⭐`) {
    const guild = reaction.message.guild;
    await reaction.fetch();
    const stars = reaction.count;
    if (stars === 0) {
      guild.channels.cache.get('starboard-channel-id').messages.fetch().then(fetchedMsgs => {
        fetchedMsgs.find(x => x.embeds[0].footer.text == reaction.message.id).delete();
      })
    }
  }
}


text:
Q: Iterator (Iterate Feature Selection) running loop in undesired path using ArcMap ModelBuilder? I am building a model using Iterate Feature Selection. I want to run the Iterator -> select by location -> Calculate field, and after finishing this loop (#3 in the image below), I will continue to the next process (#4 in the image below).

But when I run the model, it go to the next process until the end, then come to start the next loop, repeatedly.


text:
Q: EmberJS: Auto-Generate Record when no record ID in route I am creating an application which lets applicants apply through a form.  The form must auto-generate a new application if no previous application was passed in.
My router.js file:
Router.map(function () {
    this.route("apply", {path: ":application_id"}, function () {
        /* ... */
    });
});

And my routes/apply.js
export default Ember.Route.extend({
    model: function(params) {
        if (params["application_id"]) {
            console.dir(params.application_id);
            return this.store.find("application", params.application_id);
        }
        else {
            console.dir(params);
            let emptyApplicant = this.store.createRecord("applicant", {isPrimary: true}), emptyApplication = this.store.createRecord("application");
            emptyApplication.set("applicant", emptyApplicant);
            return emptyApplication;
        }
    }
});

But navigating to /apply gives me the following error:

Error while processing route: apply.index Couldn't find record of type 'application' for the id 'apply'. Error: Couldn't find record of type 'application' for the id 'apply'.
    at DS.LSAdapter.DS.Adapter.extend.find

I checked what the params is, and it is apply in this case (I was expecting it to be null, and the url apply/7g2c7 to be 7g2c7).
How can I detect when an application ID is being sent in, and auto-generate a new application otherwise?


text:
Q: Issue when using OVS-DPDK with Intel SR-IOV Virtual Function I'm using OVS-DPDK with Intel X710 NIC. What I do are:

*

*(1) Binding UIO driver for NIC port (e.g igb_uio in case physical function and vfio_pci for virtual function)

*(2) Binding this DPDK port to OVS, called dpdkport

*(3) Add a vhostuser port to OVS

*(4) Add a flow that forwarding PKT from vhostuser to dpdkport

*(5) Run a DPDK Packet Generator (e.g. pktgen or testpmd) to port vhostuser. These packets are forwarded to dpdkport and then be sent to NIC.

Everything is OK with Physical Function NIC Port. But issue appeared when using "Virtual Function - VF".
When using VF, I dumped port information by using ovs-ofctl dump-port. It shows that about all packet are error and can not be sent to NIC.
Error log:
ovs-ofctl dump-ports ovs-br0 dpdk-p0
OFPST_PORT reply (xid=0x4): 1 ports port  "dpdk-p0": rx pkts=0, bytes=0, drop=0, errs=0, frame=?, over=?, crc=? tx pkts=0, bytes=0, drop=0, errs=317971312, coll=?
Do you have any idea about what happened?
P/s: there is a duplicating item in step (3), so I edited it. I also add the report from ovs about error in packet.
Regards
Michael Tang


text:
Q: createCDATASection is undefined when generating XML I'm trying to generate an xml file using PHP, with the the description element being placed on a CDATA.
<?php

$title = "Volvo";
$description = "this is a test description";

$xml = new SimpleXMLElement('<xml/>');
    $track = $xml->addChild('blog');
    $post = $track->addChild('post');
    $post->addChild('title',$title);
    $cdata = createDATASection($description);
    $post->addChild('description',$cdata);

$xml->asXml();
?>

Am I using createDATASection correctly? I have also tried other ways but I am still not getting it.

A: createCDATASection() is a method of the DOMDocument. SimpleXML itself is limited. If you need that much control (like creating specific node types) you will have to use DOM. SimpleXML treats the XML as a tree of just elements. In DOM everything is a node, elements, texts, attributes, comments, ...
In DOM the create and the append are separate. You create an new node (of any type) with the corresponding method of DOMDocument then you append it using the method of the parent node. The append methods will return the node, so you can nest calls.
Here is your example source converted to DOM API calls:
$title = "Volvo";
$description = "this is a test description";

$document = new DOMDocument();
$xml = $document
  ->appendChild($document->createElement('xml'));
$blog = $xml
  ->appendChild($document->createElement('blog'));
$track = $blog
  ->appendChild($document->createElement('track'));
$post = $track
  ->appendChild($document->createElement('post'));
$post
  ->appendChild($document->createElement('title'))
  ->appendChild($document->createTextNode($title));
$post
  ->appendChild($document->createElement('description'))
  ->appendChild($document->createCDATASection($description));

$document->formatOutput = TRUE;
echo $document->saveXml();

Output:
<?xml version="1.0"?>
<xml>
  <blog>
    <track>
      <post>
        <title>Volvo</title>
        <description><![CDATA[this is a test description]]></description>
      </post>
    </track>
  </blog>
</xml>


text:
Q: Matlab Compiler linking errors (64 bit versus 32 bit) I have been using the deploytool in Matlab for the past few months in my 2010b 64bit version of Matlab. I just recently found out that I need to create a 32 bit version of my c shared library.
To do this I follow the same methods I had been using previously (pretty much calling the command mcc -W lib:MYLIB -T link:lib -d 'MYOUTPUTFOLDER' -v 'MFILE1' 'MFILE2') in my 2009b 32 version of Matlab. I keep getting the error LNK1811: cannot open input file LIBRARY.obj. I have tried to find this LIBRARY object file but I cannot seem to find it anywhere.
So far I have checked to ensure all of the correct libraries are available (found at $MATLABROOT$\extern\include\win32), I have made sure all of my paths are correct in the compopts.bat file, and I have used the option -T compile:lib which works fine and creates a dll. This would be great but I need a lib file to use later in mbuild.
My current path forward is to take the compopts from my 64 bit version of Matlab (on a different machine) and compare it with my compopts for the 32 bit. I will post if it makes a difference.

A: To summarize our comments in the question and make it an answer. Here is how I manage to create both x32 and x64 libraries/standalones with mcc.
NB: Maybe there are more elegant solutions to configure deploytool, anyway with brute force I'm sure it works and I can automate global deployment process for my applications ...
Machine setup

*

*Install Matlab x32 and x64 on your machine

*Run Matlab x32 and setup compiler options typing msbuild -setup

*

*This will generate a compopts.bat file in ~user\AppData\Roaming\MathWorks\MATLAB\R2013b (path may differ upon your version)

*Rename this file to compopts.x32.bat (see later)

*Run Matlab x64 and setup compiler options typing msbuild -setup

*

*This will generate a compopts.bat file in ~user\AppData\Roaming\MathWorks\MATLAB\R2013b (!!Overwrites x32!!)

*Rename this file to compopts.x64.bat (To workaround file overwrite)
EDIT Just tested ... In R2014b, Matlab does no longer overwrites same compots.bat file ... it now generates two separate MBUILD_C++_win64.xml and MBUILD_C++_win32.xml files (which is a good thing!).
Compilation in x32
Force your compilation script to point to ~matlabx32\bin\win32\mcc.exe and force mcc.exe to use previously saved compopts.x32.bat file using the -f option. Your command line should be something like:
~matlabx32\bin\win32\mcc.exe -f "compopts.x32.bat"  ... other mcc options ...

Compilation in x64
Force your compilation script to point to ~matlabx64\bin\win64\mcc.exe and force mcc.exe to use previously saved compopts.x64.bat file using the -f option. Your command line should be something like:
~matlabx64\bin\win64\mcc.exe -f "compopts.x64.bat"  ... other mcc options ...


text:
Q: Ubuntu 15.04 not working with Broadcom B4311 I've installed a fresh copy of Xubuntu 15.04 and I can't get my Broadband B4311 Wifi card working.
I had Ubuntu GNOME 14.04, and I solved the problem using the b43 driver, so I'd already done a lot of tweaking, now neither the b43 driver or the Broadcom proprietary driver works.
Is this kernel related? Has anyone had the same problem?

A: Correction:
Actually, the correct file to edit on gedit is /etc/modprobe.d/blacklist-bcm43.conf since this file is for the Broadcom 43xx series wifi chipsets. Don't forget to reboot the PC once these changes are made to take into effect.
So to put it into steps (for some people who don't get what I'm talking about):
Open Terminal by pressing Ctrl+Alt+T
Type
sudo apt-get install firmware-b43-installer
gksudo gedit /etc/modprobe.d/blacklist-bcm43.conf

Comment out (by putting a # at the start of the line) any items with the words bcm43 or bcm43xxx in them. Save the file and close gedit once you're done with these changes.
Reboot the PC.
NOTE: some PCs may require you to activate the wifi card through either a combo key press (FN + F# or an unknown side/front switch) before you can see your wifi networks on the Network Connections.

A: sudo apt-get install firmware-b43-installer
sudo -H gedit /etc/modprobe.d/blacklist-broadcom-wireless.conf

removed the line with b43
sudo update-initramfs -u

Details found here on the help.ubuntu.com wiki


text:
Q: Laravel collection .each() + array_push need help regarding array_push inside .each() method on laravel. I cannot get the container array on this code:
$imagesData = array();
collect($data['images'])->each(function($v, $k) use($imagesData){

    $v['created_at'] = date('Y-m-d H:i:s');
    $v['updated_at'] = date('Y-m-d H:i:s');
    $v['image_id'] = $v['image_id'];
    $v['settings'] = json_encode($v['settings']);

    array_push($imagesData, $v);

});

$result = Images::insert($imagesData, true);

Basically, the code above I want to iterate the data inside .each() and then push it to array container and insert it by batch.
NOTE: when i use foreach there will be no problem, but I need to use .each() instead of foreach.
Thanks

A: Because you want to change the original $imageData, you need to refer to this variable instead of just copying the value of it. This is done by using an ampersand &.
collect($data['images'])->each(function($v, $k) use(&$imagesData){
    // ...
});

A: Using the Collection::map method is a much more readable way to do the same thing:
$imagesData = collect($data['images'])
    ->map(function($item) {

        $item['created_at'] = date('Y-m-d H:i:s');
        $item['updated_at'] = date('Y-m-d H:i:s');
        $item['image_id'] = $item['image_id'];
        $item['settings'] = json_encode($item['settings']);

        return $item;
    })
    ->all();

$result = Images::insert($imagesData, true);

map iterates over the array the same way as each does. The difference is that each does not return anything (so you need to build the new array yourself) while map automatically builds a new collection of the items you return inside the function. After map, you use all to return the results as a plain array.


text:
Q: How to fix error project offline maps used Nutiteq maps SDK I'm a newbie in android. I try a project on the used Nutiteq maps SDK on Github, but I made some errors:

in class MyMapEventListener error UTFGridRasterTileLayer,class CartoDBTorqueActivity error TorqueTileLayer, class CartoDBVectorTileActivity error CartoCSSStyleSet, class OfflineRoutingActivity error NutiteqOnlineRoutingService.

A: From your own comment, I can see you're using Eclipse, however, that is an Android Studio project. The problem could lie there.
Dependencies are downloaded via Gradle, but Eclipse's default is Ant. Have you tried Gradle Eclipse (https://gradle.org/eclipse/) or Android Studio?
Additionally, Nutiteq SDK 3 is old and won't be supported for very long. You should check out the new version, 4.0.0, CartoMobileSDK

*

*Documentation:
https://carto.com/docs/carto-engine/mobile-sdk/getting-started

*Samples: https://github.com/CartoDB/mobile-android-samples


text:
Q: How to hide new item button in toolbar but keep edit So I have a list where I have applied unique permission and user can "Edit" an item but cannot "Add" an item. Normally this should have handled by SharePoint and it shouldn't show "new item" link but keep "edit" button but apparently that's not the case (I guess it's SharePoint being SharePoint).
Once you remove "Add" item permission then the whole line which says "new item or edit this list" becomes hidden. So I was thinking is there a way to only hide "new item"?

A: We can add the style, given below to Content Editor Web Part to achieve the hiding of the add link. But this will still leave "or" in the page. If we need remove "or". We need to use javascript to cover the html code.
 <style>
 #idHomePageNewItem {
 display:none;
 }
 </style>


text:
Q: How can i split a string by dot, comma and newline with removing whitespaces by using regex in javascript? I have string like this:
what, be inclined to, hi . hello
where

I want to split it like this:
["what","be inclined to","hi","hello","where"]

Currently I'm using this regex but It doesn't work like I want:
input_words.val().replace(/^\s*|\s*$/g, '').split(/\n|\s*,|\./);

A: split function alone would be enough. The below regex would split your input according to one or more commas or dots or newline characters along with the preceding or following zero or more spaces.

var s = "what, be inclined to, hi . hello\nwhere";
alert(s.split(/\s*[,\n.]+\s*/))

A: var test ="what, be inclined to, hi . hello\nwhere";
var elements = test.split(/[,\n.\s+]+/) || [];


text:
Q: Swift array does not change even thought using its reference (using inout) when passing it to a function I call a function to get data from REST api and fill array of objects with result data, I use (inout parameter) as mentioned in apple documentation But the array does not change
My code
static func getData(tab : String, inout listItems : [Item], table: UITableView) -> (){
    listItems.removeAll();
    Alamofire.request(.GET, baseURL + currencyAPI, parameters: ["tab":tab]).responseArray { (response: Response<[Item], NSError>) in

        let items = response.result.value
        if let items = items {
            listItems.appendContentsOf(items)
            table.reloadData()
        }
    }
}

and function call
APIManager.getData("syp", listItems: &listItems, table: sypTable)

Update: when I put API request inside viewDidLoad function it works correctly
override func viewDidLoad() {
    super.viewDidLoad()
    //APIManager.getData("syp", listItems: &listItems, table: sypTable)

    Alamofire.request(.GET, baseURL + currencyAPI, parameters: ["tab":"syp"]).responseArray { (response: Response<[Item], NSError>) in

        let items = response.result.value
        if let items = items {
            self.listItems = items
            self.sypTable.reloadData()
        }
    }
}


text:
Q: entity framework update i know how to do updates, inserts and deletes with the entityframework but in this case i don't know what to do.
In this case i have 3 tables: the table A the table B and the table AB which has 2 columns, one is the foreing key of the table A and one is the foreing key of the table B.
The entity framework shows only the tables A and B so how i can update only the content of the table AB?
I've tried to use the references in entity A and entity B but it gives me an exception saying that the entityset AB doesn't have the insert function and the delete function.

A: You try to make a
Public Virtual List<int> Ids

in your "A" and "B" Class to recover all the associations

A: For an insert, you would create a record for Table A, then add the Table B records to the item created that inserts into A. EF will handle the rest.
 var tableA = new TableAtype { Description = "blah", etc.};
 tableA.TableBtype.Add(new TableBtype { Property1 = "foo", Property2 = "bar"};

 yourContext.AddToTableAtype(tableA);
 yourContext.SaveChanges();

A: i'll be more specific using the code of my project as asked by TheGeekYouNeed
    public void ModificaAbilitazioni(int IdGruppoAnagrafica, List<DefAbilitazioni> AbilitazioniList)
    {
        GruppiAnag gruppo = (from g in entities.GruppiAnags
                             where g.IdGruppoAnag == IdGruppoAnagrafica
                             select g).First();

        List<DefAbilitazioni> tutteAbilitazioni = GetTutteAbilitazioni();
        for (int i = 0; i < AbilitazioniList.Count; i++)
        {
            if (tutteAbilitazioni[i].GruppiAnags.Contains(gruppo))
            {
                tutteAbilitazioni[i].GruppiAnags.Remove(gruppo);
            }
        }

        foreach (DefAbilitazioni abilitazione in AbilitazioniList)
        {
            for (int i = 0; i < tutteAbilitazioni.Count; i++)
            {
                if (tutteAbilitazioni[i].IdAbilitazione == abilitazione.IdAbilitazione)
                {
                    tutteAbilitazioni[i].GruppiAnags.Add(gruppo);
                }
            }
        }
        entities.SaveChanges();
    }

ok...here it is
this method should change the privilegies accounts.
First i recover the account using his id, than i recover all the privilegies and if in their reference they have the account recovered, then i remove it from the reference.
This way the account doesn't have any privilegies. Now in the privilegies that i've passed calling the method and in theri reference i put the account. (just a wipe and refill i'm just trying for now...)
i've also di the opposite, wiping the privilegies references in the account and refill them, but in both way won't work, in the first case it says that the third entity (AB) doesn't have the insert function

A: i've resolved the thing, the problem was that i was working with objects not attached to the db, i've tried with the attach like this
        foreach (DefAbilitazioni abilitazione in abilitazioni)
        {
            entities.Attach(abilitazione);
            gruppo.DefAbilitazionis.Add(abilitazione);
        }

but it doesn't work it says that the entitykey is null, maybe if somebody gives me an example of using the attach i'll try to change my code that now is like this
    public void ModificaAbilitazioni(int IdGruppoAnagrafica, List<DefAbilitazioni> AbilitazioniList)
    {
        GruppiAnag gruppo = (from g in entities.GruppiAnags
                             where g.IdGruppoAnag == IdGruppoAnagrafica
                             select g).First();

        IEnumerable<int> idAbilitazioni = from id in AbilitazioniList
                                          select id.IdAbilitazione;

        List<DefAbilitazioni> abilitazioni = (from abilitazione in entities.DefAbilitazionis
                                              where idAbilitazioni.Contains(abilitazione.IdAbilitazione)
                                              select abilitazione).ToList();

        gruppo.DefAbilitazionis.Clear();
        foreach (DefAbilitazioni abilitazione in abilitazioni)
        {
            gruppo.DefAbilitazionis.Add(abilitazione);
        }
        entities.SaveChanges();
    }