Idiomatic way to handle errors with an early return in Rust

Question: I currently have the below code to handle the case where I want to handle an error without propagation or continue the function. The use case for this is a web server controller, where I would prefer to manual handle possible errors - which is why the return type is HttpResponse.
I want to know if there is a way to do this without this unwrap call as in my understanding the compiler should know there is a way to unwrap to a value at this point with no risk of panic.
    // ...

    let result: Result<u8, Error> = func_that_could_error();
    if result.is_err() {
        return HttpResponse::InternalServerError();
    }
    let value: u8 = result.unwrap();

    // ...

Comment: `let value = result.map_err (|_| HttpResponse::InternalServerError())?;`
Comment: or `let value = match result { Err(_) => return HttpResponse::InternalServerError()), Ok (v) => value, };`
Answer: If you can, use ?:
let value = func_that_could_error()?;

Optionally mapping it to your error as @Jmb suggests:
let value = func_that_could_error()
    .map_err(|_| HttpResponse::InternalServerError())?;

Otherwise, use let else:
let Ok(value) = func_that_could_error() else {
    return HttpResponse::InternalServerError();
};

Or, for Rust < 1.65, match:
let value = match func_that_could_error() {
    Err(_) => return HttpResponse::InternalServerError(),
    Ok(v) => v,
};

Comment: Also while `let-else` is still unstable, [guard](https://crates.io/crates/guard) implements it via a macro (with a few limitations) and is quite reliable, and has worked fine (on stable) for  years. Basically wrap the entire thing (except the trailing `;`) in a `guard!()` and you're done.
Comment: Thanks for the options. The `let-else` is ideal but stuck with stable at the moment. Will be following the RFC for sure.
Comment: There's an extra `if` in your `let-else` example.
Comment: Note: you can only use `?` if your function's return type is either `Result` or `Option`.
Comment: @JamesGill Youre welcome. I added `match` alternative.
Comment: Use `ok_or()` for `Option` instead of `Return` ;-)


Jacob Collier "Hideaway" Analysis

Question: can Someone please analyse/explain the chordal part of the lyrics
"Even when I close my eyes ,Darling i'll.... "
in the song 'Hideaway' by Jacob Collier's ?? The chords are as folllows:

Fmaj7/G  Cmaj9  Dmaj9/A  F#m11/C#   Amaj9  Bbm11  Cmaj7-5
Ev   -   en     when     I         close  my     eyes,

C#m11           Eb6add9/G     Bbm7/F     Abmaj9/Eb   Eb9sus
Darling, I will always     stay

C6/G   Cmaj7/G   F#dim/G   C#/G
Wide awake           in my

G     Gadd4  G  Gmaj7
Hideaway
Comment: As you move from one chord to the next, look for (1) common tones, (2) resolutions, and (3) parallel movement (e.g., a set of chord tones that slide up a half step as you move to the next chord). This is how Jacob thinks about his own progressions. He has some great talks on YouTube about how to writes chord progressions.
Answer: This is all about voice leading.
For example, consider the first four chords. (Note: I'm not attempting to transcribe Collier's exact voicings; just to illustrate how the chords can be constructed by basic voice-leading principles.)

Fmaj7/G  Cmaj9  Dmaj9/A  F#m11/C#

E        D      C#       B
C        B      A        A
                         G#
A        G      F#       F#
F        E      E        E
                D        D

G        C      A        C#

One can see how smooth voice-leading can occur, even leaving options to omit notes from certain chords to preserve the total number of voices.
Keep in mind that Collier is not trying to follow standard rules of key relationships, chord relationships, or resolution of dissonances, so an analysis in terms of Roman numeral chords and secondary dominants and such is likely either to be unhelpful or unduly convoluted.
But keep in mind also that chord names as given as descriptive rather than analytical. For example, Fmaj7/G  Cmaj9 is functionally ambiguous, but V13  I9, accurately describes the sound of my above voice-leading example (though not Collier's).

For the record, I don't think the transcription is correct to begin with. For example, the very first chord, to my ear, sounds more like Em7/F.

Jacob Collier "Hideaway" Analysis


An analogy between group actions and group represenations

Question: I was trying to make a 'dictionary' between group action and group representation terms using the $\mathbb{C}[-]$ functor. I immediately found that if the set $Y \subset X$ is invariant under the action of $G$, then the corresponding representation is reducible. This of course means that irreducible represenations cannot be born out of actions that have non-trivial invariant subsets. But then again, the action of $\mathbb{Z}/2^2$ on itself by left shifts is transitive, but the corresponding representation is of course reducible. More generally, if $G$ is abelian then it appears that no irreducible representation can come out of group action.
My question is: does it make sense to try and draw parallels further? I find it compelling that the functor takes $\sqcup$ to $\oplus$ and $\times$ to $\otimes$ (and these operations turn out to be important in representation theory), but the lack of an analog for irreducibility means that most representation theory will not correspond to anything.
Comment: Why $\operatorname{Hom}{({-},\mathbb{C})}$? Wouldn't $S \mapsto k[S]$ (free $k$-module on $S$) with the $G$ action induced from the one on $S$ be a more natural candidate (where $k$ is a commutative ring or a field)?  Then $k[S \sqcup T] = k[S] \oplus k[T]$ and $k[S \times T] = k[S] \mathbin{\otimes_{k}} k[T]$ are quite immediate. You can then apply $\operatorname{Hom}_k{({-},k)}$ to those and see what happens.
Comment: Isn't $\mathrm{Hom}(-, \mathbb{C}) = \mathbb{C}[-]$? I meant hom in category of sets :)
Comment: Not for infinite sets.
Comment: Ok, I'll change to $\mathbb{C}[-]$, I only toyed with finite sets :)
Answer: When you turn a finite $G$-set $X$ into a permutation representation $V=\mathbb{C}[X]$, then $V$ is never irreducible. Indeed, it always has the trivial representation as a summand, generated by $\sum_{x\in X} s$. You can still ask yourself what happens if you take this one summand out. The beautiful answer is that the remaining representation will be irreducible if and only if $G$ acts on $X$ doubly transitively. See Proposition 5.16 and the following corollary in these lecture notes on representation theory.
The precise relationship between $G$-sets and permutation representations is an active area of research. For example you can ask when two non-isomorphic sets give rise to isomorphic representations. This question is important not only in algebra, but also has applications to number theory, differential geometry, topology, and probably other areas. It took more than fifty years to answer this question in full generality, and the answer is very recent.
Also, if you replace $\mathbb{C}$ by $\mathbb{Q}$ and ask yourself, which characters of rational representations can be expressed as linear combinations of permutation characters, then you also quickly arrive at uncharted territory. See this question on math.se.


How to write a biconditional $P\leftrightarrow Q$, into a form using only connectives: $\to, \land, \bot$

Question: Take $P\longleftrightarrow Q$.
I am struggling to understand how to rewrite this proposition as an equivalent proposition, using only the two connectives: $\;\;\to,\;\; \bot$
If someone could further explain how this can be managed thanks in advance.
Comment: Austin: I edited your post, and when I did, I took `&` to mean the connective $\land$.  If you were trying to specify that you were limited to two connectives, those being $\rightarrow, \bot$, I will surely edit again to correct the edit.
Comment: It was only those two connectives but thanks to Mauro I was able to understand with a simply equivalency!
Comment: I've make the appropriate (re-)edit!
Answer: $P \leftrightarrow Q$ is equivalent to :

$(P \to Q) \land (Q \to P)$.

In turn, $A \land B$ is equivalent to :

$(A \to (B \to \bot)) \to \bot$.
Comment: I took the question to mean that only the connectives $\rightarrow, \land , \bot$
Comment: I.e., I took the OP's use of the symbol `&` to mean the connective $\land$.
Comment: @amWhy - in that case, the OP has a "bonus" answer...
Comment: Yes indeed! Nice job!


Can't ping from inside to outside; misconfigured DNS

Question: I have configured my network inteface according to this guide.
And now I can ping to server from my computer but I can't ping from server to outside world.
Note: I can ping 220.127.116.11
Can anyone explain whats the problem? Maybe because there is no gateway in eth0? but I need to have this configuration to run KVMs.
EDIT:
I think it's a DNS problem. I can ping IPs but I cant ping domains. sorry for misunderstanding.
# ping google.com
ping: unknown host

Comment: You contradict yourself. Since you *can* ping Google's DNS server (220.127.116.11), you *can* ping the outwide world. Though you claim you can't. What host can't you ping exactly so that you concluded that you don't have access to the outside world?
Comment: nslookup tells you...?
Comment: I think it's a DNS problem. I didn't really notice. I can ping IPs but I cant ping domains. sorry for misunderstanding. `# ping google.com`
`ping: unknown host google.com` Thanks
Comment: I have DNS setup in ifcfg-br0: `DNS1=220.127.116.11
DNS2=188.8.131.52` What else can be the problem?
Answer: Since it is a dns problem put the following in your /etc/resolv.conf:
nameserver 220.127.116.11
nameserver 22.214.171.124

That would set up your DNS servers system-wide.
Comment: Give [Red Hat Enterprise Linux Deployment Guide](http://www.centos.org/docs/5/html/5.2/Deployment_Guide/index.html) a try.
Comment: sorry for unrelated comment but can  I ask for a book about this stuff ? I'd appreciate if you name some of those.
Comment: The order of nameservers is important here or not?
Comment: Yes, it is important. They are listed by priority. See [resolv.conf(5)](https://linux.die.net/man/5/resolv.conf) for details.


Resize organized point cloud

Question: I have an organized point cloud (1280 * 720) captured from a 3D camera. I just wonder whether there's a method to resize(cut down) this point cloud to a smaller size (eg. 128 * 72), when keeping this cloud organized.
(I think this shouldn't be the same as down sampling. "Resize" means like zooming an image).
I am using Point Cloud Library 1.8.0 but stuck with this.
Any advice is welcome, thanks first!
Answer: The answer of Rooscannon is in particular correct, but has some bugs in it. The correct uniform subsampling of a organized point cloud is as follows:
// Downsampling or keypoint extraction
int scale = 3;
PointCloud<PointXYZRGB>::Ptr keypoints (new PointCloud<PointXYZRGB>);
keypoints->width = cloud->width / scale;
keypoints->height = cloud->height / scale;
keypoints->points.resize(keypoints->width * keypoints->height);
for( size_t i = 0, ii = 0; i < keypoints->height; ii += scale, i++){
    for( size_t j = 0, jj = 0; j < keypoints->width; jj += scale, j++){
      keypoints->at(j, i) = cloud->at(jj, ii); //at(column, row)
    }
}

So the loop conditions, the indexing and the initialization of the subsampled point cloud are different. Otherwise, the subsampled point cloud would not be organized anymore.
Answer: Just take a point out of the number of time you want to reduce your cloud,
something like that shloud work :
for (pcl::PointCloud<pcl::PointXYZ>::const_iterator it = src->begin(); it< src->end(); it+=times)
{
  dest.points.push_back(*it);
}

Only problem is the cloud might containt some NaN values. To correct it just set is_dense to false into dest and call removeNaNFromPointCloud on it.
Hope this can help you !
Comment: Thanks @Anatole for your explanation! Actually I have also come up with another way similar to (maybe more accurate than) yours. I am just calculating the average value of each m * m window of the src cloud as the corresponding value inside the dest cloud.
Comment: I have also realized the problem of NaN. It seems that "removeNaNFromPointCloud " does not keep the cloud organized. I just ignore any NaN point when calculating the average value, leaving the point NaN if all points inside the window of src image are NaN points.

Besides, I think there should be better interpolation ways than just calculating the average inside the window. Curious there is no any related API from PCL.
Comment: One more question about organized point cloud, @Anatole. Are you familiar with how to do down sampling for organized point cloud with PCL?  Thanks.
Answer: Can't comment but removing NaNs from your point cloud by default makes it unorganized. Quite likely the NaNs are there as dummy points in case your instrument was not able to observe a point in the matrix just to keep the matrix dimensions correct. Removing those breaks the matrix structure and you'll have a different amount of points than your 1280 * 720 matrix would expect.
If you wish to down sample an organized point cloud say by a factor of 2, you could try something like
int scale = 2;
pcl::PointCloud<pcl::your_point_type> down_sampled_cloud;
down_sampled_cloud.width = original_cloud.width / scale;
down_sampled_cloud.height = original_cloud.height / scale;

for( int ii = 0; ii < original_cloud.height; ii+=scale){
    for( int jj = 0; jj < original_cloud.width; jj+=scale ){
    down_sampled_cloud.push_back(original_cloud.at(ii,jj));

    }
}

Change scale to what you wish.
This method just down samples the original point cloud, it will not interpolate points between existing points. Scaling by a decimal factor is trickier and might yield unwanted results if the surface is not continuous.

Resize organized point cloud


How does this Stradella Bass System fingering work

Question: I am trying to learn the Bayan (Accordion) and the book I am following has the following piece as it's trying to introduce the left hand bass system.

In the first measure I can understand the position for the first three notes (C, D and E) but I am not able to understand how the F note (played with a button right next to the C button) is expected to be played using the 2nd finger.
Is it a different button than the one next to the C button or is it basically really quick fingering change that I need to learn ?
Comment: That's certainly an odd fingering and not playable on Stradella Bass. My guess is either a typo or that it's not for a Stradella bass after all. Maybe free bass? What book is it?
Comment: I know accordions can be "upside down" depending on where they are from. Perhaps your accordion is not from the same country? Or perhaps I did not understand the issue, is your hands too small so shifting would be needed? I think accordion player's hands fly all over the place (I can't play anything advanced myself and don't have one at home).
Answer: This is bayan free bas system. F is in the 1st line, suitable for 2nd finger. C is in 3rd line, suitable for 4th finger and E is on 2nd line, suitable for 3rd finger.


The best performing (theoretical complexity-wise) algorithm to solve this quadratic program

Question:
Find the best performing (complexity-wise) algorithm to solve the following quadratic program
$$\begin{array}{ll} \text{minimize} & \frac 12\|\mathrm x - \mathrm v\|_2^2\\ \text{subject to} & 1_n^T \mathrm x = \mathrm 1\\ & \mathrm x \geq 0_n\end{array}$$
where $\mathrm v \in \mathbb R^n$ is given.

I have started learning Moreau Yoshida Regularization to try to solve this problem, as I was hinted by my supervisor that the best performing algorithm makes use of that theory.
I will be adding the work that I have done on this question soon.
Comment: Are you looking for theoretical complexity or practical running time?
Comment: Have you tried to differentiate the Lagrangian function $$L = \frac{1}{2}\sum_{i=1}^{n}x_{i}^{2}  -\sum_{i=1}^{n}x_{i}v_{i} +\lambda \left(\sum_{i=1}^{n}x_{i}-1\right) - \sum_{i=1}^{n}\mu_{i}x_{i}?$$ I suspect that your problem can be solved algebraically.
Comment: theoretical complexity
Comment: The Lagrangian approach yields the following dual: $\sup_y \{ -v^Ty + \min\{0,\min_i\{y_i\}\} \; | \; ||y||\leq 1 \}$.
Answer: Your problem corresponds to orthogonally projecting the point $\textbf{v} \in \mathbb R^n$ onto the unit simplex.

The problem can be solved analytically in $\mathcal O(n)$ using Kiwiel's algorithm (e.g see Algorithm 3 of this paper). Needless to say this is the best possible theoretical bound.
If you want something a bit simpler (implementation-wise) with essentially the same complexity, then this $\mathcal O(n\log n)$ algorithm  will do.
Comment: I would like to thank you for this paper. Algorithm 3 seems to be what I am looking for. O(n) complexity.
Comment: Glad to hear all of this was useful to you :)
Comment: Have 200 of my reputation =)


Python Anaconda 3.6 plotly module using Figure

Question: can't seem to have this working:
import plotly.offline as pyo
from plotly.graph_objs import *
import plotly.plotly as py
import pandas as pd
from pandas import DataFrame

pyo.offline.init_notebook_mode()

trace1 = {'type' : 'scatter',
          'x' : [1,2,3,4,5,6,7,8,9],
          'y' : [1,2,3,4,5,6,7,8,9],
          'name' : 'trace1',
          'mode' : 'lines'}

layout = {'title' : 'my first plotly chart',
          'xaxis' : {'X Values'},
          'yaxis' : {'Y Values'}
          }

data = Data([trace1])

fig = Figure(data = data, layout = layout)

python dtates that Data in depreciated, and asks me to use something else, but I can't seem to figure it out.
Answer: Looks like you missed command to plot after creating figure. And Data([trace1]) looking incorrectly for my opinion. So if you want create a simple scatter plot using Python3, you can do it in two ways (and give the same result).
1.First way:
# Import all the necessaries libraries
import plotly.offline as py
import plotly.graph_objs as go
import pandas as pd
# In trace you specify what kind of plot you want (such scatter, bar, pie or so)
trace = go.Scatter(
      x=[1,2,3,4,5,6,7,8,9],
      y=[1,2,3,4,5,6,7,8,9],
      name="trace1",
      mode="lines")
# Data is just the list of your traces
data = [trace]
# Create layout if you want to add title to plot, to axis, choose position etc
layout = go.Layout(
      title="My first plotly chart",
      xaxis=dict(title="X Values"),
      yaxis=dict(title="Y Values"))
# Figure need to gather data and layout together
fig = go.Figure(data=data, layout=layout)
# This commandd plot the plot and create HTML file in your Python script directory
py.iplot(fig, filename="first plot.html")

2.Second way:
# Import all the necessaries libraries
import plotly.offline as py
import plotly.graph_objs as go
import pandas as pd
# This code have the same result as previous, but it is more unreadable as I think
fig = {
  "data": [
    {
      "x": [1,2,3,4],
      "y": [1,2,3,4],
      "name": "trace1",
      "type": "scatter"
    }],
  "layout": {
        "title":"My first plotly chart",
        "xaxis": {
                "title": "X Values"
                },
        "yaxis": {
               "title": "Y Values"
               }
            }
    }
# Just plot
py.iplot(fig, filename="first plot.html")

If you want to customize your plot, I am suggest you to check plotly docs about scatter plot.
Output:


Is it necessary to convert mixed type features to YoY percent change in order to coordinate with target variable

Question: Let's say I'm trying to build a time series model with the following dataset:
import pandas as pd
import numpy as np

np.random.seed(2021)
dates = pd.date_range(start='2020-01-01', end='2021-12-01', freq='MS')
df = pd.DataFrame(np.random.uniform(-1, 1, size=(24, 4)), index=dates, columns=['A_values', 'B_values', 'C_values', 'target'])
df

Out:
            A_values  B_values  C_values    target
2020-01-01  0.211957  0.466739 -0.722106 -0.374654
2020-02-01  0.994487 -0.743675 -0.642014  0.505851
2020-03-01  0.324321  0.568620 -0.806211 -0.882857
......
2021-10-01  0.940398 -0.168986 -0.339022  0.933428
2021-11-01  0.651798 -0.389200  0.646556  0.113821
2021-12-01  0.437002  0.759874 -0.007980  0.024173

Suppose I will use A_values (which is actual values of a variable), B_values (which is month over month percent change of a variable), C_values (which is year over year percent change of a variable) to forecast target column (which is year over year percent change of one variable).
Now my question is should I convert A_values and B_values to year over year percent change to coordinate with the target column's type? If I don't do that, will it lower the prediction accuracy?
In other words, could the machine learning algorithm such as XGBoost capture the relationship between MoM pct change and YoY pct change?
Note: it's easy to convert the actual value to YoY pct change, meanwhile we lose accuracy as converting from MoM to YoY.
Answer: I do not think that there is a clear answer without looking at the specific data. But if you want to build a time-series model using linear regression methods, I suggest to try build some features that capture some seasonality like year and month encoding (maybe using a dict saying: 'January':1, 'February':2, .... and for year: '2020':0, '2021':1, ....).
On top of this if you think there is an autoregressive process happening I would add lagged values of your ts. Thus adding values from past months helps the model to understand how the value for the next month will be. Effectively the model will just give coefficients (at least if you think of a linear regression using OLS) to previous values (maybe saying last month has a higher weight than the month before, etc.).
To see how many lags you should include you can check serial auto-correlation plots. But it would make sense to try some values and tread the lagged values as a kind of hyperparameter you want to optimise. Meaning, pick that many lagged values, that result in best model performance.
But check if your time-series is stationary. If not, then you would need to remove the trend to get reliable forecasts.
And also on your core question if you should create some features for MoM and YoY changes, I would suggest to try and see how your model performs with and without that information. As always the goal is to have a model with as little features as possible that generalises well.
I hope that helps a little bit


Existence of a continuous function on compact hausdorff space where $f(x) =1$ and $f(y)=-1$ with $\|f\|_\infty =1$.

Question: I think from topology, in the space of continuous functions on compact Hausdorff space that maps to the complex numbers, there exists a $f$ such that $f(x) =1$ and $f(y)=-1$ with $\|f\|_\infty =1$ where $x,y$ are distinct points of our compact Hausdorff space. I was wondering why such a function should exist and is the proof of its existence related to Urysohns lemma?
Answer: It is an easy consequence of Urysohns' Lemma. There exists a continuous function $g$  with $0\leq g\leq 1$, $g(x)=0$ and $g(y)=1$ (because $\{x\}$ and $\{y\}$ are disjoint closed sets. Take $f=1-2g$. Note that $-1 \leq f \leq 1$.


Questions on Theorem 5.5.7. in Brown-Ozawa

Question: I am currently trying to digest the proof of Theorem $5.5.7.$ in the book "$C^*$-algebras and Finite-Dimensional Approxmiations" by N. Brown and N. Ozawa.
Background:
Let $(X,d)$ be a metric space (of bounded geometry/uniformly locally bounded) and denote by $B(x,S)\subseteq X$ the open ball centered at $x$ of radius $S$. Also, we denote by $\ell_n^2$ the $n$-dimensional Hilbert space with orthonormal basis $\{\eta_i\}$ and by $A(X),C_u^*(X)$ the translation algebra respectively the $\textit{uniform Roe algebra}$ associated to $X$ (i.e. the closure of $A(X)$ in $B(\ell^2(X))$). Finally, $(e_{ij})$ will denote the standard matrix units (in $\mathbb{M}_n(\mathbb{C})$).
I have the following three questions (and I would be very happy to receive even partial answers/ideas to any one of them):
$(1)$: How does one realize that $\prod_{n\in \mathbb{N}}\mathbb{M}_k(\mathbb{C})\cong \ell^{\infty}(\mathbb{N})\otimes \mathbb{M}_k(\mathbb{C})$? I suppose that the implication "$\supseteq$" is clear enough.
$(2)$: Assume that there exists $S>0$ such that for every $x\in X$ there is an element $\zeta_x\in \ell^2(X)$ with $||\zeta_x||=1$ and $\text{supp}\zeta_x\subseteq B(x,S)$. Now, the operator $V_x\colon \ell^2(X)\to \ell^2(B(x,S))$  given by $\delta_y\mapsto \zeta_y(x)\delta_y$ satisfies that $\sum_{x\in X}V_x^*V_x=1$ strongly ($\textbf{why?}$) and so defines a u.c.p. map ($\textbf{why?}$) $\psi\colon \prod_{x\in X}B(\ell^2(B(x,S))\to B(\ell^2(X))$ given by $$\psi((b_x)_{x\in X})=\sum_{x\in X}V_x^*b_xV_x$$
(here, complete positivity is true for every $x$-coordinate, but I fail to see how this gives me what I want).
$(3)$: Given $\mathcal{H}=\ell^2_n\otimes \ell^2_n$, we turn $\mathcal{H}\otimes C_u^*(X)$ into a Hilbert $C_u^*(X)$-module through the inner product given by $\langle \xi_1\otimes a_1, \xi_2\otimes a_2\rangle = \langle \xi_1,\xi_2\rangle_\mathcal{H} \cdot a_1^*a_2$. Now, let $\psi\colon \mathbb{M}_n(\mathbb{C})\to C_u^*(X)$ be completely positive and let $[b_{ij}]=[\psi(e_{ij})]^{1/2}\in \mathbb{M}_n(C_u^*(X))$. From this, we define the element
$$\xi_\psi=\sum_{j,k}\eta_j\otimes \eta_k\otimes b_{kj}\in \mathcal{H}\otimes C_u^*(X)$$
It is claimed that "Perturbing $\xi_\psi$, we may assume that $\xi_\psi\in \mathcal{H}\otimes A(X)$". I do not see which kind of "perturbation" that is needed to achieve this.
Thank you very much!
Comment: In their proof, its not $\prod_{n \in \mathbb{N}} M_n$, its $\prod_{n \in \mathbb{N}} M_k$ - i.e., the size of the matrix algebras is stationary. With this, $\prod_n M_k$ is just bounded sequences of elements of $M_k$. From here, it's not too hard to construct an isomorphism $\prod_n M_k \simeq \ell^{\infty}(\mathbb{N}) \otimes M_k$.
Comment: @PStheman Thank you for noticing this! My insecurities stand, however. On the algebraic tensor product alone, the right-hand side allows for only finitely many specifications of $M_k$ (whereas the left-hand side can have arbitrarily many). Thus, I suppose that one should argue that all elements in the product set can be written as a norm-limit of finite specifcations. Would you say that finite dimension of $M_k$ plays a crucial role here?
Comment: @Deracless Have you been able to calculate explicitly $V_x^*$?
Comment: @QuantumSpace My guess would be that $V_x^*$ is given by $\delta_y\mapsto \overline{\zeta_y(x)}\delta_y$. My issues may lie entirely in the understanding of strong convergence. Like; if $\sum_x V_x^*V_x\delta_y=\delta_y$, can we then conclude $\sum_x V_x^*V_x=1$?
Answer: I'll answer $(1)$. More generally, if $M$ is a von Neumann algebra, and $I$ is an index set, then
$$\prod_{i \in I} M \cong \ell^\infty(I)\overline{\otimes} M$$
where the tensor product is the von Neumann tensor product. In your case, $M$ is finite-dimensional, so the von Neumann tensor product is just the algebraic tensor product which leads to
$$\prod_{i \in I} M_k(\mathbb{C}) \cong \ell^\infty(I)\odot M_k(\mathbb{C}).$$
In an ad hoc way, we can proceed in multiple ways. For example, we have a canonical chain of $*$-isomorphisms
$$\prod_{i \in I} M_k(\mathbb{C})= \ell^\infty(I, M_k(\mathbb{C})) \cong M_k(\ell^\infty(I)) \cong  \ell^\infty(I) \odot M_k(\mathbb{C}).$$
Comment: Uhm not really: but the proof is easy enough: if $M\subseteq B(H)$ embed $\prod_{i \in I} M\subseteq B\left(\bigoplus_{i \in I} H\right)$. On the other hand, $\ell^\infty(I)\overline{\otimes} M$ embeds in $B(\ell^2(I)\otimes H)$. Now we observe that there is a unitary $\ell^2(I)\otimes H\cong \bigoplus_{i \in I} H_i$ and this unitary implements the desired $*$-isomorphism.
Comment: Thank you! Do you have a reference in mind for this result?
Answer:
For C$^*$-algebras, the norm in the direct product is the supremum norm. This is natural if one thinks of the direct product as forming a "block diagonal". Thus
$$
\prod_n A=\{f:\mathbb N\to A,\ \text{ uniformly bounded}\}=\ell^\infty(\mathbb  N,A).
$$
So one needs to check that $\ell^\infty(\mathbb N,A)\simeq \ell^\infty(\mathbb N)\otimes A$  when $\dim A<\infty$. If we fix a basis $a_1,\ldots,a_r$ of $A$ any $f:\mathbb N\to A$ is of the form $f(n)=\sum_{k=1}^r x_{n,k}\,a_k$, where $x_k=(x_{n,k})_n\in\ell^\infty(\mathbb N)$. Then we define the map
$$
\gamma:f\longmapsto \sum_{k=1}^r x_k\otimes a_k.
$$
Using that $a_1,\ldots,a_r$ form a basis, it is easy to see that $\gamma$ is bijective. Linearity and multiplicativity are also trivial, as is the fact that $\gamma$ preserves adjoints.

In the canonical basis the operator $V_x$ is "diagonal", since its sends $\delta_y$ to a multiple. It follows that
$$
V_x^*\delta_y=\overline{\zeta_y(x)}\,\delta_y,\qquad\qquad\text{ and } \qquad\qquad V_x^*V_x\,\delta_y=|\zeta_y(x)|^2\,\delta_y.
$$
Then, for any $F\subset X$ finite,
$$
\sum_{x\in F}V_x^*V_x\sum_y\alpha_y\delta_y=\sum_{x\in F}\sum_y\alpha_y|\zeta_y(x)|^2\,\delta_y=\sum_y\alpha_y\Big(\sum_{x\in F}|\zeta_y(x)|^2\Big)\,\delta_y\xrightarrow[F]{}\sum_y\alpha_y\delta_y
$$
since $\sum_{x}|\zeta_y(x)|^2=1$. That is, $\sum_xV_x^*V_x\to1$ sot.

When you apply $\psi^{(n)}$ to a positive $n\times n$ matrix $[(b^{(k,j)}_x)_x]$ (where positivivity means positivity for each $x$) you get
$$
\sum_x[V_x^*b^{(k,j)}_x V_x]_{k,j}=\sum_x\begin{bmatrix} V_x\\ &\ddots\\&&V_x\end{bmatrix}\big[b_x^{(k,j)}\big]\,\begin{bmatrix} V_x\\ &\ddots\\&&V_x\end{bmatrix}^*\geq0
$$

Given $\varepsilon>0$, there exists elements $b_{kj}'\in A(X)$ such that $\|b_{kj}-b_{kj}\|<\varepsilon/n^2$. Then
$$
\xi_\psi'=\sum_{j,k}\eta_j\otimes \eta_k\otimes b_{kj}'\in \mathcal{H}\otimes A(X)$$ and $\|\xi_\psi'-\xi_\psi\|<\varepsilon$.
Comment: Thank you for your very detailed answer. All of it seems to work out nicely. However, further on in the proof (and something that I forgot to mention), it seems necessary to have that $\langle \xi_\psi,\xi_\psi\rangle=\psi(1)=1$ in order to conclude that the collection $\{\zeta_x\}_{x\in X}$ consists of unit vectors. This is easily verified for the initial specification of $\xi_\psi$, but establish the same property for an element $\xi'_\psi\in \mathcal{H}\otimes A(X)$?  Thank you again!
Comment: The proof ends with an estimate, so as far as I can tell you can do a further approximation.


Can an unbounded series of functions converge pointwise to a bounded function?

Question: I'm trying to find an example of a sequence of unbounded functions $f_n: [0,1] \rightarrow \mathbb{R}$ which converge pointwise to a bounded function $f: [0,1] \rightarrow \mathbb{R} $.
I can find lots of examples of bounded sequences which converge pointwise to an unbounded function but can't think of a function which converges unbounded $\rightarrow$ bounded.
Is this possible?
Comment: $$f_n(x)=\begin{cases} 0, &x=0 \\ 1/x, & 0<x<1/n \\ 0, & x\geq 1/n\end{cases}$$
Comment: Did you consider $f_n=\frac f n$?
Answer: Yes, it is possible, but you will have to consider functions which are not continuous, since a continuous function is bounded on a compact set by Weierstrass' theorem.
Let $g : [0,1] \to \mathbb{R}$ be an unbounded non-negative function.
For every $n\geq 0$, let $f_n = g \mathbb{1}_{g(x)> n}$.
Then for every $x\in [0,1]$, for every $k\geq g(x)$, we have $f_k(x) = g(x) * \mathbb{1}_{g(x)> k}(x) = 0$, so the sequence of functions $(f_n)_{n\in{\mathbb{N}}}$ converges pointwise to the zero function.


CCK text field does not appear in views fields nor filters

Question: I have a CCK text field in my TOC. However, it is not displayed for selection under the views fields nor the views filters.
I tried clearing cache and refreshing the module list with no luck.
Any hint of what could be happening?
Comment: Have you checked permissions?
Comment: Other fields in the same TOC are visible. I have installed no field access permissions module.
Answer: The problem was that I had in Views -> Tools the option "Disable views data caching" unchecked. Fixed now, thanks for your help!


Sent items are stored in own mailbox instead of shared mailbox

Question: E-mail sent from (not on behalf) a shared mailbox is stored in the user's mailbox sent items folder instead of the sent items folder in the shared mailbox.
There is apparantly a hotfix (KB2181579) but that only works with Cached Exchange Mode enabled.
Enabling Cached Exchange Mode is PITA, as it has its own problems (missing folders, calendar items missing/not synchronizing etc)
Is there a way to store the sent items in the shared mailbox, which does not involve rules?
Comment: I'm curious on your comment "enabling cached exchange mode is a PITA" since this is the recommended (and nowadays normal) way for Outlook to operate in an Exchange environment.
Comment: It happens often that mail folders just disappear from Outlook's cached copy. And we've seen a lot of mysterious problems with shared calendars (for example: calendars that appear empty in cached mode, but do have appointments in them) and now this problem with saving sent items to the user's folders instead of the mailbox where it belongs.
Answer: I am unsure if this would answer your query.
Create a rule on OWA (webmail) and open your shared mailbox on which the sent item has to be saved.
Open Options in the (Shared Mailbox webmail)

And go to Mail -> Automatic processing -> Inbox and sweep rules and create a rule to download the Sent Items which are saved in Personal mailbox
[2


Relative versus Absolute path to cv::imread OpenCV

Question: I've got a cross platform error with OpenCV 2.3.1 and 2.4 on both VS2010 and Xcode 4.2
If I use cv::imread while giving the path to the image as an absolute path, it works. It does not work if that is a relative path. I usually put the images in the same dir as the code as well as all other dirs in the project just to be careful.
Much appreciated if anyone can answer this. Thank you!
Harish.
Answer: In Visual Studio, when you create a C++ project, it sets the project's working directory to the project dir, not the output dir of the executable.
That means that if you run the project from inside Visual Studio (by using the F5 button or the "Start Debugging" button), the program that you are writing won't be able to see the files that are in the same dir as the .exe file. But when you run the program from Windows Explorer (by double-clicking it) it will work as expected.
To fix this, you need to go in the Project properties window under Configuration properties -> Debugging, and change the Working Directory from $(ProjectDir) to $(OutputPath). You should change this both for the Debug and the Release configuration.
I don't know if this is the same case in XCode, but you can try this solution there too.
Comment: I did try this, but it didn't work..Also, my code works perfectly with an absolute path, and not with relative.
Comment: Does it work when you run it with double-click from Windows Explorer? Also, please post the line of code where you use `cv::imread`, and maybe a screenshot of the folder where your .exe file is located.
Comment: Hi, I was able to get it working in VS2010 after building OpenCV using Cmake again and putting in the libraries for linking. It does work. I wasn't able to get it to work on Xcode though, but I think it is once again an build dir problem as you mentioned, and will get back on that.


Knot invariants that discern prime and composite knots.

Question: Is there a list of knot invariants that can tell whether or not a knot is prime? Or at least partially so? i.e. invariants that have one or more of the following properties:
(a) The invariant has a certain value/form/etc. $\Rightarrow$ a knot is prime
(b) The invariant has a certain value/form/etc. $\Rightarrow$ a knot is composite
(c) A knot is prime $\Rightarrow$ the invariant has a certain value/form/etc.
(d) A knot is composite $\Rightarrow$ the invariant has a certain value/form/etc.
For example, genus falls into category (a) since $g(K) = 1 \Rightarrow K$ is prime
edit: I just realized that (a)$\Leftrightarrow$(d) and (b)$\Leftrightarrow$(c), but some things might be more natural to state in one form or the other.
Comment: Please correct me if I am wrong... but since the composite knot $K_1 + K_2$ has an Alexander polynomial $A(K_1)A(K_2)$, if the Alexander polynomial of $K$ cannot be factorized then it is prime. There is a similar formula for satellite knots. And there are similar formulae for Jones polynomial, I guess?
Answer: There are other invariants, like your example genus, where the first value that the unknot does not take is guarnteed prime. Bridge number is also like this.  The more useful answer however, is in the form of being able to determine hyperbolic knots.
Knots come in three types: Torus, Satellite (which includes composite knots), and Hyperbolic.
Any hyperbolic knot is prime. There is a program, originally developed by Jeff Weeks, called SnapPea, and the new incarnation is called SnapPy (download here) , that determines can determine the hyperbolic volume, (which is always >2) of a knot - IF that knot is a hyperbolic knot.  Otherwise, it returns zero, in which case it is either torus or satellite.
Now you have answered your question, or gave yourself a new one.  To determine if you have a torus knot or satellite knot, you can use the fact that a knot is a torus knot if and only if it has non-trivial center of its fundamental group.  Unfortunately, this isn't that easy. But it will mostly answer your question, you will then have to determine the index of your satellite knot.  If it is index 1, you have a composite, if >1, it is (I will use the word) proper satellite.  This whole process shouldn't be too bad for a knot with small crossing number.
Hope this helps.  Let me know if something was not clear here.


How to export a cytoscape web graph before serving a page to a browser

Question: Scenario:
A client is on a page with a search bar, they enter a query. This query is passed along to a second page that is generated dynamically with php by the server. Along with the query information given to the php script a variable is passed that allows the php script to determine if flash is available to the client's browser. Now the php script displays a png of a network graph generated by cytoscape web if flash is unavailable and a swf of the graph if flash is available.
Problem/Question:
1.) Cytoscape web is a javascript library for displaying graphs. It has an export function(http://cytoscapeweb.cytoscape.org/documentation#section/exportNetwork) but that only allows for a browser to download an exported file. I want to be able to export and save this file during the php runtime and then embed it as content in place of a swf if flash is not enabled. How would I go about doing this if the javascript method has to be run in the client's browser?
Resources
Graph export method 1: http://cytoscapeweb.cytoscape.org/documentation#section/png
Graph export method 2: http://cytoscapeweb.cytoscape.org/documentation#section/exportNetwork
Comment: Basically I think I would need some way of running the cytoscapeweb javascript serverside to generate and save the files there. And to be able to run the JS from within my php file.
Answer: A similar question was asked over on the cytoscape web google groups page.
Here is the link to the question and answer
Here is what the said:
If you use png(), you only get the bytes of the image as String (as Base64). It does not export the image to the server-side and does not make it available for download. In order to do that, you have to submit the string to the server side yourself, convert from base64 to bytes again and then make the server component (e.g. PHP, Java Servlet) stream the bytes back to the browser, so users can download the image.
There is also the option of using a Flash component/plugin for getting the bytes and making it downloadable without the need of the web server.  That's exactly what the Cytoscape Web demo application (http://cytoscapeweb.cytoscape.org/demo) does when you select the "Save file" menu option.
You can copy the examples from the demo's JavaScript file and use the Flash library we developed for that. It is not well documented, so I guess it may be a little bit complicated. Anyway, if you want to give it a try, take a look at:
- http://cytoscapeweb.cytoscape.org/js/content/demo.js - search for "org.cytoscapeweb.demo.Exporter"
- http://chianti.ucsd.edu/svn/cytoscapeweb/trunk/file/ - you can download the component project from Subversion with the command:  svn checkout http://chianti.ucsd.edu/svn/cytoscapeweb/trunk/file cwfile-read-only

If you search the internet, you may find similar plugins.
Remember that the png() function must be called from inside the ready() function, before you call vis.draw() - example:
vis.ready(function() {
    var png = vis.png();
// handle the png bytes here:
    alert(png);
});
vis.draw(draw_options);

An easier option is to use the exportNetwork() function, which requires a server-side part. See http://cytoscapeweb.cytoscape.org/documentation/cytoscape_web#section/exportNetwork ; it even includes a PHP example.
The JavaScript part would be something like this:
vis.ready(function() {
    // ...
vis.exportNetwork('png', 'export.php?type=png');
    // ...
});

The name of the output file is done by the server-side code -- the "export.php" file in this example.
I hope that helps


How to solve wordpress redirect with parameter 404 error?

Question: i am new in wordpress and i am going to replace the search url with my own page, but when i hit the page and it show me 404 error.
It works without any parameter (http://harsimranjit.vintage-comics.net/products/)
but with parameter not (http://harsimranjit.vintage-comics.net/products/?s=bag).
Please help me to solve this problem. i am using wordpress default theme twenty-twenty
Answer: First you need to create a function to tell WordPress to keep track of our new query variables
function add_query_vars($aVars) {
$aVars[] = "products";
return $aVars;
}
add_filter('query_vars', 'add_query_vars');

you also need to tell WordPress how to populate that query variable
function add_rewrite_rules($aRules) {
$aNewRules = array('products/([^/]+)/?$' => 'index.php?pagename=products&s=$matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}

add_filter('rewrite_rules_array', 'add_rewrite_rules');

you can't just use the $_GET superglobal to grab our query variable
Instead you have to access the query_vars property of the $wp_query object.
if(isset($wp_query->query_vars['s'])) {
$sMsdsCat = urldecode($wp_query->query_vars['s']);
}

Passing Query String Parameters In WordPress URL


Laravel request validation

Question: Bom estou tendo problemas com validações no laravel, na real ele está validando corretamente porém preciso informar ao usuário que campo X é requerido ou não.
Hoje o sistema simplesmente manda para mesma tela limpando todo o meu formulário isto não seria o ideal para mim.
Preciso que meu programa informe os campos que estão com falhas então permanecer no mesmo local com os dados preenchidos ainda.
Tenho um partilview onde faço estas mostro esta massagens:

any() ? '' : "style='display: none'" !!}>

Ops...

    @if($errors->any())
        @foreach($erros->any() as $erro)

{{$erro}}

        @endforeach
    @endif

@if(Session::has('flash_message'))

        {{Session::get('flash_message')}}
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

@endif

Nas páginas onde quero que esta validação apareça eu simplesmente faço:
@include('shared.alert')

Em meu model tenho a função store que salvaria meus dados ela, eu programei assim:
public function store(ProdutoRequest $resquest){
    $produto = Produto::create($resquest->all());
    session()->flash('flash_message', 'Produto criado com sucesso');
    $produtos = Produto::all();

    if(Request::wantsJson()){
        return $produto;
    }else{
        return view('Produto.listProduto', compact('produtos'));
    }
}

O legal que dentro dela utilizo o session-flash e ele funciona perfeitamente porém para os erros não.
Ja meu ProdutoRequest eu programei assim:
class ProdutoRequest extends Request
{
   public function authorize()
   {
       return true;
   }

   public function rules()
   {
     return [
        'CdSubCategoria' => 'required',
        'NmProduto' => 'required|min:1',
        'VlUnit' => 'required|min:1',
        'FlgDescontinuado' => 'required',
        'FlgProdutoVisivel' => 'required',
        'FlgPontua' => 'required',
     ];
   }
}

minha view form:
@include('shared.alert')
{{dump($errors)}}

has('CdSubCategoria') ? ' has-error' : '' }}">
        {!! Form::label('nmSubCategoria', 'Sub Categoria') !!}
        {!! Form::select('CdSubCategoria', $subcategorias , $produto->CdSubCategoria, ['class' => 'form-control select2']) !!}

has('NmProduto') ? ' has-error' : '' }}">
        {!! Form::label('nmProduto', 'Nome do produto') !!}
        {!! Form::text('NmProduto', null, ['class' => 'form-control nomeProduto']) !!}

has('DscProduto') ? ' has-error' : '' }}">
        {!! Form::label('dscProduto', 'Descrição do produto') !!}
        {!! Form::textarea('DscProduto', null, ['class' => 'form-control', 'id' => 'editor1']) !!}

    {!! Form::label('vlProduto', 'Valor') !!}

has('VlUnit') ? ' has-error' : '' }}">

            R$
            {!! Form::text('VlUnit', null, ['class' => 'form-control','data-inputmask' => '"mask": "999.99"', 'data-mask']) !!}
            <?php echo $errors->first('VlUnit'); ?>

        {!! Form::label('flgAdicionarEstoque', 'Adicionar estoque?') !!}
        {!! Form::radio('FlgAdicionarEstoque', '1', false, ['class' => 'form-control estoqueVisivel minimal']) !!}
        {!! Form::label('flgAdicionarEstoque', 'Sim') !!}
        {!! Form::radio('FlgAdicionarEstoque', '0', true, ['class' => 'form-control estoqueVisivel Inativo minimal']) !!}
        {!! Form::label('flgAdicionarEstoque', 'Não') !!}

            {!! Form::label('qtdEmEstoque', 'Estoque') !!}
            {!! Form::number('UnitEmEstoque', null, ['class' => 'form-control']) !!}

        {!! Form::label('flgDescontinuado', 'Produto descontinuado ?') !!}
        {!! Form::radio('FlgDescontinuado', '1', false, ['class' => 'form-control minimal']) !!}
        {!! Form::label('flgDescontinuado', 'Sim') !!}
        {!! Form::radio('FlgDescontinuado', '0', true, ['class' => 'form-control Inativo minimal']) !!}
        {!! Form::label('flgDescontinuado', 'Não') !!}

        {!! Form::label('flgProdutoVisivel', 'Produto visivel ?') !!}
        {!! Form::radio('FlgProdutoVisivel', '1', false, ['class' => 'form-control produtoVisivel minimal']) !!}
        {!! Form::label('flgProdutoVisivel', 'Sim') !!}
        {!! Form::radio('FlgProdutoVisivel', '0', true, ['class' => 'form-control produtoVisivel Inativo minimal']) !!}
        {!! Form::label('flgProdutoVisivel', 'Não') !!}

            {!! Form::label('visivel_Ini', 'Inicio da visualização') !!}
            {!! Form::datetime('Visivel_Ini', \Carbon\Carbon::create()->format('d/m/Y H:i:s'), ['class' => 'form-control datepicker', 'id' => 'datInic']) !!}

            {!! Form::label('visivel_Fim', 'Fim da visualização') !!}
            {!! Form::datetime('Visivel_Fim', null, ['class' => 'form-control datepicker']) !!}

        {!! Form::label('flgPontua', 'Produto pontua ?') !!}
        {!! Form::radio('FlgPontua', '1', false, ['class' => 'form-control FlgPontua minimal']) !!}
        {!! Form::label('flgPontua', 'Sim') !!}
        {!! Form::radio('FlgPontua', '0', true, ['class' => 'form-control FlgPontua Inativo minimal']) !!}
        {!! Form::label('flgPontua', 'Não') !!}

            {!! Form::label('qtdPontos', 'Quantos pontos ?') !!}
            {!! Form::number('QtdPontos', null, ['class' => 'form-control']) !!}

            {!! Form::label('maxPontosPorSubCategoria', 'máximo de pontos ?') !!}
            {!! Form::number('MaxPontosPorSubCategoria', null, ['class' => 'form-control']) !!}

        {!! Form::submit($submitButton, ['class' => 'btn btn-success']) !!}
        {!! link_to_route('produtos.index', 'Voltar', '', ['class' =>  'btn btn-warning' ]) !!}

E aqui a minha view principal:
@section('conteudo')

Cadastro de produtos

        {!! Form::open(['route' => 'produtos.store', 'id' => 'produtos-form']) !!}
            @include('Produto.form', array('submitButton' => 'Enviar'))
        {!! Form::close()  !!}

@stop

O que falta para mim ? Como conseguir chegar até o ponto que preciso, especificado em negrito ?
Answer: Eu não sei bem como foi configurado seu Framework Laravel, mas, vou tentar esclarecer com um exemplo:
ChamadoRequest
Na classe ChamadoRequest possui validação para nome que é obrigatório e email que é obrigatório e tem que ser um e-mail válido.

<?php

namespace App\Http\Requests;

use App\Models\Pedido;
use Illuminate\Foundation\Http\FormRequest;

class ChamadoRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'nome' => 'required',
            'email' => 'required|email'
        ];
    }
    public function messages()
    {
        return [
            'nome.required' => 'O nome do cliente é requerido',
            'email.required' => 'O e-mail do cliente é requerido',
            'email.email' => 'O e-mail é inválido'
        ];
    }
}

controller ChamadoRequest

No controller ChamadoController no método save, faça a injeção da classe ChamadoRequest, que terá um papel fundamental de testar os dados antes de executar esse método, se não for satisfatório ele volta para View com os erros
public function save(ChamadoRequest $request)
{
    //operações
    return redirect()->route('chamados.index');
}

View index.blade.php

@extends('layout._layout')
@section('content')

Cadastro de Chamados

    @include('errors',['errors'=>$errors])

    {{ Form::open(array('route' => 'chamados.save', 'role'=>'form', 'id' =>'form1','name' =>'form1' )) }}

        {{ Form::label('email', 'E-mail do cliente:', array('class' => 'awesome')) }}
        {{ Form::text('email', old('email'), array('class'=>'form-control','placeholder'=>'E-mail do cliente', 'maxlength' => '70')) }}
        <?php echo $errors->first('email'); ?>

        {{ Form::label('nome', 'Nome do cliente:', array('class' => 'awesome')) }}
        {{ Form::text('nome', old('nome'), array('class'=>'form-control','placeholder'=>'Nome do cliente','maxlength'=>'50')) }}
        <?php echo $errors->first('nome'); ?>

    <button type="submit" class="btn btn-success"> Salvar</button>
    {{ Form::close() }}
@stop

e a View errors.blade.php que é chamado com include na View index.blade.php.
@if (isset($errors) && count($errors) > 0)

  ×
  Erros encontrados!

  @foreach($errors->all() as $error)

{{$error}}

  @endforeach

@endif

No formulário principal (index.blade.php) exite um
<?php echo $errors->first('nome'); ?>

se houver algum erro de validação no campo nome ele volta e te mostra o erro.
Comment: dando uma olhada no seu código o seu `@foreach($erros->any() as $erro)` deveria ser `@foreach($erros->all() as $erro)` observe tem erro de sintaxe... !
Comment: ainda sim ele não esta me retornando os erros na pagina.
Comment: Fiz as devidas alterações porém continua da mesma maneira, o que pode ser @Virgilio
Comment: Poste na sua pergunta a sua View principal?! a sua rota também!
Comment: Atualizei minha pergunta
Comment: @RenanRodrigues `
        {!! Form::label('nmProduto', 'Nome do produto') !!}
        {!! Form::text('NmProduto', null, ['class' => 'form-control nomeProduto']) !!}
    ` você não colocou a tag igual eu disse na resposta! Também tem tag que não está sendo verificada! Faz o seguinte, crie um formulário simples com 1 campo e teste pra ver se está funcionando se espelhando no meu exemplo!

Laravel request validation


powershell Read-host does not stop for input

Question: I thought this would be fairly basic, but i'm stuck.
I have 3 lines of powershell script in which I want to collect a mailbox name from user input, then create names based on that mailbox name. (later the script proceeds to create the groups in AD, etc)
my problem is that when I run all 3 of these lines by pasting them into powershell window, I don't get a change to enter the response to read-host. Instead the script just scrolls through to the next line and uses it as the response for the Read-Host
here's the powershell:
<code>$name = read-host "enter group name"
$groupfull = ($name+'.Full'a)
$groupsendas = ($name+'.SendAs')
</code>
Here's the output:
<code>PS C:\Users\kg> $name = read-host "enter group name"
enter group name: $groupfull = ($name+'.Full')
PS C:\Users\kg> $groupsendas = ($name+'.SendAs')
PS C:\Users\kg>
</code>
Thanks in advance
Answer: From a powershell shell window you will need to enter them one at a time.  If you want to do all three at once you should run them from a script file or within an IDE such as ISE.  You can run them from the script pane of ISE (enter the code, hit the Run Script button or F5).
Here it is in ISE:
Comment: Here is what happens when I run from ISE: PS C:\Users\kg> `c:\scripts\Exchange.SharedMailbox.Input.test.ps1
enter group name = .Full: mailbox PS C:\Users\kg>`
-- it's taking the line below the read-host and using it as input
Comment: @llirik42 Are you running it from inside the script pane?  See the screenshot in my edit.
Comment: Got it.. I had a comma after "enter group name"
It's working now, except it's prompting me on the execution pane, rather than a dialogue box. Not sure if because of version.  Either way, I think I'm good.  Thanks for your help


Safari pull-to-reload creates different innerHeight than normal reload

Question: I'm working on a page where a full height banner is displayed on page load, this is done by setting the height of the image container in JS when page is loaded, resized, or the orientation is changed. This works well, however I've come across an issue in Safari on iOS where on initial page load, or by pressing the refresh icon, the height calculates correctly, but when using pull-to-reload the window.innerheight calculates about 60 pixels less. I know there are differences in how Safari calculates innerHeight based on if the toolbar is expanded, but this seems to be a different issue because the height is only wrong when pull-to-reload is used. Any ideas?
Answer: I was able to fix this by using the new svh unit instead of window.innerheight
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Exponential Twisting

Question: I am with a difficult to prove the next relation about exponential twisting.
According to Monte Carlo Methods and Models in Finance and Insurance by Ralf Korn, Elke Korn, Gerald Kroisandt.
The method of exponential twisting is given by:

I am trying to prove that in fact
$$C'(\theta)=E[X \exp(\theta'X-C(\theta))]=E_{\theta}(X)$$
I have the next steps:
First I know by the definition given that $M(\theta)=E(\exp(\theta'X))$, then the function $C(\theta)=ln(E(\exp(\theta'X)))$.
I need to compute the derivative, in that case, I am looking for $$\frac{dC(\theta)}{d\theta}=\frac{dE[\exp(\theta'X)]}{E[\exp(\theta'X)]}$$
using the derivative of the natural logarithm.
Now, I note that $E(X)=\int x f(x)dx$ then, If I take the derivative on both sides I get: $$\frac{dEX}{dx}=xf(x)dx$$.
It the derivative of the expectation is equal to the argument $x$ times the density function, times the differential of the variable , i.e.
$$C'(\theta)=\frac{\exp(\theta'X)}{E(\exp(\theta' X))}xf(x)$$
Then I note that $\frac{\exp(\theta'X)}{E(\exp(\theta' X))}f(x)=f_\theta(x)$
From here I am a little bit confused with my proof, maybe something of my justifications are not right.
Answer: It looks like you're having trouble with the derivative of a moment generating function. The reason they have the name they have is because they generate (via differentiation) moments (as long as you set $\theta$ equal to zero after). For moment generating functions, you can interchange the order of integration and differentiation. This means $\frac{d}{d\theta}E[e^{\theta'x}] = E\left[\frac{d}{d\theta}e^{\theta'x}\right] = E\left[X e^{\theta'X}\right]$.
Here are the rest of the steps.
\begin{align*}
C'(\theta) &= \frac{d}{d\theta} C(\theta) \tag{defn}  \\
&= \frac{d}{d\theta} \ln M(\theta) \tag{defn} \\
&= \frac{M'(\theta)}{M(\theta)}\tag{chain rule}  \\
&= \frac{ E[X \exp(\theta'X)] }{\exp(\log M(\theta))}\tag{prop. of mgf}  \\
&=E[X \exp(\theta'X)]  \exp( - \log M(\theta))  \tag{algebra} \\
&=E[X \exp(\theta'X- \log M(\theta))] \tag{algebra} \\
&=E[X \exp(\theta'X- C(\theta))] \tag{defn}
\end{align*}

Exponential Twisting


mysql trigger para replicar o valor do ID noutra coluna

Question: Tenho andado em torno disto mas o valor é "NULL"
<code>create trigger tr_ReplID before insert on DuploId FOR EACH ROW set new.ID=new.Replica_ID;
</code>
O que pretendo...
Ao inserir dados na tabela Processos o ID será o número do processo, posteriormente ao fazer alterações na tabela com formulário PHP o número do processo que será mostrado será o Replica_ID, que poderá ser duplicado e assim saber sempre que estou a alterar o processo pretendido. Na minha ignorância é a forma de o fazer ...
Será que me podem ajudar?
Obrigado
Answer: Depois alguns testes cheguei à conclusão que talvez não seja possível copiar o ID. (pelo menos com trigger simples)
Estarei correcto?
Fiz um teste com um trigger que copia e Formata a Data e funciona, com o ID NULL ou "0".
PS: uso MariaDB em Linux


Problemas na Pseudo Classe nth-child(n) CSS3

Question: Estou tentando fazer em CSS3 com nth-child() o famoso "cor sim, cor não" em uma lista feita em Foundation 5. Acontece que no meio da lista haverá uma div na qual será um modal e essa div do modal acaba bagunçando o efeito "cor sim, cor não" fazendo a coluna ficar cinza, ao invés da linha.

#container>.row div:nth-child(2n) {
  background-color: #dcdcdc;
}

#container>.row div:nth-child(2n+1) {
  background-color: #fff;
}
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">

      a

      b

      c

      d

      a

      b

      c

      d

      a

      b

      c

      d

      a

      b

      c

      d

      a

      b

      c

      d

      a

      b

      c

      d

Comment: `:nth-child(number) {
    css declarations;
}` .... você está passando `div:nth-child(2n)`.. o que é esse `"n"`?
Comment: Não sei explicar ao certo o que é o `n`, mas é um tipo de multiplicador. Funciona parecido com `:nth-child(odd)` e o `:nth-child(even)`
Answer:
Seu problema não é a div modal, visto que no CSS você seta a classe .row. O CSS está fazendo exatamente o que você manda, colorir uma coluna inteira de cinza e outra coluna inteira de branco. Para resolver de outra forma, faça o seguinte:

Faça uma classe padrão no CSS para coloração.
Coloque uma classe padrão juntamente ao "row" para cada lista que você quer colorir. Fazendo isso, você não mistura os outros "row" da página.
Utilize um jQuery para fazer uma lógica de coloração, por exemplo:

//Fazemos um loop nas suas listas (LINHAS).
$('.row.lista').each(function(i) {
  //Se a linha tiver resto da divisão um número PAR -> executa coloração das colunas.
  if(i % 2 == 0)
  {
    ($(this).children()).each(function(j) {
      $(this).addClass("striped");
    });
  }
  //Assim teremos um aspecto cor sim, cor não para cada linha.
});
.striped {
  background-color: #dcdcdc;
}

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">

      a

      b

      c

      d

      e

      f

      g

      h

      a

      b

      c

      d

      a

      b

      c

      d

      a

      b

      c

      d

      a

      b

      c

      d

Comment: É possível fazer em CSS? Porque nessa lista eu tenho um cabeçário e ao clicar no cabeçário é ordenado conforme ordem alfabetica porém bagunça  tudo as cores... Se for em css não bagunça.
Comment: Fiz um "ajuste técnico" no seu código e deu certo, rsrsrs. Obrigado!!!


Como pegar ip de um usuario usando php?

Question: Eu estou usando a função getenv("REMOTE_ADDR"), para pegar o ip dos usuários que entrar numa determinada pagina do meu site e depois eu fiz um if para redirecionar aquele ip que não for igual o da variável de ip permitido. Mas quando eu jogo na hospedagem ele não pega o ip de quem esta acessando e sim um outro ip.
Alguém sabe o porque ou conhece outro método?
<?php

    $pegar_ip = $_SERVER["REMOTE_ADDR"];
    $ip_permitido = "ip_permitido";

    if ($pegar_ip == $ip_permitido)
    {
       echo 'Ip Permitido!';
    }
    else
    {
        header("Location: url");
    }

?>

Answer: Se não estiver utilizando serviços como CloudFlare, Incapsula e nem Sucuri, dentre outros, você pode utilizar:
$_SERVER['REMOTE_ADDR'];

Isso irá retornar o IP do usuário, se ele estiver usando proxy irá retornar o IP do proxy que está usando, entretanto é melhor do que confiar do X-FORWARDED-FOR.

Se estiver usando CloudFlare:
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];

Se estiver usando Incapsula:
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_INCAP_CLIENT_IP'];

Se estiver usando o Sucuri:
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_SUCURI_CLIENTIP'];

Lembre-se que é extremamente necessário recursar conexões diretas ao servidor, restringido o acesso ao site para conexões originadas destes serviços. Caso contrário, permitirá um IP Spoofing. Isso ocorre porque qualquer cabeçalho pode ser alterado ou inserido pelo cliente, neste caso ele poderia incluir um HTTP_CF_CONNECTING_IP arbitrário e enviar a requisição por fora do CloudFlare.
Neste caso, do CloudFlare, apenas autorize o acesso aos IPs do CloudFlare, isso impedirá que alguém se conecte diretamente ao seu servidor e especifique um HTTP_CF_CONNECTING_IP arbitrário, pode ver um exemplo dessa configuração em especifico aqui.
Answer: A maneira mais simples de obter o endereço de IP seria usando a variável $_SERVER, como $_SERVER['REMOTE_ADDR'] ou $_SERVER['REMOTE_HOST']. Entretanto essas 2 variáveis nem sempre retornam o IP correto do usuário/visitante, então pode-se usar outras variáveis, o melhor modo de fazer isso seria criando uma função. Recomendo que olhe o tópico da fonte, mesmo em inglês, para ter uma explicação e ideias até melhores.
De modo básico criando uma função simples:
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

Essa função não é de autoria minha, e sim de um usuário do fórum stackoverflow em inglês, olhe a fonte.

Fonte: Stackoverflow em Inglês
Comment: Essa função é bem perigosa. O `HTTP_CLIENT_IP` e o `HTTP_X_FORWARDED_FOR` são cabeçalhos enviados pelo usuário, que podem ser alterados e manipulados. Inclusive, o `X_FORWARDED_FOR` pode possuir mais um um IP separado por virgula. _Alguém comentou sobre isso na postagem original em inglês também, não com essas palavras, mas fica o aviso aqui._
Comment: é isso mesmo vlw deu certinho aki.
Comment: @Inkeliz Correto, eu vi este aviso, por isso recomendei que dessem uma boa olhada no tópico, já que essa seria a solução mais simples em PHP, mas tem suas ressalvas

Como pegar ip de um usuario usando php?


Resouce in .resx file not visible to MVC code

Question: I have a solution with two projects. One is called Resources and is a collection of resource .resx files for localization. The other is an MVC 5 project that has Resources as a reference. I define a new resource in the .resx file called EmailAddress and sure enough it is in  Resource.Designer,cs:
<code> internal static string EmailAddress {
            get {
                return ResourceManager.GetString("EmailAddress", resourceCulture);
            }
        }
</code>
However, when I try to refernce in my Model class it says it doesn't exist:
<code>[Display(Name = "EmailAddress", ResourceType = typeof(Resources.Resources))]
        [Required(ErrorMessageResourceType = typeof(Resources.Resources),
                  ErrorMessageResourceName = "EmailRequired")]
        [RegularExpression(".+@.+\\..+", ErrorMessageResourceType = typeof(Resources.Resources),
                                         ErrorMessageResourceName = "EmailInvalid")]
        public string EmailAddress { get; set; }
</code>
Also, if I try to do this a Razor View, it doesn't show up in the Intellisense:
<code>@Resources.Resources.
</code>
What is going on? I should also state that the resource file was originally taken from a sample project and the resources that were in it show up but any I add don't (but its the designer cs file).
Comment: Also, when editing your .resx file, is the Access Modifier set to Public or Internal?
Comment: Make sure your project has a reference to your resources project. Also in your view you will need to add the @using statement followed by your projectnamespace
Comment: I have both and it still does not find any that I add. The "original set" is there. I get this error on running with the model the way shown above "Cannot retrieve property 'Name' because localization failed.  Type 'Resources.Resources' is not public or does not contain a public static string property with the name 'EmailAddress'."
Comment: What is the Build Action (under file properties when you select the .resx file) of your resources vs the files from the original sample?
Comment: They are all set to Internal. I don't see how to change this. The ones that work all internal too.
Comment: I changed them all to public and got the same error
Comment: To start with, the .resx will need the [Access Modifier](http://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx) set to Public to be seen outside the assembly. Not sure why that wouldn't fix it in your case. Can you verify that the properties in the Designer file were updated accordingly? Is your reference from MVC to Resource set to the project, or to a snapshot DLL somewhere?
Comment: Yes, they are now set to Public. The reference is set to a class library project (DLL). I am still getting "Cannot retrieve property 'Name' because localization failed.  Type 'Resources.Resources' is not public or does not contain a public static string property with the name 'EmailAddress'.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/59415/discussion-between-mike-guthrie-and-user2471435).
Answer: I had a very similar problem, in my case it was solved by doing 2 things to those resource files:

Set the custom Tool to PublicResXFileCodeGenerator.
Set the build action to "Embedded Resource".
Additionally added the reference in the web.config for the views to the resources in the namespaces section.

After that, it was solved so I was able to call it as "<code>@Resources.Resources.EmailAddress</code>"


Using !{ } and #{ } interpolation in a jade template (exclamation-object, hash-object)

Question: In a jade template (using express over node.js), I see a template using the following syntax:
script(type='text/template', id='data-services') !{data}

I don't understand the !{ } construct; apparently it interpolates a javascript object defined elsewhere as:
var data={ name:"Doe", age:"21" };

Jade docs & tuts show the use of #{ } for interpolation, but I don't see !{ }.  Even #{ } is not documented, so I think it's not jade-specific.  Where does this syntax come from and where is it documented?
Comment: Good question. Quite annoying that jade-lang.com doesn't even explain this!
Comment: It's in the pug documentation now: https://pugjs.org/language/interpolation.html#string-interpolation-unescaped
Answer: Quite difficult to find it, indeed. Have a look at this resource:
http://naltatis.github.io/jade-syntax-docs/#escaping
# is used when you want to escape data and ! when you want it raw.
For example let's say that name = "Hello World". Then you have:
#{name} --> Hello <em>World</em>
!{name} --> Hello World

Think about it like that: # will display name as it is written while ! will treat it as HTML.
Comment: thx freakish, thx naltatis for the missing docs. kind of funny jade forgot to explain interpolation...


Within a View, How do i paginate the content found inside a single Multiple file field, i.e. inside one node

Question: Hopefully someone can help.
I am using a file field and allowing unlimited files within a single content type field called "Video", handled by Media Module. I have created a view per "gallery" of multiple files inside the node, it's already set-up contextually using the nid. Paginating the media files list from this one node result isn't easy to do with what is out there. I have tried infinite scroll but it didn't work out, i have also tried CCK Pager with no luck and the limit settings available are just that limits which don't paginate. Any ideas?
Just to be clear i am not trying to paginate a view of nodes, its a view of files found within a single node.
I am using Drupal 7.63
Answer: There are two obvious ways to solve this, the easier one is through your existing Content views, and the other is through creating a new File type view.
Content type Views
It is true that the Views type determines what will go into each new row in views results, and Pager is acting on views rows.
But if you have a multi-value field it is possible to make it display each value in a separate views row, making the same node appear many times in the views results, as many times as there are field values.
Here's how you do it:

Edit your "Videos" field and under Multiple field settings make sure you don't have the Display all values in the same row option enabled.

This will make the same node repeat as many times as you have videos, and although the Pager will still work on node rows, it will look like it's working on field values (if you're only showing that one field and not revealing the node Title, for example).
File type Views
To get the Pager to actually page through individual files you have to create File views. There are some steps how you can make that views pull data from one content type and field:

The File views starts by displaying file names of all the files on the system. To make it aware of where the file is being used (you want only the Videos) add a Relationship File: Content using Videos and make it required. This will filter out only the files that are in the "Videos field", and it will make available various Content related Fields and Filters.
Add the "Content: Videos" Field and set it so it doesn't display all values in the same row. You will still see the files repeated in the results.
Don't add any File Fields
Under Query settings enable Distinct and Pure distinct. This will make each file display only once.
Add the Contectual filter for NID, it will be available because of the Relationship you added and it will use it by default.
Comment: I did add the Description as a Field to see what would happen but the default result was the description was shown multiple times, as you suggested. I'll try out the Grouped idea but the 'Global:View area' worked well and find it intuitive and far more adaptable to different needs, i imagine. The more i delve into Drupal the more powerful it seems to be.
Comment: Hi Prkos, Thank you so much... lifesaver. I'm currently implementing your Content type Views approach and it's working like a charm. In order to allow for a node description to come through at the top of the view list i'm using https://www.drupal.org/project/views_block_area to allow the fields i need to appear once on the views page... haven't got this to work as yet, need the block to receive the nid to be able to display the description.
Comment: Ok, I did not need the "views_block_area" module, instead, the default 'Global: View area' inside the view "header" worked. I created a separate views block which contextually only displayed the node description based on the nid, saved this. I then went back to my views page and added the  'Global: View area' inside the header. IN the settings I selected the 'block view with description' from the drop down, checked the box "Inherit contextual filters" and applied. The description was generated in the first listed position, this can be themed to behave as needed.
Comment: Yes, that's the way to do that, you seem to have Views covered :) I haven't tried this but I'm wondering if you could have added the Description as a Field and then Grouped under Format, but I expect that would still mess up Pager.


What is the hook to alter links in the Book Outline tree?

Question: What is the theme hook to alter links in the book outline like theme_menu_link__menu does for menus?  Or is there a way to make theme_menu_link__menu apply changes to a tree view of the Books?  Not the book navigation but the Outline.
Answer: Turns out there isn't one.  Had to go back to an ajax approach and update the book outline in the client browser.


How can I trigger a BroadcastReceiver on Android 11 using adb?

Question: I have two receivers I want to trigger manually and I can't seem to do it. These are the commands I'm using:
adb -s deviceid shell am broadcast -a action android.intent.action.PHONE_STATE
or
adb -s deviceid shell am broadcast -a action android.intent.action.MEDIA_BUTTON
I've tried adding -p mypackage or -n mypackage/myreceiver and they never get triggered. I also don't see anything on logcat. Adb returns result=0, not sure what that means.
Answer: Try this.
adb -s deviceid shell am broadcast -a android.intent.action.VIEW -n com.mypackage.broadcast/com.mypackage.broadcast.Broadcaster

Example of broadcast class.
import android.content.*;
import android.widget.*;

public final class Broadcaster extends BroadcastReceiver
{
    @Override
    public final void onReceive(final Context context, final Intent intent) {
        intent.setClass(context, Starter.class);
        //Note: without this flag android will throw a runtime exception.
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        try {
            context.startActivity(intent);
        } catch (final Exception e) {
            Toast.makeText(context, e.getMessage(), 1) .show();
            forceStop();
        }
        forceStop();
    }

    private final void forceStop() {
        clearAbortBroadcast();
        //throw new RuntimeException();
        System.exit(0);
    }

}

Starter.java //Class that you want to start
public final class Starter extends Activity {
     @Override
      protected final void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Do something
      }
}

And dont forget to put this inside your manifest.
 <application
android:noHistory="true"
android:launchMode="singleInstance"
android:excludeFromRecents="true"
android:exported="true"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent.NoTitleBar">

    <receiver
        android:name="com.mypackage.broadcast.Broadcaster"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="*/*" />
            </intent-filter>
    </receiver>
...

Comment: This worked but with `-n` not `-p`. I'll mark it as correct, hopefully you'll edit it or others will see this comment.


Intersection, having some problem solving for Y? Do I have to solve for Y?

Question: $3y=\frac{x}{x-y}$
$x+4y=2x$
The top equation is the problem. But I think I've solved it correctly for x
$\frac{1}{3y} = \frac{x}{x}-\frac{y}{x}$
$\frac{1}{3y} = 1-\frac{y}{x}$
$\frac{y}{x} = 1-\frac{1}{3y}$
$\frac{X}{Y} = 1-3y$
$x = y-3y^2$
Put the X equal to eachother and solve for Y?
$y-3y^2 = 4y$
$-3y^2-3y=0$
That gives Y values $-1$ and $0$, which is not correct. So do I have to solve for Y first and find X-values or did I do a mistake somewhere?
http://www.wolframalpha.com/input/?i=3y%3Dx%2F%28x-y%29%2C+x%2B4y%3D2x
Comment: Is the recreational-math tag really appropriate? Wouldn't algebra-precalculus be better?
Comment: As a matter of solving strategy, it seems better **first** to use the second equation to conclude that $x=4y$, and then to substitute for $x$ in the first equation.
Answer: $\frac{y}{x} = 1-\frac{1}{3y}$  implies $\frac{x}{y} = \frac{1}{1-\frac{1}{3y}}$ , not $\frac{x}{y} = 1-3y$.
Comment: That explains a bit, thanks.
Answer: $3y=\frac{x}{x-y} /(x-y) $ multiply by $(x-y) $ both sides so we get
$3y(x-y)=x$
From the second equation we may conclude that $x=4y$   ,If we substitute $x$ with $4y$ at the first equation we may write
$3y(4y-y)=4y \Rightarrow 9y^2-4y=0 \Rightarrow y(9y-4)=0$ , so: $y_1=0$ and $y_2=\frac{4}{9}$  which means that $x_1=0$ and $x_2=\frac{16}{9}$   ,Since $x-y\neq0$ only solution is $(x_2,y_2)=(\frac{16}{9},\frac{4}{9})$


Delayed internet access

Question: When I (and presumably my users) first start up or log in to my computer I can't get internet access until several minutes after logging in.  Internet pages like serverfault.com will time out.  During this time I can access internal web servers.  Sometimes pinging the gateway seems to fix the problem.
I'm using Windows 7 on this machine with wifi, and the problem seems limited to the wifi network, which is on a separate vlan.  The wired network does not share the problem, but I know it's not the wifi connection itself because the internal sites work.
The wifi access point is attached to a 3Com 4200 switch, with the port set for vlan 2 untagged, vlan 1 tagged.  The 4200 has a fiber connection to a 3Com 4900SX fiber switch that acts almost as a router here.  The fiber connection is vlan 1 untagged vlan 2 tagged at both ends. The gateway is then attached to a different 4200 (vlan 1 untagged, vlan 2 tagged) that has a similar fiber connection to the 4900SX.
vlan 2 has 192.168.8.0/22 IPs, vlan 1 has 10.1.0.0/16 IPs. The 4900SX has an interface for both vlans (10.1.1.1/192.168.8.1), as does the gateway (10.1.1.5/192.168.8.5).  There is one dchp server for both vlans on the same switch as the gateway.  It chooses a dhcp scope based on the interface used by the 4900sx to forward the dhcp request.
There is also a network access list on the 4900sx set to deny all vlan2 traffic to any 10.1.x.x host, with exceptions made for a few servers, including dhcp, 4900sx, and the gateway.
I think that about covers it.  Any ideas on why internet access would be delayed like this?
Answer: This sounds like a DNS issue.  More specifically, DNS queries are initially being sent to a server that is not responding (it could be down, not have a known route from the WiFi access point, an old server that no longer exists, etc.).  Once the initial queries time out, another server is tried and eventually, one works.  From that point, DNS queries go to the working server and you're OK.  Internal sites work because you're using a different address server, such as Active Directory.
So, next time you connect to the WiFi point, check the DNS connection.  A simple nslookup or dig may be enough to see which server is being tried and which one finally responds.
Comment: This was part of it.  The main thing is that my computer had the "Autodetect proxy settings" option checked, and so spent a while trying to do that after a restart.  But I also found a dns error on the secondary dns server, which is for some reason occasionally preferred by wireless connections.

Delayed internet access


Can I safely use tracers with precision barrel?

Question: I know precision barrels require high-quality BBs (strict size tolerances).
There are "Tracer" BBs that when exposed to bright light (or used with a special "silencer" that flashes bright light at BB passing through it), shine in the dark. Unfortunately these exist "besides" the normal classification of BBs by quality and obviously are more expensive due to the gimmick, so even the price isn't an indicator - in effect I have no clue if they are of quality high enough to use with precision barrels. Are they?
Answer: Technically precision barrels do not require high quality BBs. They require BBs that are spherical in shape and smaller than the bore diameter. There is nothing wrong with low cost or low quality BBs so long as they are not defective BBs as in they possess physical defects like dents, cracks, seams, are not spherical, or are  dirty.
To determine whether a BB can be shot through your barrel is to measure the BB and the bore with a caliper that reads out in 0.01mm or 0.001". Alternatively a micrometer may be used, although the extra precision isn't really needed.
If the BBs are of dubious quality, it may be wise to measure all of them, or random select a large number and check for any measuring larger than bore diameter.
Worst case the BB is larger than bore diameter, it will only get stuck, can be removed by cleaning rod or other rod like tool, and will not damage the barrel because plastic is softer than the steel or brass barrel.
Another potential issue with oversized BBs is safety in airsoft play. Larger BBs means tighter fit with bore, meaning less air rushes past the BB that results in higher velocity and higher energy that may be beyond field limits, especially if the gun passes chrono test with smaller BBs. The effect is increased further if the gun has a tight bore or a precision barrel installed, further reducing the gap between BB and barrel, and can result in significant increases in velocity and energy well beyond field limits. Different fields, locales and countries treat this problem differently. Some parts of the US they don't care, most of Europe will permanently ban you whether you knew or not.
Comment: Unfortunately in this case **quality** means **repeatability**. If I'm buying 5000 BBs of high quality, I'm sure all of them will pass through the barrel. If I'm buying "economy" ones, I can expect about 5 in the batch to be off-standard and jam. And calipers measure only in one axis. So, at least 3 measurements per BB, 15,000 measurements for the batch, all by hand? Not my idea of fun! That's why you either use a standard barrel, where all but total crap ones will fit, or you pay premium for high-quality, where industrial QA assures none will jam.


Cohen's Kappa using (irr) and kappa2() outputs z and p-value with NaN

Question: I used the kappa2 function from the irr-library in R, however it returned an invalid z- and p-value and a kappa value of exactly 0. I already looked it up and stumbled upon this article Cohen's Kappa using (irr) and kappa2() outputs NaN, but over there the measurements are exactly the same while in my measurements (see in code below) it is not exactly the same.
I ran this code:
rm(list=ls());
library("irr")

a = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1)
b = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
kappa2(cbind(a, b))

And this output:
Cohen's Kappa for 2 Raters (Weights: unweighted)

 Subjects = 36
   Raters = 2
    Kappa = 0

        z = NaN
  p-value = NaN

Does anyone have an idea what goes wrong here?
Answer: Cohen's Kappa is

where in which p0 is the observed agreement between your prediction and the actual labels. pc is the randomly expected match, which is usually the proportion of label you are trying to predict. For example, if your dataset is balanced, then by chance you expect 0.5. If one of them takes up 90%, it will be 0.9
In your case, I don't know if you mixed up the prediction and reference, the reference (b) is all 1s. So pc = 1 and you end up with Inf.
Comment: I am not sure I completely understand, as I understood it the Cohens kappa is used to calculate inter-rater reliability between equally important raters. So, should the calculation not be interely symmetric?
Comment: well.. let's put it this way, if one of your rating system gives all 1, either something is rong with the rating, or you should not be using this cohen's kappa at all.
Comment: I deleted my other comments because in hindsight they were kinda stupid. Thanks a lot, I will look if I did something wrong when in processing my results. Otherwise, do you have any advice as which method would work better to solve this?
Comment: The data was indeed wrong.


Send stderr/stdout messages to function and trap exit signal

Question: Im working on error handling and logging in my bash script. Below I have included a simplified code snippet that exemplify the use case.
I want to achieve following in my script:

trap exit signals which should trigger onexit() function in the code below
stderr and stdout should be sent to the log() function which will make sure to log the output to an log file according to specific log format (simplified in the example below)

Issue with current code below:

Step 1 is not trapped by onexit function and script is continuing to Step 2. Most probably because stderr is piped to logStd(). How can I send error messages to logStd() but still trap the exit signal in onexit()?

Resolution:

Add set -o pipefail
Get exit status on onexit() by adding local exit_status=${1:-$?}

script.sh (edited after resolution)
#!/bin/bash -E
set -o pipefail

# Perform program exit housekeeping
function onexit {
    local exit_status=${1:-$?}
    log "onexit() called with param: $exit_status"
    exit $1
}

# Simplified log function that sends input parameter to echo. This function is used within this script
# In real case this function would send log statement to log file according to specific log format
function log {
    echo "log(): $1"
}

# Simplified log function that reads input stream and sends to log
# This function is used from commands
function logStd {
    log "logStd() called"
    while IFS= read -r line; do log "$line"; done
}

# http://linuxcommand.org/wss0160.php
# The trap command allows you to execute a command when a signal is received by your script.
# Usage: trap arg signals
# "signals" is a list of signals to intercept and "arg" is a command to execute when one of the signals is received
# arg can either be a command or a function name like clean_up below
trap onexit 1 2 3 15 ERR

# STEP 1 - should fail, send errors to logstd() and be trapped by onexit()
log "**Tarballing should fail, file doesn´t exist"
tar -czf /Users/ismar.slomic/shellscripting/unknownfile.txt.gz /Users/ismar.slomic/shellscripting/unknownfile.txt 2>&1 | logStd

# STEP 2 - should run successfully and send "tar: Removing leading '/' from member names" to logStd()
log "**Tarballing should run successfully"
tar -czf /Users/ismar.slomic/shellscripting/file.txt.gz /Users/ismar.slomic/shellscripting/file.txt 2>&1 | logStd

onexit

output:
log(): **Tarballing should fail, file doesn´t exist
log(): logStd() called
log(): tar: /Users/ismar.slomic/shellscripting/unknownfile.txt: Cannot stat:  No such file or directory
log(): tar: Error exit delayed from previous errors.
log(): **Tarballing should run successfully
log(): logStd() called
log(): tar: Removing leading '/' from member names
log(): onexit() called with param:

Answer: You have to use
set -o pipefail

See this related StackOverflow Question.

Minimal example:
#!/bin/bash

trap handler ERR
handler() { echo trapped ; }

echo 1
false | :

echo 2
set -o pipefail
false | :

Output:
$ bash test.sh
1
2
trapped

Comment: Thanks, this did work. However, the exit code in onexit() function is 0. Based on the thread you referred to this is because exit signal for rightmost command is returned, which in my case is logStd(). How could I end up with non-zero signal in onexit() for this use case?
Comment: @IsmarSlomic: Bash does not pass the signal in `$1` to your `onexit()`function as you may have expected. So the `pipefail` setting has no effect on this. If you need to differentiate on the signal receive, you have to use different traps for each one.
Comment: I am able to differentiate the different signals by using `local exit_status=${1:-$?}` in the `onexit()` function. I have updated my script now. Thanks a lot for support!
Comment: You're welcome, great it worked out. I just suspect you could have written `$?` instead of `${1:-$?}` as I can't see any case where something else is passed into `onexit()`.


Installing Soap extension for PHP 8.1 issue

Question: I have PHP 8.1 installed in Ubuntu 18.04.06.
Now i am trying to install soap extension for PHP 8.1 using following command
sudo apt install php8.1-soap
But I get following error
E: Unable to locate package php8.1-soap
E: Couldn't find any package by glob 'php8.1-soap'
E: Couldn't find any package by regex 'php8.1-soap'

I also tried adding, but same error
sudo apt update
sudo add-apt-repository ppa:ondrej/php
sudo apt install php8.1-soap -y
sudo apt update

Is this because my Ubuntu version is old? How can i install soap extension compatible to php 8.1
Thanks
Comment: This is because  Ubuntu U18.04 is not supported. Try: 'add-apt-repository ppa:ondrej/php '/. Or update your version Ubuntu
Comment: Does `apt search php soap` show the package?
Comment: @brombeer Yes it shows but `php 5.6-soap` and `php7.0-soap` only
Comment: Strange. Have you installed PHP8.1 recently? Does `apt search php8.1` show the package `php8.1-common` (or any 8.1 package)? Could be you installed PHP8.1 some time ago but support for Ubuntu18.04 has been dropped, just a guess
Comment: try:'sudo apt install php8.1-dev'
'sudo pecl install soap'
Comment: @brombeer search gives many php8.1 packages including `php8.1-common`
Comment: @ЛюбомирГорбей I get same error  `Unable to locate package php8.1-dev`
Comment: update your version Ubuntu , otherwise you will have such problems in the future
Answer: As far as I think you have not ppa:ondrej/php in your system. That's why you are getting this package not found error. You can learn below command
sudo apt update
sudo add-apt-repository ppa:ondrej/php
sudo apt install php8.1-soap -y
sudo apt update

Comment: Thanks for the reply, I added that too, still not working
Comment: very strange situation.
Comment: Can you update your system or it is not possible?
Comment: Wouldn't OP already have `ppa:ondrej/php` to install PHP8.1?
Comment: ppa:ondrej/php is enough for installng all php extensions such as curl, zip, mbstring, intl, json, soap etc. But why your system don't getting extension, it is totally strange


Use listener container for heartbeats in spring kafka

Question: I'm trying to set up container to listen to heartbeat topic - I'm only interested when the listener container is idle - Is it possible to configure the container without @KafkaListener and with only EventListener to listen to idle event ? Is it possible to set up seek in the idle event listener to get the last message from the topic for context information  like time and other details ?
Is there a event to know the consumer has starting consuming after the idle event without needing to use @KafkaListener ?
Answer: There is no event that consumption has restarted.
It's not clear what you mean by "without needing to use @KafkaListener"; you can create your own listener...
@SpringBootApplication
public class So63957429Application {

    public static void main(String[] args) {
        SpringApplication.run(So63957429Application.class, args);
    }

    @Bean
    public ConcurrentMessageListenerContainer<String, String> container(
            ConcurrentKafkaListenerContainerFactory<String, String> factory, MyListener myListener) {

        ConcurrentMessageListenerContainer<String, String> container = factory.createContainer("so63957429");
        container.getContainerProperties().setMessageListener(myListener);
        return container;
    }

    @Bean
    public NewTopic topic() {
        return TopicBuilder.name("so63957429").partitions(1).replicas(1).build();
    }

    @Bean
    public ApplicationRunner runner(KafkaTemplate<String, String> template) {
        return args -> template.send("so63957429", "foo");
    }

}

@Component
class MyListener extends AbstractConsumerSeekAware implements MessageListener<String, String> {

    @Override
    public void onMessage(ConsumerRecord<String, String> record) {
        System.out.println(ListenerUtils.recordToString(record, true));
    }

    @EventListener
    public void listen(ListenerContainerIdleEvent event) {
        System.out.println("Idle; rewinding to last");
        getSeekCallbacks().forEach((tp, callback) -> callback.seekRelative(tp.topic(), tp.partition(), -1, true));
    }

}

spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.group-id=so63957429
spring.kafka.listener.idle-event-interval=5000

so63957429-0@0
Idle; rewinding to last
2020-09-18 10:50:54.408  INFO 17195 --- [container-0-C-1] o.a.k.clients.consumer.KafkaConsumer     : [Consumer clientId=consumer-so63957429-1, groupId=so63957429] Seeking to offset 0 for partition so63957429-0
so63957429-0@0
Idle; rewinding to last
2020-09-18 10:50:59.436  INFO 17195 --- [container-0-C-1] o.a.k.clients.consumer.KafkaConsumer     : [Consumer clientId=consumer-so63957429-1, groupId=so63957429] Seeking to offset 0 for partition so63957429-0
so63957429-0@0

EDIT
If you need to access the last consumed record, you can add a RecordInterceptor:

    @Bean
    public ConcurrentMessageListenerContainer<String, String> container(
            ConcurrentKafkaListenerContainerFactory<String, String> factory, MyListener myListener) {

        ConcurrentMessageListenerContainer<String, String> container = factory.createContainer("so63957429");
        container.getContainerProperties().setMessageListener(myListener);
        container.setRecordInterceptor(myListener);
        return container;
    }

@Component
class MyListener extends AbstractConsumerSeekAware implements MessageListener<String, String>,
        RecordInterceptor<String, String> {

    private ConsumerRecord<String, String> lastRecord;

    @Override
    public void onMessage(ConsumerRecord<String, String> record) {
        System.out.println(ListenerUtils.recordToString(record, true));
    }

    @EventListener
    public void listen(ListenerContainerIdleEvent event) {
        System.out.println(event);
        System.out.println("Last Record: " + ListenerUtils.recordToString(this.lastRecord, true));
//      getSeekCallbacks().forEach((tp, callback) -> callback.seekRelative(tp.topic(), tp.partition(), -1, true));
    }

    @EventListener
    public void listen(ListenerContainerNoLongerIdleEvent event) {
        System.out.println(event);
    }

    @Override
    @Nullable
    public ConsumerRecord<String, String> intercept(ConsumerRecord<String, String> record) {
        return this.lastRecord = record;
    }

}

If you have concurrency > 1, you will need to store the last record in a ThreadLocal.
Comment: No; you can't read the last record in the event listener - in any case, you won't know which partition the last record came from. The idle event has the `idleTime` property which starts when the previous `poll()` returned some records. I added a [pull request](https://github.com/spring-projects/spring-kafka/pull/1592) to publish an event when consumption resumes, but it sounds like that won't really help your use case. You could add a `RecordInterceptor` to the listener container to grab and save off the last processed record so it's available in your event listener.
Comment: See the edit to my answer to see how to capture the last consumed record.
Comment: Thanks Gary - It definitely helped but if I may ask you a follow up question. I have a set up where I track how long the topic is idle and based on configured threshold I generate alerts. Is it possible to consume the last message in the idle event method itself ? Also I need to know when the consumption has restarted so I can reset the alert   - do you think if there is way to reset alert ? I dont want to keep resetting on the onMessage everytime . do you think its worthwhile to add a consumption restarted event  ?
Comment: In my case I really don't care about messages so would like to avoid reading them at my side  - I only care about last message before
 the idle event occurred.


Force all items in list in each row to have the same height (each item has dynamic height)

Question: I have a list of items
, the number of items in the list is dynamic, and the content as well. The list has 4 items per row, define by float:left. The height of each item is dynamic , and as a result the item in the next row gets "stuck" just before the highest item on the above row. Its results in a visually ugly list, and rows not being populated.
How can I force all the items in each row to be the height of the highest row? or, how to force all the items in the list to be the height of the highest items in the list?
Thanks
UPDATE:
The final solution is:


Required taxonomy term fields for node publishing?

Question: I want to create content which has shared some aspects. I am doing this through a taxonomy reference. The taxonomy has certain fields that describe each piece of content (in my case used cars).
In my workflow, I only want the content published if the taxonomy term reference has all its fields filled out. How can I automate this workflow?
Comment: Hard to understand what it is you're asking. Please clarify the question. At the moment, it's muddled up between taxonomy and node types, they're just referred to as Type A and Type B. Please make those distinctions at least.
Answer: This is a workflow requirement that can be handled by Rules.

Set your user car type set to unpublished by default.
Create a rule for the event Before saving content of type User Car (or whatever your node type is called)
Add a Data value is empty condition. On the Data selector you'll want something like node:field-MYTERM_FIELD:0:field-MYREQUIRED_FIELD (it depends on your field names). Make sure to check the Negate checkbox so that the rule is triggered when the taxonomy field IS NOT empty.
Add a Publish Content action.
Comment: Thank you, much more simple and maintable than the custom module I suspected it would take.
Comment: No problem. Rules is a powerhouse for enforcing workflow. I edited the question to get toward the core of your answer (and less about the concrete nature of what you're content is describing). Make sure to mark the question as answer to help out future users.