Ordinary kriging stationary case

Question: I am trying to understand ordinary kriging.
Say I have 3 elevation measurements: Z1, Z2, and Z3 taken at X positions: X1, X2 and X3.
I am also assuming some semivariogram: g(h) and that the process is stationary.
From what I understand the kriging weights in this case should be ?:
$ L = M^{-1}*Gs $
Where:
$L=\ \left( \begin{array}{ccc}
l_1 \\
l_2 \\
l_3 \\
\mu\end{array} \right) $
$\
M = \left( \begin{array}{ccc}
g(0) && g(X2-X1) && g(X3-X1) && 1 \\
g(X2-X1) && g(0) && g(X3-X2) && 1 \\
g(X3-X1) && g(X3-X2) && g(0) && 1 \\
1 && 1 && 1 && 0 \end{array} \right)$
$Gs=\ \left( \begin{array}{ccc}
g(|X1 - Xs|) \\
g(|X2 - Xs|) \\
g(|X3 - Xs|) \\
1
\end{array} \right) $
And the elevation Zs at x position Xs should be estimated by ?:
$\ Z(Xs)=\sum_{i=1}^3 l_i*Zi$
Will the inverse of the matrix pose a problem?
I found a Matlab script on the internet that was using "Moore-Penrose pseudoinverse" instead.
The reason I am asking this question is that I coded a Matlab script on this which drew random X and Z; and it seemed to work just fine most times, but every now and then it returned a "crazy" estimate for Z(Xs).
So I am just trying to understand if I have misunderstood the theory, if the inverse of the matrix sometimes become "ill posed" or if I have just tripped up in my Matlab coding.
Here is my Matlab script:
<code>% kriging.m
n = 3;
X = 1000*rand(1,n);
Z = 1000 + 100*randn(1,n);
stem(X,Z,'b');
hold on;

a0 = 300; % range
c0 =   4; % scale

M = ones(n+1,n+1);
for r = 1 : n
    for c = 1 : n
        Xr = X(r);
        Xc = X(c);
        h = abs(Xr - Xc);
        M(r,c) = c0*(1-exp( -(h/a0)^2 ));
    end
end
M(n+1,n+1) = 0

MI = inv(M)

Xs = 500;
hs = abs(X - Xs);
Gs = c0*(1-exp( -(hs/a0).^2 ));
Gs = [Gs 1]'

L = MI*Gs;
L = L(1:n)

Zs = Z*L

stem(Xs,Zs,'r')
</code>
And here is an example of an crazy result:
<code>X =

  117.4177  296.6759  318.7783

Z =

  1.0e+003 *

    0.9679    1.0012    0.6971

M =

         0    1.2010    1.4508    1.0000
    1.2010         0    0.0217    1.0000
    1.4508    0.0217         0    1.0000
    1.0000    1.0000    1.0000         0

MI =

   -0.8331    5.2214   -4.3883    1.0956
    5.2214  -55.8175   50.5960   -6.3666
   -4.3883   50.5960  -46.2077    6.2710
    1.0956   -6.3666    6.2710   -1.4516

Gs =

    3.2134
    1.4732
    1.2229
    1.0000

L =

    0.7441
   -9.9423
   10.1982

Zs =

 -2.1255e+003
</code>
Comment: If you are using a valid semivariogram, you should never run into these difficulties. However, for certain data configurations and certain variograms you can get *close* to singular matrices. (I have never seen kriging software that uses a pseudoinverse--that would be appropriate only when data fall on a regular grid or when all data are used at once; directly solving the system $ML=G_s$ is more stable and far more efficient in most applications.) What semivariogram are you using that causes problems? BTW, did you really mean to put absolute values in the expression for $G_s$ but not in $M$?
Comment: Gaussians can produce such strange results, Andy: because they and their derivatives are zero at the origin, they impose extreme smoothness on the kriged estimates. In the bottom picture, fitting a smooth spline (as a proxy for the kriging) clearly would extrapolate high values in the 150-250 range. Such extrapolation requires weights beyond the 0-1 range. The extremely low value you have plotted at 500 similarly looks consistent with the data and variogram.  Why not experiment first with an exponential variogram (and add a tiny nugget to it)?
Comment: Hi whuber. Thanks for the help! I am using a Gaussian semivariogram.
Comment: Thanks. I understand now that the result value is not so crazy after all. Besides I want to do interpolation, not extrapolation so this case is not so important.
Answer: Pseudo inverses are used when the matrix is not of full rank and hence a true inverse does not exist meaning also that there is not a unique solution.  Taking a Moore-Penrose psuedoinverse is a way of picking a particular solution.  You can Google Moore-Penrose pseudoinverse and I bet you will find out alot about it. If you use it as a key phrase using this sites search engine you will probably find places where it has appeared in previous questions.
Comment: I am not an expert on this.  You probably know a lot more than me and maybe have read Michael Stein's book where I have it collecting dust on my book shelf. The point that we both can agree on is that figuring this out requires more details from the Matlab writeup and/or more experimentation with the data
Comment: The kriging equations are set up to guarantee that the matrix $M$ is always of full rank, Michael.  It is an error to use a semivariogram $g$ that would produce a singular $M$. This issue is likely tangential to understanding OK and the Matlab script.
Comment: My comment was made because the OP mentioned a Moore-Penrose pseudoinverse.  The Moore-Penrose inverse is a generalized inverse.  You wouldn't be using it if M was nonsingular!
Comment: Here:  Look at this which was obtained by googling Moore-Penrose Inverse and finding this Wikipedia source. In mathematics, and in particular linear algebra, a pseudoinverse A+ of a matrix A is a generalization of the inverse matrix.[1] The most widely known type of matrix pseudoinverse is the Moore–Penrose pseudoinverse, which was independently described by E. H. Moore[2] in 1920, Arne Bjerhammar [3] in 1951 and Roger Penrose[4] in 1955.
Comment: Contiuation of quote from Wikipedia:  Earlier, Fredholm had introduced the concept of a pseudoinverse of integral operators in 1903. When referring to a matrix, the term pseudoinverse, without further specification, is often used to indicate the Moore–Penrose pseudoinverse. The term generalized inverse is sometimes used as a synonym for pseudoinverse.
A common use of the Moore–Penrose pseudoinverse (hereafter, just pseudoinverse) is to compute a 'best fit' (least squares) solution to a system of linear equations that lacks a unique solution (see below under Applications).
Comment: Final continuation of Wikipedia quote: Another use is to find the minimum (Euclidean) norm solution to a system of linear equations with multiple solutions. The pseudoinverse facilitates the statement and proof of results in linear algebra.
Comment: @whuber Sorry Bill I misread your post. But the mention of the Moore-Penrose inverse in the Matlab post is an indication of an error there. But what makes kriging so special that you could guarantee a unique solution based on three points?  Couldn't the data cause a singularity with spatial fitting just like the design matrix can do in ordinary least squares regression?
Comment: Michael, notice that the elevations themselves are not involved in the matrix equations. The matrix elements depend entirely on the geometric configuration of the sample locations. It is a *requirement* of kriging that the "semivariogram" $g$ be such that *for all possible configurations* of distinct points, $M$ be positive-definite and therefore nonsingular. The presence of a pseudoinverse in the algorithm therefore smacks of papering over a deeper problem, such as using an invalid or unstable variogram.

Ordinary kriging stationary case


Disable ComboBox of a UserControl from another UserControl without MVVM

Question: I have a UserControl Person_UC and Student_UC. There is a ComboBox in Student_UC which I want to disable it from Person_UC.
But its not working. I want to accomplish this without MVVM.
public partial class Person_UC : UserControl
{
    public Person_UC()
    {
        InitializeComponent();
        Student_UC su = new Student_UC();
        su.myComboBoxName.IsEnabled = false;
    }
}

Comment: What do you mean by doesn't work exactly? You get any error message?
Comment: Is there a postback happening of any sort between this enabled change? Does this postback affect said combobox? Maybe sequence of execution here prevents the combobox from being changed. Why not create a global var that handles the combobox?
Comment: this Student_UC usercontol is inside the Person_UC or out side the Person_UC.
Comment: @JobyJames outside, they are two different UCs
Comment: @user2946329 Didn't get any error, it just does not disable the control
Comment: don't create new object of the StudentUC, Use the existing object of the StudentUC
Comment: How can I access existing object of the StudentUC when there is none to access ?
these are two different UC in two different folder of my solution
Answer: Without MVVM it would be quite hard to solve. You have to manipulate the same instance of Student_UC which is currently used.
Actually, you're instantiating a new Student_UC and disabling its ComboBox, but you're not doing anything with your variable "su". Did you assign it somewhere?
Basically, you should have one ViewModel per UserControl, so a ViewModel for Person_UC and a ViewModel for Student_UC.
Warning, this solution requires you to use a MVVM Framework like MVVM Light (https://mvvmlight.codeplex.com) for sending messages.
One standard way would be sending a message. Bind your Loaded event of your Person_UC to a method in your code-behind like so:
<UserControl x:Class="YourAssembly.Person_UC"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Name="Person_UC"
        Loaded="Loaded">

    <Grid Name="RootGrid">
    </Grid>
</UserControl>

And:
public partial class Person_UC : UserControl
{
    public Person_UC()
    {
        InitializeComponent();
    }

    private void Loaded(object sender, RoutedEventArgs e)
    {
        //Use a Message to notify your Student_UC's ViewModel that you would like to disable its ComboBox
       Messenger.Default.Send<ChangeComboBoxEnabilityMessage>(new ChangeComboBoxEnabilityMessage(false));
    }
}

Then, when you receive the message within the Student_UC's ViewModel, you have to pass this information to the view. Basically, you can bind IsEnable property of the ComboBox to a property in its ViewModel, that you will set to false when the message is received.
public class Student_UC_ViewModel : INotifyPropertyChanged
{
    public Student_UC_ViewModel()
    {
        //Register your message
        Messenger.Default.Register<ChangeComboBoxEnabilityMessage>(message => ComboBoxIsEnabled = message.ComboBoxIsEnabled);
    }

    private bool _comboBoxIsEnabled;
    public bool ComboBoxIsEnabled
    {
        get
        {
            return _comboBoxIsEnabled;
        }

        set
        {
            _comboBoxIsEnabled = value;
           OnPropertyChanged("ComboBoxIsEnabled");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

And your message class:
public class ChangeComboBoxEnabilityMessage : MessageBase
{
    public ChangeComboBoxEnabilityMessage(bool comboBoxEnabled)
    {
        ComboBoxIsEnabled = comboBoxEnabled;
    }

    public bool ComboBoxIsEnabled
    {
        get;
        set;
    }
}

I let you bind your IsEnable property of your ComboBox in your Student_UC xaml to the property of its ViewModel (i.e ComboBoxIsEnabled).
Don't forget to make sure your DataContext is set:
public partial class Student_UC : UserControl
{
    public Person_UC()
    {
        InitializeComponent();
        DataContext = new Student_UC_ViewModel();
    }

    ...
}

Also, take care of your binding issues, see your output console in Visual Studio.


Cannot append date to a filename

Question: Good morning,
Why I cannot append date to a filename when saving a dataframe to excel? Here is my code.
date = '24/12/2020'
datetime_object = datetime.strptime(date, '%m/%d/%Y')

writer = pd.ExcelWriter('Weekly_Report_'+date+'.xlsx', engine='xlsxwriter')
df.to_excel(writer,sheet_name='Scheduled Report', index=False)
writer.save()

The error is:
FileNotFoundError: [Errno 2] No such file or directory: 'Weekly_Report_24/12/2020.xlsx'

Answer: You are attempting to include forward slashes in the file name which is prohibited. Use some other character such as '-' as a separator in the date (e.g. 24-12-2020).
Read more - Is it possible to use "/" in a filename?

Cannot append date to a filename


I can't add my list to lazycolumn. how can i add

Question: I'm adding my notes in "items" but I'm getting this error. I couldn't find the reason, can you help?
@Composable
fun NotesList() {
    val notesList = remember { mutableStateListOf<Note>() }
    LazyColumn {
        items(notesList) {note->
            NoteCard(note.title, note.content,note.color,note.liked)
        }
    }
}

When I hover the cursor over noteList I get the following error.
Type mismatch.
Required:Int
Found:SnapshotStateList
I was hoping it would work by adding my list to items but it didn't.
Answer: Adding this import should fix that:
import androidx.compose.foundation.lazy.items

This is because the fun items(count: Int) function is a member function of LazyListScope but the fun <T> LazyListScope.items(items: List<T>) is an extension function of LazyListScope. Therefore, you don't need any import to use the first one, but you need that import to use the second one. If you (or Android studio) doesn't add the import, the one with count is automatically used and it doesn't work when you pass list instead.
Comment: Error fixed, thank you very much.
Comment: damn, i thought i was going crazy, thanks for the solution


how to correctly append xml child elements in php

Question: I'm trying to iterate over an array of movie names and am struggling as shown below. I've included the actual output vs expected output.  thanks!
$root = new SimpleXMLElement('<movies/>');
$movies = ['foo', 'bar'];
foreach($movies as $movie_name){
    $movie_el = buildMovieTag($movie_name);
    $root->addChild($movie_el->asXML());
}

function buildMovieTag($name){
    $movie_tag = new SimpleXMLElement('<movie/>');
    $movie_tag->addChild('name', $name);
    return $movie_tag;
}

I'm expecting this:
<?xml version="1.0"?>
<movies>
<movie><name>foo</name></movie>
<movie><name>bar</name></movie>
</movies>

but am getting this:
<?xml version="1.0"?>
<movies><<?xml version="1.0"?>  // extra xml tag
<movie><name>foo</name></movie>
/><<?xml version="1.0"?> // extra xml tag
<movie><name>bar</name></movie>
/></movies>

Answer: The new SimpleXMLElement then asXML() is the issue.
addChild is enough to make the element then its return value is the node, then subsequent addChild's on the node make the children.
<?php
$root = new SimpleXMLElement('<movies/>');
$movies = ['foo', 'bar'];
foreach($movies as $movie_name) {
    $movie = $root->addChild('movie');
    buildMovieTag($movie, $movie_name);
}

function buildMovieTag($node, $name) {
    $node->addChild('name', $name);
}

echo $root->saveXML();

<?xml version="1.0"?>
<movies><movie><name>foo</name></movie><movie><name>bar</name></movie></movies>

Edit: if your data is more extensive, structure it so its standard key/value array then loop over the items. The actual issue to the original question is noted on the first line of the answer.
<?php
$root = new SimpleXMLElement('<movies/>');
$movies = [
    ['name'=>'foo', 'released' => '2020-12-01 00:00:00', 'plot' => 'foo is a foofoo'],
    ['name'=>'bar', 'released' => '2020-12-02 00:00:00', 'plot' => 'bar is a barbar'],
];
foreach ($movies as $movie) {
    buildMovieTag($root->addChild('movie'), $movie);
}

function buildMovieTag($node, $data) {
    foreach ($data as $key => $item) {
        // just year from datetime string
        if ($key === 'released') $item = date_create($item)->format('Y');

        $node->addChild($key, $item);
    }
}

echo $root->saveXML();

Result (manual formatted)
<?xml version="1.0"?>
<movies>
    <movie>
        <name>foo</name>
        <released>2020</released>
        <plot>foo is a foofoo</plot>
    </movie>
    <movie>
        <name>bar</name>
        <released>2020</released>
        <plot>bar is a barbar</plot>
    </movie>
</movies>

Comment: thanks. I suppose I might have constrained my example a bit too much. I was hoping that I'd be able to have `buildMovieTag` also add other child elements like so: `
foo2020foobar2019bar`
Comment: see edit, or if you only have the name, then inside buildMovieTag you would need pull the data


Dispersion measure - probability density function

Question: I am wondering whether someone has a tip on this potentially very basic question. i have done some grid-based bayesian analysis and ended up with a non-standard discrete posterior density function over an interval of 100 observational values (per graph) below and as shown in the vector format per below. I can easily find the corresponding value of the distribution in R (which.max) but am struggling to find a way to calculate any measure of dispersion of the probability distribution. Ideally - i would like to have a quick way of calculating in R that gives me the answer that x% of the density lies between e.g. the index values of 20 and 80; any tips very welcome...

  [1] 4.615412e-02 7.685555e-02 7.936106e-02 9.355243e-02 9.390333e-02 9.415255e-02 8.812764e-02 8.094180e-02
  [9] 7.111677e-02 6.096649e-02 5.067963e-02 4.113239e-02 3.252751e-02 2.514941e-02 1.900486e-02 1.405895e-02
 [17] 1.018350e-02 7.230007e-03 5.033092e-03 3.437899e-03 2.305284e-03 1.518504e-03 9.831581e-04 6.261243e-04
 [25] 3.925111e-04 2.424243e-04 1.476553e-04 8.878700e-05 5.277273e-05 3.104750e-05 1.810726e-05 1.048550e-05

Comment: See https://stats.stackexchange.com/questions/240749/how-to-find-95-credible-interval/240777#240777
Answer: If you want the smallest possible range with $x \%$ probability for a unimodal distribution (like the one you plotted), then I recommend the HPDinterval function in the R coda package. See the vignette here. There are other ways to construct intervals (e.g., centered quantiles through the quantile function) but this HPD interval seems to be what you want.
How it works
What the HPD interval is essentially doing is taking a horizontal line from far above, lowering it incrementally and stopping once the area under the posterior density (ignoring the line) is equal to $x/100$. Then it considers the points of intersection of the horizontal line and the posterior density curve and returns the interval with endpoints the same as that of the line segment formed by the intersection. Mathematically this captures the smallest interval of the posterior which has exactly $x \%$ probability.


Uniform distribution MLE

Question: Just a quick question:
I know a $U(0, A)$ with density of $1/A$ has as MLE of $X_{max}$, but would a $U(1,1+A)$ have the same MLE that of $X_{max}$?
I'm assuming so but just for clarity.
Answer: If $X \sim U(c, c + A)$. Then having observed $n$ independent observations, we can write the likelihood as,
$$L(A) = \dfrac{1}{A^n}\prod_{i=1}^{n}\mathbb{I}(c < X_i < c+A) = \dfrac{1}{A^n}\mathbb{I}(\min X_i \geq c) \mathbb{I}(\max X_i \leq c+A). $$
Since $1/A^n$ is a decreasing function of $A$, the MLE will be the smallest value possible such that $c+A \geq \max X_i$. Thus we want smallest value such that $A \geq (\max X_i - c)$.
Thus the MLE is $(\max X_i - c)$.
Answer: It looks like you want to estimate $A$ which I'll assume is greater than zero. The estimate should be: $\hat{A} = X_{max} - 1$. For example suppose $A = 5$, so the upper bound on the uniform distribution is $6$. If your sample contained $X_{max}=5.97$, then your estimate would be: $\hat{A} = X_{max} - 1 = 4.97$.

Uniform distribution MLE


How to get reference to Codemirror inside an iframe from parent page?

Question: I have a parent.html page which I have embedded an Iframe inside a div element and the src of iframe refer to a codemirror.html page which displays Code-mirror.

  ×

when I click a button I display a div which contains iframe as a modal block.
At this time I would like initialize Code-mirror by calling Code-mirror instance.
How can I initialize CodeMirror content from parent.html?
What I have done and still couldn't initialize codemirror:

Declared a global instants of codemirror and a global function on codemirror.html page.
var codeMirrorEditor;
window.setCode = function(content) {
    codeMirrorEditor.setValue(content);;
}

Calling those global instants and function from parent.html
 function openCodeMirror(){
            // Get the modal
            var modal = document.getElementById("cmModal");
            modal.style.display = "block";

            var iframe = document.getElementById("cmIframeId");
            iframe.contentWindow.setCode('My initial value');
            iframe.contentWindow.codeMirrorEditor.setValue('My initial value')
        }

codemirror.html
<!doctype html>

    <title>CodeMirror: HTML EDITOR</title>
// all codmirror addons and script comes here ...

parent.html
<!DOCTYPE html>

    <link rel="stylesheet" href="../css/modal.css">

<textarea id="source" style="width:100%; height:400px"> initial text comes from here </textarea>

<input type="button" value="open codemirror" onclick="openCodeMirror()"> </input>

    ×

modal.css for parent.html
/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 0px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
/*   background-color: #ff8000; */
  background-color:#fefefe ;
  margin-left: 0px;
  margin-right: 0px;
  margin-top: 0px;
  margin-bottom: 0px;

  padding-left: 0px;
  padding-right: 0px;
  padding-top: 0px;
  padding-bottom: 0px;

/*   padding: 10px; */
  border: 1px solid #888;
  width: 100%;
  height:100%;
}

/* The Close Button */
.close {
  color: #aaaaaa;
  float: right;
  font-size: 32px;
  font-weight: bold;
  margin-right: 10px;
/*   border: 1px solid #ff0000; */
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

Answer: Guys it works like charm, it was just my mistake mixing code. After cleaning the code it works as it should. Thanks to everyone, may it help someone else to solve other issues.


Manual simulation of Markov Chain in R

Question:
Consider the Markov chain with state space S = {1, 2}, transition matrix

and initial distribution α = (1/2, 1/2).

Simulate 5 steps of the Markov chain (that is, simulate X0, X1, . . . , X5). Repeat the simulation 100
  times. Use the results of your simulations to solve the following problems.

Estimate P(X1 = 1|X0 = 1). Compare your result with the exact probability.

My solution:
# returns Xn
func2 <- function(alpha1, mat1, n1)
{
  xn <- alpha1 %*% matrixpower(mat1, n1+1)

  return (xn)
}

alpha <- c(0.5, 0.5)
mat <- matrix(c(0.5, 0.5, 0, 1), nrow=2, ncol=2)
n <- 10

for (variable in 1:100)
{
   print(func2(alpha, mat, n))
}

What is the difference if I run this code once versus 100 times (as is said in the problem-statement)?
How can I find the conditional probability from here on?
Answer: The R function func2 produces the vector$$(\alpha,1-\alpha) \mathbf P^n$$which is the marginal distribution of the Markov chain after $n$ steps, given that the initial state is generated with distribution $(\alpha,1-\alpha)$. To generate the Markov chain, one needs to proceed one step at a time:

generate $X_0$ equal to $1$ with probability $\alpha$ and $2$ with probability $1-\alpha$
generate $X_1$ which is equal to $2$ if $X_0=2$  and to $1$ with probability $1/2$ and $2$ with probability $1/2$ if $X_0=1$
generate $X_2$ which is equal to $2$ if $X_1=2$  and to $1$ with probability $1/2$ and $2$ with probability $1/2$ if $X_1=1$
generate $X_3$ which is equal to $2$ if $X_2=2$  and to $1$ with probability $1/2$ and $2$ with probability $1/2$ if $X_2=1$
generate $X_4$ which is equal to $2$ if $X_3=2$  and to $1$ with probability $1/2$ and $2$ with probability $1/2$ if $X_3=1$
generate $X_5$ which is equal to $2$ if $X_4=2$  and to $1$ with probability $1/2$ and $2$ with probability $1/2$ if $X_4=1$

Each transition can be simulated by a one-line code such as
tranz <- function(x=1) 2-(x==1)*(runif(1)<.5)

leading to a five step Markov chain in a similarly easy coding such as
marx <- function(alf=.5){
   x=2-(runif(1)<alf)
   for (t in 2:6) x=c(x,tranz(x[t-1]))
   return(x)}

Thus one recovers one realisation of the sequence $X_0,X_1,X_2,X_3,X_4,X_5$. Rerunning the algorithm 99 times produces in total 100 realisations of the sequence $X_0,X_1,X_2,X_3,X_4,X_5$. Not necessarily all different (actually certainly not all different!), but iid replicas of such realisations, from which $\mathbb P(X_1 = 1|X_0 = 1)$ and $\mathbb P(X_5 = 1|X_0 = 1)$ can be estimated by the Law of Large Numbers.
Here is an illustration for 100 replications when $\alpha=.7$:

where the 6x100 values have been jittered and the curve corresponds to the 6 means of the simulated $X_t$'s.
Comment: I think your sentences from 1 to 6, need some punctuation. Otherwise, I am lost.

Manual simulation of Markov Chain in R


Systemd scripts will not run on boot

Question: I have three docker containers that I've created systemd scripts to run at startup. I've run systemctl enable xxxx for all three services, and i've tried systemctl reenable xxxx as well. I've created the scripts from the docker documenation. If I run the scripts with service xxx start, the script runs fine. Whenever I reboot, the docker service runs fine, but the three scripts remain loaded but inactive:
● guacd.service - Redis container
   Loaded: loaded (/etc/systemd/system/guacd.service; enabled; vendor preset: enabled)
   Active: inactive (dead)

The composition of my script /etc/systemd/system/guacd.service:
[Unit]
Description=Redis container
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker start -a guacd

ExecStop=/usr/bin/docker stop -t 2 guacd

[Install]
WantedBy=local.target

Comment: This isn't the right way to go about it to begin with. You should be setting Docker restart policies when you create the containers.
Comment: Which is what I have since done, however that does not explain why this documented feature does not work.
Answer: Is it WantedBy=local.target? Maybe WantedBy=local-fs.target
https://www.freedesktop.org/software/systemd/man/systemd.special.html#local-fs.target

Systemd scripts will not run on boot


how to insert a char after specified number

Question: I want to insert a | after a specified number of characters on every line, then remove trailing whitespace.
For example...
Insert a | on characters 11, 15, 27, and 46 of every line. Then remove trailing white space before each |
1234567890 123 blahblahblah              blahblahblah

into
1234567890|123|blahblahblah|blahblahblah

Comment: positions like 11,15 etc are they always empty?
Comment: They are always empty. I could make use of William's except that sometimes I have addresses which are separated by a space. If I could say "between chars 100 and 120, replace spaces between words with a %" then run awk '{$1=$1}1' OFS=\|, then turn all "%" into spaces again, that would be perfect. But I don't know how use a reg ex only between places 100 and 120.
Answer: Do you really want to count characters, or do you just want:
awk '{$1=$1}1' OFS=\|

Comment: That's elegant... Thanks! Can you tell me how I would have counted chars though?
Comment: Here's one way: `perl -pe 'for $x(11,15,27,46) { substr( $_, $x, 0, "|")} s/\s+\|/|/g'`  This also replaces whitespace before non-inserted `|`, but that's easy to fix.
Comment: This does exactly what I want it to. Thanks.


Book on stochastic processes

Question: What is good applied book on stochastic processes? Specifically, a book that focuses on Wiener process and Brownian motion.
PS: Preferably free
Answer: You can have a look on:
Ross, Sheldon M. Introduction to probability models. Academic press, 2010. Chapter 10 of the book is "Brownian Motion and Stationary Processes". The PDF of the book is also available in online.
Answer: Someone should probably mention Karlin and Taylor's First Course in Stochastic Processes although this is more theoretical.
Comment: You just did.  I think it is good for Brownian Motion but it is hard to find a good book on Brownian Motion that is also applied and vice versa.
Comment: The OP doesn't ask for much.  He wants it to be free.  Another old one that I like from the 1970s  Is Hoel, Port and Stone.

Book on stochastic processes


How to build classification model towards some rare response classes?

Question: I was asked to build a predictive classification model that can predict some types of response. I am interested in 6 classes, however, the total occurence of these 6 classes (out of almost half a million total observations) is only ~2000, and all other responses belong to two huge classes that I'm not interested in. The number of variable is 25. That leads to a problem, since more than 98% of the observation belongs to a two classes, when apply methods like knn or classification tree, 100% of the data will be assigned to those two classes, which makes the prediction meaningless.
I have no idea about how to deal with this problem. I try to reduce the dimension of the data by removing observations with many missing values, but the proportion of the two dominant classes is still about 95%. I would try to study only on the ~2000 observations that belong to "interesting" classes, but that seems to a very bad method...
So anyone can give me some advice about general approach to this problem? I appreciate any help!
Comment: This tutorial is for data mining of rare event information ... http://www-users.cs.umn.edu/~aleks/pakdd04_tutorial.pdf
Answer: One possibility is to collapse the four rare classes down into one, or set up a model to predict those separately. That may change your problem entirely, however, and not be appealing to you.
Gary King of Harvard University published an excellent paper (http://gking.harvard.edu/files/0s.pdf) on logistic regression for rare events. In this case you oversample the rare events (or collect all rare events) but only a small sample of the more common events. I think this would be a good place to start, but you may ultimately be able to branch out to corrections for multinomial logistic regression. I don't know of resources for rare event multinomial logistic regression, but this may get you started.
Comment: Thanks! Unbalanced Sampling would be a great idea. I looked at some R documents of packages like 'ROSE' and 'unbalanced' but they can only handle binary response, so maybe I need to do the sampling by myself. Is it pretty strightforwad? Since it seems that I only need to make a new data set with almost even proportion of majority class and rare classes by sampling, or there is something else that I need to consider?
Comment: And also, after getting the unbalanced sampling data set, it looks like knn is not helpful here because there will be many ties, should I apply classification tree? What I think is doing a tree several times, every time with different unbalanced sampling, and use majority vote of different predicted classes by those trees to determine the final predicted class.
Comment: @dave2d I would be wary of resampling, mostly because it is very difficult to know just the right amount of resampling needed to correct any undue bias against the minority class, and the bias is only likely to be a problem with very small datasets.  If you have a very small dataset, it is difficult to have enough data to tune the amount of resampling.


How do I import images using the module migrate source CSV?

Question: I'm using the module migrate source csv to import a csv file.
I took a look at the page https://www.drupal.org/docs/8/modules/migrate-source-csv/using-the-migra... to understand how to use the module.
This is my CSV file.
id,title,body, field_image
1,title 1,some body text 1, image_from_the_web.jpg
2,title 2,some body text 2, image_from_the_web.jpg
3,title 3,some body text 3, image_from_the_web.jpg

This is my configuration.
id: basuuid
label: Import articles
migration_groups:
  - ACME import

source:
  plugin: csv
  # Full path to the file.
  path: '/mypath/to/file/acme_articles.csv'
  # Column delimiter. Comma (,) by default.
  delimiter: ','
  # Field enclosure. Double quotation marks (") by default.
  enclosure: '"'
  # The number of rows at the beginning which are not data.
  header_row_count: 1
  keys:
    - id
  # Here we identify the columns of interest in the source file.
  # Each numeric key is the 0-based index of the column.
  # For each column, the key below is the field name assigned to
  # the data on import, to be used in field mappings below.
  # The value is a user-friendly string for display by the
  # migration UI.
  column_names:
    0:
      id: 'Unique Id'
    1:
      title: 'Title'
    2:
      body: 'Post body'
    3:
     field_image: 'Image'
process:
  title: title
  body: body
  field_image:  field_image
  type:
    plugin: default_value
    default_value: article

destination:
  plugin: entity:node

When I want to execute drush migrate-import basuuid, I get this error:

Call to a member function getFileUri() on a non-object in /drupal/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php

I took a look on other topics to solve my problem, without success.
How do I migrate images?
Thank you
Comment: Sounds like it can't find the file?
Answer: You have to create a separate yml for the image config. There's a tutorial here: https://www.mtech-llc.com/blog/ada-hernandez/how-migrate-images-drupal-8-using-csv-source


incremental backup IMG files - Linux

Question: I have been looking for a solution in LINUX to be able to get incremental backup of .img files (KVM) for the past two weeks and I tried almost everything I could get from searching in google ( Rdiffbackup, Attic, Rsync, Rsnapshot, Bacula, Areca Backup,etc.., you name it!) but still could not find a solution.
Basically I want something like an agent to run in the hardware node of the VMs and detect if an image is changed and be able to read inside the img file and copy the new section(s) only to the original img file which is backed up on the first run and to have a main backup machine which all the backups come into it.
I do not need any web interface(not necessarily) and it has to be under LINUX.
Would appreciate any suggestion or help on this.
Thank you
Comment: http://wiki.qemu.org/Features/IncrementalBackup but not quite what Veeam offers.
Comment: What was not working for you in the solutions ruled out? It seems that rsync would be the best bet for you...
Comment: @Fox Rsync could not realize that which part of img file is change and when time stamp of the img file changes, it copies the whole img file again
Comment: It is exactly what rsync does (copies only changed parts of file), but to do that, it has to read and checksum the whole file on both sides. So disk i/o is the same, but network traffic is less.
Comment: @Fox even for .img files? if so, how can I make that happen?
Answer: I'd recommend using LVM (optionally with thin provisioning) along with lvmsync, but then I'm biased, having written lvmsync for this exact situation.
If that doesn't suit, the qemu incremental backup support (as mentioned in a comment by @HBruijn) in newer versions of qemu is available, if you don't mind running bleeding edge code.  Unfortunately, the qcow2 image format doesn't allow the kind of "live point-in-time snapshot" feature that would be needed to implement the sync process you'd like.  The VMDK format does, and I wrote vmdksync to handle that, but I don't know if qemu's VMDK support is suitably advanced to deal with it (I wrote it to migrate off VMWare servers, and I've never tested it against qemu).
Comment: Thanks for the suggestion but I can not have the VM ( or its service)to be down and copy. I am looking for something to backup from live without stopping
Comment: Yeeeesssss... that's what my suggestions will provide.
Answer: There are several possibilities.

rsync. It does what you expect it to do, but to do so, it has to read whole file on both ends, compute checksums and transfer the changes. If you are not using rsync remotely (networked filesystem for example), you need to disable whole-file transfer. (<code>--no-whole-file</code>)
LVM snapshots + lvmsync as suggested by @womble
Filesystem that supports snapshots and incremental backups (like btrfs (still not recommended for production), or ZFS).
DRBD - works as an online "RAID1". Does not work as an archive - if anything gets deleted on master, it is lost immediately on slave as well. But you have the latest data in case of hardware failure. (possible hack is to enable synchronization only at certain times, but i'd not recommend that) Just keep in mind, that most filesystems can not be mounted on both ends.
Combination of 2/3 and 4 (DRBD+LVM snapshots, or DRBD+ZFS) - gives you the best of both worlds. Online "RAID" across machines, and snapshotting the backing device on backup server to keep an archive.
Comment: Thanks for the suggestion, I tried DRBD but could not make it happen, I am looking at qemu now to see if I can make it to work.

incremental backup IMG files - Linux


Eliminar o último número que Digitei

Question: Amigos, mais uma dúvida(^^). Observem o Código a seguir:
Numero = int(input('Digite um Numero'))

inteiro = []
inteiro.append(Numero)

while Numero>0:
  Numero = int(input('Digite um Numero'))
  inteiro.append(Numero)
if Numero<0:
  print(sorted(inteiro,reverse=True))

Na minha lista final, quero que imprima os valores anteriores ao último número.
Answer: O problema tem na verdade a ver com a forma como estruturou o programa. Dentro do while está a ler o numero e adiciona-o à lista independentemente do seu valor:
while Numero>0:
  Numero = int(input('Digite um Numero'))
  inteiro.append(Numero) # aqui adiciona mesmo se for 0 ou negativo

O número é adicionado mesmo quando não é valido, porque a comparação do while é feita depois. Para solucionar basta restruturar um pouco:
inteiro = []

while True:
  Numero = int(input('Digite um Numero'))
  if Numero <= 0: # logo após ler o numero vê se é inválido
      break # caso seja termina o while sem adicionar
  inteiro.append(Numero) # se for valido adiciona à lista e segue para o próximo

print(sorted(inteiro,reverse=True))

Veja o código a funcionar no Ideone
Comment: Perfeito!!! Muito Obrigado^^

Eliminar o último número que Digitei


Apache frontend for Tomcat, proxy security

Question: I have a server that hosts Tomcat for apps and Apache2 for it's frontend.
They communicate to each other through ajp protocol over mod_moxy and proxy_ajp modules.
Am I really safe using apache virtualhosts in this form:
...
        ProxyRequests Off

        <Proxy *>
                Order deny,allow
                Deny from all
                Allow from 192.168.0.100
        </Proxy>

        ProxyPass / ajp://srv.local:8009/
        ProxyPassReverse / http://srv.local
...

0.100 is the server's IP address and behind port 8009 is the Tomcat AJP connector.
I want Apache to cut any proxy requests from outside and allow only itself to use it for communicating with Tomcat.
Comment: Can you clarify what you're trying to accomplish?  That configuration will block all access through Apache to the Tomcat service, except for `192.168.0.100` - is that what you're going for?  Or are you trying to make sure that any communication with Tomcat happens via the Apache service?
Comment: I want to serve Tomcat application(s) to WWW through Apache. Tomcat is backend and therefore unacessible directly. Since Apache and Tomcat are paired through proxy_ajp, I want to make sure that nothing from WWW can abuse my proxy.
So my question would be, is this correct to block all access to proxy except the server itself? This setting is currently on our dev server and we can access Tomcat webapps.
Answer: The access controls in a <Proxy> block apply to where the request comes from, rather than where a request is going.  As long as ProxyRequests is disabled, requests through the proxy will never be sent to a destination that you didn't configure.
So, your <Proxy *> block can be removed with no risk.


Creating a wine static executable?

Question: I have some windows command line applications, in binary form (I do not have the source code) which I use frequently. Sometimes I need to run them in Linux machines, and it works perfectly under wine (wine is not an emulator). The problem I'm facing now is that I need to work on a cluster which has not wine installed on it. I wonder if it is possible to create in another similar linux machine kind of a static executable or so, so i can run this windows program on the cluster
Thanks
Comment: sorry, I forgot to say that I can not install anything on that cluster
Answer: This is an insane idea ;) Install wine on that cluster. What stops you? If you can execute programs there....
If this is some kind of serious software, it don't recommend to run it on non-native OS. Wine is not developed for running critical applications. It is still not Windows.
Comment: There are perfectly reasonable conditions under which users don't get root access, and can't install software.  Clearly large academic or commercial clusters are one of them.
Comment: I just will try to install wine from source code

this is kind of a old fortran 77 code application which runs fine under wine
Comment: Don't install wine from sources. Install from rpm or deb. It is much easier. If this is a simple app, then why to run it on a cluster? BTW, what do you mean under "cluster"? I thought, cluster is a several PCs, working together on some task.
Answer: You can't compile a static exe; Windows is too complex for that. But you might be able to compile Wine to run on your cluster.
What you need is a way to compile code on the cluster. Wine itself can be installed anywhere but since I don't know if you have all the dependencies on the cluster, it might take some work.
So I suggest to get the Wine sources, run configure --prefix=$HOME/wine && make and then work through the errors.
(--prefix is the path under which Wine will be installed; it should be some path that is the same on the cluster and your build host. If all else fails, ln is your friend).
Answer: I've just spent a couple minutes looking for a reference to the knowledge in my head but it my googling isn't up to it.
Picasa for linux is bundled with Wine, so it may be possible but I couldn't find the article I read a couple months back.
Other than this, you can cross compile with gcc and winelib but as Cyper rightly said, no code no compilation.

Creating a wine static executable?


Hyperbola with its directrix

Question: The equation $9x^2 - 16y^2 -18x +32y-151=0$ represents a hyperbola . We have to find the equation of its directrix.
I simplified the equation and got :   $$(3x-1)^2 -(4y-1)^2 = 151$$
And found that its center is $(\frac{1}{3},\frac{1}{4})$ .
But I am not getting how to find the equation of the directrix . For a standard hyperbola it is $x = \frac{a}{e}$   where $e$ is the eccentricity.
Comment: Your simplified equation is not correct: check your calculations.
Answer: Once you have rewritten your equation as
$$
{(x-x_0)^2\over a^2}-{(y-y_0)^2\over b^2}=1,
$$
then the equation of a directrix is $x=x_0+a/e$, where $e=\sqrt{1+b^2/a^2}$.

Hyperbola with its directrix


How to determine if a model is nested?

Question: I have two models for prospect theory utility functions and want to compare their fits. However, I'm not sure if the models are nested or not. The first model is given by:
$U(x) = x^α$ for  $x ≥ 0$ and
$U(y) = −λ|y|^α$ for $y < 0$
The second model is given by:
$U(x) = x^α$ for  $x ≥ 0$ and
$U(y) = −λ|y|^\beta$ for $y < 0$
The first model could be a specific version of the second model where $\beta = \alpha$ but my gut tells me this isn't how nested models work. Any help identifying nested models would be appreciated.
Comment: Two models are nested if we can simplify the bigger model into the smaller model by imposing constraints on the parameters. In your case the constraint is $\beta=\alpha$ just as you point out, so model 1 is nested in model 2.
Comment: See also the similar post:  https://stats.stackexchange.com/questions/509957/nested-glm-models/510243#510243
Answer: Two models are nested if we can simplify the bigger model into the smaller model by imposing constraints on the parameters.
Often this means setting a parameter to 0. For example, regression M1
$$
g(E\{Y\}) = \beta_0 + \beta_1 X_1 \color{white}{+ \beta_2 X_2}
$$
is nested in regression M2
$$
g(E\{Y\}) = \beta_0 + \beta_1 X_1 + \beta_2 X_2
$$
because M2 simplifies into M1 if we set $\beta_2 = 0$.
However, the principle is more general than fixing a parameter to equal a constant. In your case the constraint is $\beta = \alpha$. So your model 1 is indeed nested in your model 2.

How to determine if a model is nested?


Barra de progresso bootstrap acompanhando duração de video youtube implantado na pagina html

Question: como fazer a barra de progresso do bootstrap acompanhar o seguimento do video youtube (iframe) implantado na pagina html

var player,
  time_update_interval = 0;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('video-placeholder', {
    width: 600,
    height: 400,
    videoId: 'Xa0Q0J5tOP0',
    playerVars: {
      color: 'white',
      playlist: 'taJ60kskkns,FG0fTKAqZ5g'
    },
    events: {
      onReady: initialize
    }
  });
}

function initialize() {

  // Update the controls on load
  updateTimerDisplay();
  updateProgressBar();

  // Clear any old interval.
  clearInterval(time_update_interval);

  // Start interval to update elapsed time display and
  // the elapsed part of the progress bar every second.
  time_update_interval = setInterval(function() {
    updateTimerDisplay();
    updateProgressBar();
  }, 1000);

  $('#volume-input').val(Math.round(player.getVolume()));
}

// This function is called by initialize()
function updateTimerDisplay() {
  // Update current time text display.
  $('#current-time').text(formatTime(player.getCurrentTime()));
  $('#duration').text(formatTime(player.getDuration()));
}

// This function is called by initialize()
function updateProgressBar() {
  // Update the value of our progress bar accordingly.
  $('#progress-bar').val((player.getCurrentTime() / player.getDuration()) * 100);
}

// Progress bar

$('#progress-bar').on('mouseup touchend', function(e) {

  // Calculate the new time for the video.
  // new time in seconds = total duration in seconds * ( value of range input / 100 )
  var newTime = player.getDuration() * (e.target.value / 100);

  // Skip video to new time.
  player.seekTo(newTime);

});

// Playback

$('#play').on('click', function() {
  player.playVideo();
});

$('#pause').on('click', function() {
  player.pauseVideo();
});

// Sound volume

$('#mute-toggle').on('click', function() {
  var mute_toggle = $(this);

  if (player.isMuted()) {
    player.unMute();
    mute_toggle.text('volume_up');
  } else {
    player.mute();
    mute_toggle.text('volume_off');
  }
});

$('#volume-input').on('change', function() {
  player.setVolume($(this).val());
});

// Other options

$('#speed').on('change', function() {
  player.setPlaybackRate($(this).val());
});

$('#quality').on('change', function() {
  player.setPlaybackQuality($(this).val());
});

// Playlist

$('#next').on('click', function() {
  player.nextVideo()
});

$('#prev').on('click', function() {
  player.previousVideo()
});

$('pre code').each(function(i, block) {
  hljs.highlightBlock(block);
});
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>How to Control YouTube's Video Player with JavaScript</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

0:00 / 0:00

              70% Complete

        play_arrow

        pause

Answer: Pelo YouTube creio não ser possível. Para customizar, é necessário utilizar a tag <video> do HTML5.
Vamos começar pelo JavaScript? Pra facilitar, usei JQuery, mas se quiser, posso postar uma outra com JavaScript puro.
O segredo aqui é o width da barra, que deve ser em porcentagem.

// Como a barra de progresso do Bootstrap na verdade trabalha com o width em CSS, vamos criar primeiro uma função pra transformar o tempo atual do vídeo em sua correspondente porcentagem
function porcento(valor,maximo){
  // max   = 100
  // valor = x
  // x = valor * 100 / max
  var x = valor * 100 / maximo;
  return x + '%';
}

// Agora começamos o código...
$(document).ready(function(){
  // Criei essa var pra dar play e pause no vídeo ao clicar nele
  var rodando = false;
  // Simples: Ao clicar no vídeo se ele estiver rodando, para ele. Senão, põe ele pra rodar
  $("#meuVideo").click(function(){
    if (rodando){
      this.pause();
      rodando = false;
    } else {
      this.play();
      rodando = true;
    }
  });
  // Aqui tratamos a barra em si:
  // A cada alteração no tempo do vídeo
  $("#meuVideo").on('timeupdate',function(evt){
    // Eu preferi usar variáveis, por motivo de didática
    // Gravo a posição atual
    var estadoAtual = this.currentTime;
    // E o tempo máximo do vídeo
    var duracao = this.duration;
    // Na barra de progresso,
    $('#barra')
      // seto o "valor máximo" para o tempo do vídeo
      .attr('aria-valuemax',duracao)
      // o "valor atual" para o tempo rodado até agora
      .attr('aria-valuenow', estadoAtual)
      // e o principal, o width dela ganha quantos % já foram rodados até aqui (graças a nossa funçãozinha)
      .css('width', porcento(estadoAtual,duracao));
  });
});

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

  <video id="meuVideo" width="400" height="225" poster="endereco/da/sua-thumbnail.jpeg">
    <source src="endereco/do/seu-video.mp4" type="video/mp4" />
  </video>

O HTML é bem básico, apenas usei a tag <video> do HTML 5 e a própria barra de progresso do Bootstrap 4.

Referências bibliográficas

Pegar duração do vídeo (em inglês)
Mudar o valor da barra de progresso do Bootstrap (em inglês)
API do Bootstrap para barra de progresso

Veja também:

Documentação da tag video na W3Schools (em inglês)
Tutorial da tag video na W3Schools (em inglês)


How to Install Custom Plugin in Locally Setup Kong

Question: I have created one custom kong plugin and trying to deploy it locally.
Trying with Luarocks, Pongo and Manually... but some how now able to make it.
Sharing steps what I am following below.
Command
luarocks make

Logs
kong-check-x-header 1.0-1 depends on lua ~> 5.1 (5.1-1 provided by VM) kong-check-x-header 1.0-1 is now installed in /email@example.com/126.96.36.199/luarocks (license: Apache 2.0)
Command
luarocks pack kong-check-x-header 1.0-1

logs
Packed: /Users/jaikratsinghtariyal/Sandbox/kong-check-x-header/kong-check-x-header-1.0-1.all.rock

Command
luarocks install kong-check-x-header-1.0-1.all.rock

logs
kong-check-x-header 1.0-1 depends on lua ~> 5.1 (5.1-1 provided by VM)

Error: /email@example.com/22.214.171.124/luarocks/lib/luarocks/rocks-5.1/kong-check-x-header/1.0-1/lua/kong/plugins/kong-check-x-header/schema.lua: No such file or directory

Been quite some days...struggling with this... need some assistant here pls.
GITHUB - https://github.com/jaikratsinghtariyal/kong-check-x-header
UPDATE After Comment
Commands fired in below order.

pongo pack

logs -
Creating kong-pongo_kong_run ... done

kong-plugin-check-x-header 1.0-1 depends on lua ~> 5.1 (5.1-1 provided by VM)
Stopping after installing dependencies for kong-plugin-check-x-header 1.0-1

Kong version: 2.5.0

kong-plugin-check-x-header 1.0-1 depends on lua ~> 5.1 (5.1-1 provided by VM)
kong-plugin-check-x-header 1.0-1 is now installed in /usr/local (license: Apache 2.0)

Packed: /kong-plugin/kong-plugin-check-x-header-1.0-1.all.rock

`

pongo shell
luarocks install /kong-plugin/kong-plugin-check-x-header-1.0-1.all.rock

Logs:-
kong-plugin-check-x-header 1.0-1 depends on lua ~> 5.1 (5.1-1 provided by VM)
kong-plugin-check-x-header 1.0-1 is now installed in /usr/local (license: Apache 2.0)

export KONG_PLUGINS=bundled,kong-plugin-check-x-header
(shall I mention kong-plugin-check-x-header or check-x-header... Tried both actually its failing in both but error are more promising with check-x-header)
kong migrations bootstrap
kong start

All command except kong start are working.
Logs -
Error:
/usr/local/share/lua/5.1/kong/cmd/start.lua:75: /usr/local/share/lua/5.1/kong/cmd/start.lua:64: nginx: [error] init_by_lua error: /usr/local/share/lua/5.1/kong/init.lua:515: error loading plugin schemas: on plugin 'kong-plugin-check-x-header': kong-plugin-check-x-header plugin is enabled but not installed;
no plugin found
stack traceback:
    [C]: in function 'assert'
    /usr/local/share/lua/5.1/kong/init.lua:515: in function 'init'
    init_by_lua:3: in main chunk

stack traceback:
    [C]: in function 'error'
    /usr/local/share/lua/5.1/kong/cmd/start.lua:75: in function 'cmd_exec'
    /usr/local/share/lua/5.1/kong/cmd/init.lua:88: in function </usr/local/share/lua/5.1/kong/cmd/init.lua:88>
    [C]: in function 'xpcall'
    /usr/local/share/lua/5.1/kong/cmd/init.lua:88: in function </usr/local/share/lua/5.1/kong/cmd/init.lua:45>
    /kong/bin/kong:9: in function 'file_gen'
    init_worker_by_lua:47: in function <init_worker_by_lua:45>
    [C]: in function 'xpcall'
    init_worker_by_lua:54: in function <init_worker_by_lua:52>

Comment: Can you share your `rockspec` file ?
Comment: Added my GITHUB link.
Answer: First to use pongo you have to respect the file path and plugins name
kong-check-x-header => kong-plugin-check-x-header
then you should put your files in the right directory
kong/plugins/check-x-header/
you have kong-check-header-x instead of check-x-header in a spec file.
I think you should use linter like pongo lint to detect issue for example
X-Auth-Token cannot be used as key you should prefer X_Auth_Token
Comment: I don't understand, the file name is `kong-plugin-check-x-header-1.0-1.rockspec`
Try to use pongo I think it will be easier
Comment: Right, so I did the changes and command `luarocks make` is failing with `Error: Filename './kong-check-x-header-1.0-1._rockspec' does not look like a rockspec.`


Touch Flash action script 3

Question: Porque acontece isso?
Criei um circulo converto ele em BOTÃO, e dou a ele qualquer ação,  se eu deixar um dos meus dedos pressionado na tela fora do circulo, e toca-lo com meu outro dedo ele não executa qualquer tipo de ação.
Answer: Para eventos de toque, você deve definir qual o tipo de toque que o seu aplicativo irá receber. O ActionScript disponibiliza três tipos:

GESTURE Você realiza um movimento e ele toma uma ação)
NONE O touch é tratado como click do mouse
TOUCH_POINT Cada toque que você dá na tela é gerado um "touchID" para manipulação.

(ref.)
O padrão é GESTURE, portanto, para definir mais de um toque na tela, você deve usar:
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;

E então, para tratar os eventos:
botao.addEventListener(TouchEvent.TOUCH_BEGIN, comecouTocar); //Início
botao.addEventListener(TouchEvent.TOUCH_END, terminouTouch); //Término
botao.addEventListener(TouchEvent.TOUCH_MOVE, moveTouch); //Movimento
botao.addEventListener(TouchEvent.TOUCH_TAP, toqueTouch); //Toque (Equivalente ao MOUSE_CLICK)
.............

Para ler os IDs dos toques que são efetuados pelo usuário, você deve ler a propriedade touchPointID do objeto TouchEvent, assim:
function toqueTouch(e:TouchEvent):void {
    trace(e.touchPointID); //ID do toque do usuário
}

Neste link há todas as referências para tratar toques na tela. Caso você não consiga, verifique se o dispositivo que você está testando sua aplicação suporta multitoques, alguns leem apenas um, este site pode ajudar.

Touch Flash action script 3


Create chart for fivestar note

Question: I'm using Drupal 7, and Fivestar.
I try to display notes in the format of a pie chart.
If the note (= rating) is 5,2 on 10, I would like to have a circle of this type :

I tried Charts (with Google Charts as its charting engine) and Google chart Tools, but I do not manage to obtain what I wish (using the Views integration).
With Google chart tools, I have this problem (only one value is shown), and with Chart nothing displays (i do not use aggregation, just fivestar field in views).
Would you know a solution?
A tabular of the data which I wish to display :
Answer: Solution 1 - Use Charts to create a pie chart
The sample image in your question doesn't look like a pie chart to me, instead it rather looks like a Gauge chart. If you want to try to create a pie chart anyway, using the Charts module, then have a look at this feature request (which allows you to pass "library specific options"). Comment #9 in it contains a patch that you'll need for it (using Google Charts as the rendering engine).
After you applied that patch, you'll be able to pass any of the specific options to the Google Charts charting engine that correspond to the chart you're trying to create.
If applying the patch is not sufficient, then I'd recommend what's written in the "Bonus tip" of Steps to create charts using the views UI, i.e.:

You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In other words: before trying to create a chart, make sure the tabular version of it has the correct data displayed.
Solution 2 - Use Charts to create a Gauge chart
Your sample image in your question rather looks like a Gauge chart. Have a look at the Charts issue about Support for gauge charts. After you apply the patch included in comment # 4 of this issue, you'll be able to use the Charts API to create such Gauge charts (using Google Charts as your charting engine). BTW, you can also use this specific SimplyTest.Me  link (which has this patch enabled).
Here is a sample of 2 such charts I created in my own environment (using that patch):

The first (left) chart is to show a rating like 5.7, and the second (right) chart is to show a rating like 7.2 (both ratings on a scale of 10). Attention: I haven't found any specific option (yet) to show that value of 5.7 (and 7.2) in the Gauge chart, instead of the rounded value 6 (and 7) near the bottom. Though the (red) pointer within the chart seems to correctly reflect the actual values already.
My PHP code for rendering the above 2 Gauge charts looks like so (the various options I used should be self explaining):
<?php

 $chart = array(
    '#type' => 'chart',
    '#chart_type' => 'gauge',
    '#chart_library' => 'google',
    '#title' => t('Gauge Chart'),
    '#min' => 0,
    '#max' => 10,
    '#width' => 300,
    '#height' => 300,
    '#greencolor' => '#00AA10',
    '#greenfrom' => 0,
    '#greento' => 5,
    '#redfrom' => 8,
    '#redto' => 10,
    '#redcolor' => '#FF3333',
    '#yellowfrom' => 5,
    '#yellowto' => 8,
    '#yellowcolor' => '#66BB88',
    '#minorticks' => 5,
  );

echo "
Left Gauge chart (= Rating 1) : 5.7 / 10 ; Right Gauge chart (Rating 2) : 7.4 / 10
";

  $chart['rating1'] = array(
    '#type' => 'chart_data',
    '#title' => t('Rating 1'),
    '#data' => array(array('Rating1', 5.7)),
  );

  $chart['rating2'] = array(
    '#type' => 'chart_data',
    '#title' => t('Rating 2'),
    '#data' => array(array('Rating2', 7.2)),
  );

  $example['chart'] = $chart;

  return drupal_render($example);
?>

If you paste the above code in the body of any content type that allows using the PHP filter, and assuming you have a working internet connection (prereq to use Google Charts), you should get a similar chart in your own environment (provided you also enabled the patch mentioned before).
With the above solution that uses the Charts API, it should be possible to use the same technique for adding an extra column in your tabular Views display, using "rewrite results", in which you also refer to the actual value of the Score column for each of your views result rows (so that you get 1 Gauge chart somewhere to the right of your Score column).
Disclosure: I'm a co-maintainer of the Charts module.
Comment: I do not understand why but nothing displays in the block which I create in views. I configured everything well, but i have only the title of my block views... With Google chart tools, the chart appear... I look I look, but I do not find why nothing displays. A problem like that has already indicated? I looked also but nothing found there
Comment: I think there is a problem with the label. I have three field : content title for the "provide labels", rating for the first provides data, and a simple field number for the second provides data. The pie chart appear only when i'm adding a label to the simple field number. The rating field doesn't appear (with label or not)... Hm. I read [this issue](https://www.drupal.org/node/2346991) but the solution won't work for me
Comment: @Hgfdsoiu : please refer to my updated answer: can you edit your question to also show some type of tabular display of the data for which you're trying to create a chart?
Comment: The tabular display correctly the data, but when I tip over it chart, nothing more of displays. I have downloaded a picture of tabular in my question (for example, for node 1, i want to display the score = 3 on 10 (= the reference))
Comment: @Hgfdsoiu : check the "solution 2" I added ... I realized that your chart, IMO, is a Gauge chart (not a pie chart ...).
Comment: For information, I do not succeed in obtaining what I want, but I continue to test. Thanks for your help

Create chart for fivestar note


Função load() jQuery + Twig

Question: Estou desenvolvendo um sistema utilizando PHP, com a idéia de possuir apenas uma página. Como? (Não sei se é a melhor solução, acredito que não seja), desenvolvi um menu lateral que é fixo e os conteúdos a serem alterados ficariam no centro da página, o menu lateral contem alguns "links" ex:

   Perfil

Ao clicar nesse "link", carrego um arquivo html que contem um formulário simples de acordo com o link do menu clicado.
Fiz um script jQuery utilizando a função load():
$("#menuPerfil").click(function () {
   $('#principalContent').load("formPerfil.html.twig");
});

Conforme os links são clicados, é carregado um determinado html. Porém o html carregado pela função load do jQuery não consegue acessar algo que está no index, por exemplo uma tag do twig, é como se carregasse um html independente da index, e não apenas o incluísse.
Gostaria de saber se alguem conhece um modo de resolver utilizando a função .load(), tendo em vista que ela não acumula os arquivos html carregados na mesma página, ou alguma outra forma de fazer corretamente o carregamento desses dados, sem ter que fazer uma página diferente para cada funcionalidade do sistema.
OBS: utilizo PHP, twig e jQuery no projeto.
Answer: Para recuperar apenas uma div de um conteúdo você pode usar o AJAX para solicitar um determinado conteúdo, depois recupere apenas a info que deseja usando o id!

Segue abaixo o código.

$("body").on('click', '#menuPerfil', function () {

   $.ajax({
     url : "arquivo_com_conteudo_que_quer_pegar.html",
     success : function (retorno) {
           var conteudo =  $('
' + retorno + '
').find('#ID_DO_CONTEUDO').html();

           $('#principalContent').html(conteudo);
     },
     erro : function (a,b,c) {
           alert('Erro: '+a['status'] + ' ' + c);
     }
   });

   return false;
});

Comment: Hiago, tentei usar o que sugeriu e não funcionou pra mim, além de que ele insere o código no html toda vez que eu clico em um menu (possível visualizar no F12 do Chrome). Agradeço pela ajuda
Comment: ah, ele está recarregando a página? é um link né... faltou um return false na função .click o id #menuPerfil já esta no seu DOM ou é adicionado via javascript? Vou editar a resposta para que possa fazer mas um teste.
Answer: Não é verdade esse caso que você citou.

Conforme os links são clicados, é carregado um determinado html. Porém o html carregado pela função load do jQuery não consegue acessar algo que está no index

Ao usar .load() e carregar um arquivo HTML e nesse HTML conter códigos javascript tal qual este pode sim acessar qualquer tag do seu codigo. irei demonstrar com um exemplo.
Arquivo index.php

    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

        <button id="botao">Me clica</button>

Arquivo teste02.php

    Ola mundo!

Comment: SneepS NinjA, obrigado pela ajuda. Faço um render do twig em um arquivo index.php da página index.html.twig, nesse index.php, passo um array contendo o perfil de usuário autenticado, com a chave 'perfilUsuario'. Se eu for na index, e colocar uma tag do twig : {{perfilUsuario.nome}}, é exibido o nome que está no array passado para o twig, porém se tento usar {{perfilUsuario.nome}} nesse form que carreguei com o .load(), o mesmo é exibido como um texto comum. E se eu der apenas um include no lugar do .load(), consigo exibir as tags do twig normalmente.

Função load() jQuery + Twig


Normal distribution about probability of stocks revenue (positive and negative)

Question: So I am struggling with a question in statistics following :
An investment broker reports that the yearly returns on common stocks are approximately normally distributed with a mean of 12,4% and a standard deviation of 20,6%. On the other hand, the firm reports that the yearly returns on tax-free municipal bonds are approximately normally distributed with a mean return of 5,2% and a standard deviation of 8,6% Find the probability that a randomly yearly selected :
c) Common stock will give more than a 10% return.
Formula : $P(0,01>b)=1-P(X\le b)$
$Z=0,10-12,40/20,60 = 0,597$
Which gives me 0,2743 on normal table and :
$1-0,2743 = 0,7257$
So this should in theory mean the probability of more than 10% revenue is 0,7257?
The next question is with a loss of at least 10% how should I compute that?
Comment: Welcome to CV. This seems like homework. If so, remember to use the [self-study] tag.
Answer: Using software to check first computation:
You have $X \sim \mathsf{Norm}(\mu=12.4, \sigma=20.6).$ You seek
$P(X > 10) = 1 - P(X \le 10) = 0.5464.$
Computations are in R statistical
software, where pnorm is a normal CDF. Because
of rounding involved in the use of normal tables, your answer might
be a little different. [It seems you have the right approach, but with
a mistake at the start. I will leave it to you to fix the standardization.]
1 - pnorm(10, 12.4, 20.6)
## 0.5463738

For the next part you seek
$$P(X < -10) = P\left(\frac{X-\mu}{\sigma} < \frac{-10-12.4}{20.6}\right) =
P(Z < -1.087) = \dots \approx 0.1384.$$
pnorm(-10, 12.4, 20.6)
##  0.1384348

The figure below shows the density function of $\mathsf{Norm}(12.4, 20.6),$
with vertical lines at $\pm 10.$ The first answer is the area under the normal
curve to the right of the right-hand vertical line; the second is the area
under the curve to the left of the left-hand line.

Note: It is always a good idea to make sketches of normal curves and
areas when working problems like these. By hand, you can't make a sketch
as accurate as the figure above, but with some practice you can make a sketch
that is accurate enough to catch gross computational errors. (For example,
there is no way the area to the right of the vertical blue line exceeds 70%.)


Ring homomorphism from $\mathbb Z$ to $\mathbb Z$ is always identity or $0$

Question: I must assume that there exists f such that:
$$f(x+y) = f(x)+f(y)\\f(x\cdot y) = f(x)\cdot f(y)$$
One thing I managed to do was:
$$f(2+2) = f(2) + f(2) = f(2\cdot 2) = f(2)\cdot f(2) \implies \\f(2)+f(2) = f(2)\cdot f(2)\implies \\2f(2) = f^2(2) \implies f^2(2)-2f(2)=0 \implies f(2)(f(2)-2) = 0 \implies\\ f(2) = 0 \text{ or } f(2) = 2$$
but how to extend this argument to all the integers? That is, how to force $f(3) = 3$ and so on?
Comment: Usually a rinng homomorphism maps $1$ to $1$.
Comment: Many authors would define *ring* as having multiplicative identity, and thus a ring homomorphism from $\mathbb{Z}$ to $\mathbb{Z}$ may well be required to send 1 to 1 (eliminating the trivial map to zero).
Comment: To the commenters above: unless the ring is the zero ring, in which case $0$ is indeed a multiplicative identity (playing a dual role along with being the additive identity).
Answer: From $f(1)=f(1\cdot1)=f(1)\cdot f(1)$ we conclude that either $f(1)=1$ or $f(1)=0$. At any rate, $f(n)=f(\underbrace{1+\ldots+1}_n)=\underbrace{f(1)+\ldots +f(1)}_n=nf(1)$, so in the first case $f(n)=n$ and in the second $f(n)=0$ for all $n$ (actually, first only for all $n\ge 0$, but we can take inverses).
Comment: How did you get that bracket underneath to indicate n 1's?
Comment: @SirJective right click equation and select "Show as -> Tex commands"
Comment: Wow I was not aware I could do that. Thank you.
Comment: Worth noting that this proof uses the fact that $\mathbb{Z}$ is generated by 1 to write any n as a sum of 1s.
Answer: Hint: Use the definition of ring homomorphism i.e. we must have that the multiplicative identity is sent to the multiplicative identity, and that the additive identity is sent to the additive identity.
So if $f(1)=1$, Then $f(n)=f(1+1+1+.....+1) \text{(n times)}=$?


currency.properties file in JDK7

Question: From this oracle java tutorial:

Suppose that a country adopts a different currency and the ISO 4217
  maintenance agency releass a currency update. To implement this
  update and thereby supercede the default currency at runtime, create a
  properties file named /lib/currency.properties. This file
  contains the key/value pairs of the ISO 3166 country code, and the ISO
  4217 currency data. The value part consists of three comma-separated
  ISO 4217 currency values: an alphabetic code, a numeric code, and a
  minor unit. Any lines beginning with the hash character (#), are
  treated as comment lines. For example:
Sample currency property for Canada CA=CAD,124,2

However I cannot create a file currency.properties in my usr/lib/jvm/jdk1.7.0/lib as I am not the owner. I have also tried the command sudo chmod root .  but apparently it does not affect it. I am using ubuntu 12.04 and running a Jdk1.7.0.
Is it possible to add that file or those java folders are unchangeable?
Thanks in advance.
Comment: Off topic? Why would it be?
Answer: You can use a file from your app conf dir. Run this code at the start of your app
String javaHome = System.getProperty("java.home");
System.setProperty("java.home", "conf");
Currency.getInstance("USD");
System.setProperty("java.home", javaHome);

this will make Currency read props from conf/lib/currency.properties
Comment: Actually I tried it out and does not work to my system.

currency.properties file in JDK7


Issues with Zen subtheme

Question: I am running a Zen subtheme for another drupal instance and it all worked fine. However, when I copied the folders across to my new Drupal instance, all I see is
The name of the site and
User menu :
My account
Log out

There is no Add content link... or the administration menu along the top... also no styles are applied... I am pretty sure I changed all the site specific instances in the code (.info file etc)... What am I doing wrong?
Ok, so I can navigate through the admin menu by changing the url path... admin/appearance
I have cleared the cache, but the styles for the zen sub theme are still not being picked up and I cannot see the Add Content link on the front page.
I've tried changing the theme to Bartik, and it looks fine. The styles are being picked up and everything.
So why is it not working for the Zen subtheme?
In the logs, I am seeing this message:

Notice: Undefined property: stdClass::$prefix in system_theme_settings() (line 547 of /home/mysite/public_html/modules/system/system.admin.inc).

Does this explain the wsod problem?
Comment: Thank you @mojzis

Enabling the theme based on the zen theme is the only thing I was able to do. All I now see is the chinese symbol, user menu and my account and log out links :S

I can't even get to the blocks, because there is no administration menu... There is an administration menu on the drupal site I copied the theme and styles from though... SHould I have just started from scratch, by following the instructions in the zen folder, instead of copying an subtheme from another site?
Comment: did you check whether you have blocks placed in regions ? theoretically the theme you had before could have had a different set of refions ... also, did you enable the zen theme ?
Comment: can you post your theme info file ? it could be that the reference to zen could be mistyped or something like that
Comment: you might want to check the results of `dpm(list_themes());` in devel/php under some other theme - look for zen and the prefix variable ... normally it contains "phptemplate"
Answer: You need to copy over The Zen theme as well, A sub-theme requires both the sub theme and its parent theme in order for it to work
Comment: That's the thing that confuses me. I did also copy the zen theme as well @frazras
Comment: Do other themes work?
Comment: They did... But I can't test if they still do, because I can't get to the admin menu :(

I originally had the bartik theme selected, and it looked fine...

@frazras
Comment: Ok, so I can navigate through the admin menu by changing the url path... admin/appearance

I have cleared the cache, but the styles for the zen sub theme are still not being picked up... and I cannot see the Add Content link on the front page...

I've tried changing the theme to Bartik, and it looks fine... the styles are being picked up and everything...

So why is it not working for the Zen subtheme? @frazras
Comment: In the logs, I am seeing this message:
Notice: Undefined property: stdClass::$prefix in system_theme_settings() (line 547 of /home/mysite/public_html/modules/system/system.admin.inc).

Does this explain the wsod problem? @mojzis
Comment: strangely this still sounds like its not properly detecting your parent theme. what directory structure do you have the the themes in? sites/all/themes/subtheme AND sites/all/themes/zen ?
Comment: Also ensure that both themes are enabled. if you can't do it in the UI use drush pm-enable zen && drush pm-enable subtheme && drush vset theme_default subtheme
Answer: These are the steps you need to follow to use zen sub theme.

Download the zen theme from https://www.drupal.org/project/zen and extract the zip file in to your "`sitename/sites/all/themes/"

now your theme folder will look like "sitename/sites/all/themes/zen" you zen base theme.

move inside zen theme folder you will find STATRETKIT folder that is the sub theme you need to inherit, just copy that folder and paste it out site the folder

now in your themes folder you have two folder "zen" and "STATRETKIT" -> rename the folder to your desired theme name. lets say "samplesite"

modify your info file name to "samplesite.info" please check if the file format is in .info or text file because in starterkit the info file is text you need to change the extention by saving it as info file.
modify and create your css and js files as specified in the info file.

and if you have old site you want to copy that themes here dont copy full theme files here only replace the css and js file and your template.php and template folder alone.

clear the cache in configuration -> performance . and check if its working.

if you have any issues still read this https://www.drupal.org/node/873778 installing zen
https://www.drupal.org/node/1549668 subtheme steps
Note: Always read the README.txt file for all modules and themes installation will help you install easily and understand quickly.
hope these steps will help

Issues with Zen subtheme


Store values from UITextFields in NSArray programmatically iOS

Question: I would like to start by saying that I am fairly new to iOS programming, so excuse my ignorance.
I have three UITextFields in my CustomLayout. I am asking users to fill in their name, age and sex. I would like two things, if possible. First I would like, as soon as a user hits the return button from the keyboard, the input string to be stored in an NSArray. In addition, the secondary objective is to iterate through the UITextFields when the user hits the same button.
// CustomLayout.h
@interface CustomLayout : UIView {

UITextField *nameField;
UITextField *ageField;
UITextField *sexField;

UILabel *nameLabel;
UILabel *ageLabel;
UILabel *sexLabel;

UIButton *startButton;

}

@property (nonatomic, strong) UITextField *nameField;
@property (nonatomic, strong) UITextField *ageField;
@property (nonatomic, strong) UITextField *sexField;

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *ageLabel;
@property (nonatomic, strong) UILabel *sexLabel;

@property (nonatomic, strong) UIButton *startButton;

-(void)textFieldShouldReturn:(UITextField*)textField;

@end

In the implementation file
//CustomLayout.m
@implementation CustomLayout

@synthesize nameField, ageField, sexField;
@synthesize nameLabel, ageLabel, sexLabel;
@synthesize startButton;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[tkStyle viewBackgroundColor]];

        NSString *startButtonLabel = @"Start Experiment";

        //alocate and position views
        CGRect viewRect;//placeholder rect, reused for each view

        //nameLabel and nameField
        nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 95, 150, 40)];
        nameLabel.textColor = [UIColor colorWithRed:106/256.0 green:180/256.0 blue:150/256.0 alpha:1.0];
        nameLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:25];
        nameLabel.backgroundColor=[tkStyle viewBackgroundColor];
        nameLabel.text=@"Enter Name:";

        nameField = [[UITextField alloc] initWithFrame:CGRectMake(280, 90, 200, 40)];
        nameField.textColor = [UIColor colorWithRed:0/256.0 green:84/256.0 blue:129/256.0 alpha:1.0];
        nameField.font = [UIFont fontWithName:@"Helvetica-Bold" size:25];
        nameField.borderStyle = UITextBorderStyleRoundedRect;
        nameField.backgroundColor=[tkStyle viewBackgroundColor];
        textFieldShouldReturn:nameField.text;

// same for ageField and sexField

        //startButton
    viewRect = CGRectMake(250, sexField.frame.origin.y+75, 200, 40);
    startButton = [[UIButton alloc] initWithFrame:viewRect];
    [startButton setTitle:startButtonLabel forState:UIControlStateNormal];
    [startButton setTitleEdgeInsets:UIEdgeInsetsMake(4, 0, 0, 0)];
    [startButton setButtonIsActive:true];
    //[startButton setOSCAddress:OSCStopPressedString];
    [startButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchDown];

    //and so on adjust your view size according to your needs
    [self addSubview:nameField];
    [self addSubview:ageField];
    [self addSubview:sexField];
    [self addSubview:nameLabel];
    [self addSubview:ageLabel];
    [self addSubview:sexLabel];
    [self addSubview:startButton];
}
return self;
}

// that should allow for users to hit 'return' button to move through textfields
-(void)textFieldShouldReturn:(UITextField*)textField;
{
    //[(NSArray *) userInfoArray addObject:textField.text];
}

// that should change Views as soon as the user presses 'Start Experiment'
-(void)buttonAction:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"startTest" object:self];
}

@end

Any help would be appreciated.
Answer: NSDictionary will be a good approach. you can have unique key for each textfield value.
Answer: -(void)textFieldShouldReturn:(UITextField*)textField;

should be:
- (BOOL)textFieldShouldReturn:(UITextField*)textField;

Also, don't forget to return TRUE or FALSE (or YES or NO).
To make this work, implement the UITextFieldDelegate protocol in your class.
Put the following line of code in your .m file, above the @implementation:
@interface CustomLayout () <UITextFieldDelegate>
@end

then, set the delegate in your UITextFields with:
nameField.delegate = self;
ageField.delegate = self;
sexField.delegate = self;

This way the textFieldShouldReturn: method will be called when the user presses 'enter'
Answer: A couple of things:

Given your delegate methods, I assume you've actually specified the delegate for your three UITextField controls to be the object in which you've implemented these various delegate methods.
If you want to control the behavior of the return key, implement the textFieldShouldReturn method:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.nameField) {
        [self.ageField becomeFirstResponder];
    } else if (textField == self.ageField) {
        [self.sexField becomeFirstResponder];
    } else if (textField == self.sexField) {
        [textField resignFirstResponder];
        [self saveResults];
    }

    return NO;
}

I'd generally be inclined to do something like the above, where pressing return takes me to the next field, and pressing return on the last one dismisses the keyboard and tries to save the results.
BTW, in IB, I'd make sure that the "return key" setting for the first two control would be "Next", and for the last one, either "Go" or "Done".
Your save routine would simply populate an object with the contents of the three controls:
- (void)saveResults
{
    Person *person = [[Person alloc] init];

    person.name = self.nameField.text;
    if (self.ageField.text) {
        person.age = @([self.ageField.text integerValue]);
    }
    person.sex = self.sexField.text;

    // now do whatever you want with this object
}

This obviously assumes that you have a Person class:
@interface Person : NSObject
@property (nonatomic, copy)   NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, copy)   NSString *sex;
@end

@implementation Person
@end

If you'd rather use a NSDictionary or NSArray, that's fine, too (make sure you check the text fields are not nil, though), though I personally prefer a well-defined model object like above.
As a refinement, you might want to make sure you only enter numeric values for age (if that's how you want to store the age):
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.ageField) {
        NSCharacterSet *invalid = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
        NSRange range = [string rangeOfCharacterFromSet:invalid];
        return range.location == NSNotFound; // if non-numeric character not found, return true
    }
    return YES;
}

Comment: Thank you all for your answers! unfortunately I cannot up vote your answers due to lack of reputation!
@Rob, a question though. In order to call textFieldShouldReturn, the syntax goes [nameField textFieldShouldReturn:YES]; ?
Comment: No, you don't call it. The OS calls it for you when the user hits the return key in the text field (assuming you've set the delegate property for the text field, either in IB or programmatically).
Comment: @tk1863 And note, that method takes a `BOOL` return, not `void` as in the code sample of the original question.


Is there a name for an expression that is solely the sum of integer multiples of factorials?

Question: All natural numbers may be expressed as the sum of terms where each term is an integer coefficient multiplied by a factorial.  In each term, the coefficient is always less than or equal to the factorialised number in that term.  For example:
$$3 = 2! + 1!$$
$$11 = 3! + 2(2!) +1!$$
$$5000 = 6(6!) + 5(5!) + 3(4!) + 3! + 2!$$
Do such expressions have a name?  I have tried searching google, but was unable to come up with anything likely.
Comment: Compare https://math.stackexchange.com/questions/868774/calculating-a-factorial-base-representation (not a duplicate, I think, because that question was concerned with the properties of the representation rather than with terminology).
Answer: They're apparently called factoradic numerals!  But I've only ever heard it called base-factorial.
Answer: Sometimes this is called the Cantor expansion.  Most elementary number theory books have some exercises about it.


class implementation of operator delete() not being invoked

Question: I have the following code
#include <iostream>
#include <cstddef>
#include <string>
#include <memory>

class Object
{
public:
       Object()
       {
               std::cout << __PRETTY_FUNCTION__ << std::endl;
       }
       std::string x;

       void *operator new( size_t bytes )
       {
               std::cout << __PRETTY_FUNCTION__ << " : bytes = " << bytes << std::endl;
       }

       void operator delete( void * arg )
       {
               std::cout << __PRETTY_FUNCTION__ << std::endl;
       }
};

int main( int c, char *v[] )
{
       // std::auto_ptr< Object > pObject( new Object() );
       Object *o = new Object();
       delete o;
}

and it produces this output...
static void* Object::operator new(size_t) : bytes = 8

and then core dumps.
Given that I don't get the output from the operator delete() method and that it core dumps. I'm assuming that my operator delete() method isn't being invoked.
Can anyone shed any light as to why it isn't being invoked?
Thank you for focusing on the core dump against my ALL CAPS RANTS because it actually turned out to be the problem.
EDIT--
Ok, Where do I start.... I'm incredibly sorry for ranting. We've all been there, under pressure to meet a deadline and something innocuous appears to be causing an issue and we're convinced it's one thing when in fact it's another.
This has taught me a valuable lession... I need to start listening....
I fully appreciate all of help and advice given here.
Thx
Mark.
Comment: ALL THOSE CAPS REALLY HELP TO GET THE POINT ACROSS. NOT REALLY.
Comment: What do you return from `operator new` ?
Comment: But the control reaches end of a function returning a value, which is undefined behavior.
Comment: @ScaryAardvark: *you* are missing the bloody point. Your `delete` isn't called because the whole thing crashes *before* `delete` has to be called (in facts, it probably crashes in the `std::string` constructor).
Comment: @ScaryAardvark: no, *you're* missing the point - you're crashing because `new` is not behaving correctly, not because `delete` is not being called.
Comment: It doesn't matter as it's not used in operator delete().
Comment: YOU ARE MISSING THE BLOODY POINT YOURSELF.  THE CRASH *IS* THE MALE-CHICKEN-SUCKING PROBLEM!  GET IT?  GOT IT?  GOOD!
Answer: Your new expression does two things. It invokes the appropriate operator new function to allocate some memory and then constructs a new Object in the memory pointed to by the return value of operator new.
As you don't have a return statement in your operator new you get undefined behaviour. If we explore what is likely to happen, it is likely that the function returns a random value for the return value and the compiler attempts to construct the Object (including its owned std::string) at an invalid address.
This will cause a crash before your code ever reaches the delete statement.
Answer: operator new must return a pointer to sufficient memory (or throw an exception), because the new-expression will also be trying to invoke the constructor of Object for the allocated memory. The problem is not with delete, it's new Object that cannot complete normally.
Answer: If I change main to be
int main( int c, char *v[] )
{
       // std::auto_ptr< Object > pObject( new Object() );
       Object *o = new Object();
       std::cout<<"I'm ok here"<<std::endl;
       delete o;
}

then I get
static void* Object::operator new(size_t) : bytes = 4
Bus error

and cout is never called.. This is because you are running into undefined behaviour. (In particular it looks like on many compilers the constructor is being called in the location that is undefined)
If I change new to be
   void *operator new( size_t bytes )
   {
           std::cout << __PRETTY_FUNCTION__ << " : bytes = " << bytes << std::endl;
          return new char[bytes];
   }

I get
static void* Object::operator new(size_t) : bytes = 4
Object::Object()
I'm ok here
static void Object::operator delete(void*)

so delete will be called if you do the right thing.
Comment: There's nothing being corrupted on the call stack.  He's just returning whatever random garbage was in the EAX register (for Intel machines) as a pointer to a block of memory.  This bogus pointer is then dereferenced for the call to the constructor.
Comment: @JUST MY correct OPINION: What if the function call was implemented so that the callee pushes the return value onto stack, and the caller pops that? In that case, as there would happen a pop without matching push been done earlier, the stack *would* get corrupted.
Comment: If it was so implemented, then yes, indeed, it would corrupt the stack.  Now all you have to do to have a point here is point to a C++ compiler anywhere that implements returns this way.  (Hint: this is a very difficult task.)
Comment: @JUST MY correct OPINION: Indeed, very difficult to find such an implementation which would store a return value onto stack instead of a register, when the return value is something as small as a pointer. Just a theoretical note from me, which doesn't make any practical difference in this case :)
Comment: Yeah I guess i this case it may not corrupt the stack (though I've seen that happen a lot from statements with no return in other code .. I hate tracking those particular bugs down). But it certainly runs into undefined behaviour, so corrupting your stack is among the nicer things that it is allowed to do. .. updated my post to reflect that fact.
Answer: You're crashing well before delete() is called, because you haven't allocated any storage for std::string x; - if you comment out this instance variable then the code should compile (with warnings) and run OK.
Comment: if undefined behavior is "run OK"... :(((
Comment: @Armen: yes, strictly speaking it's UB, but in practice it will probably "run OK" in most environments. I'm not advocating for this kind of code though !
Answer: Why doesn't your operator new return a value? It is declared to return void * but dosn't return anything. This means your compiler should have given a compile error, apparently it didn't, and well the crash may be becaue of that.
On the other hand, if this, as you say, is an example, then maybe you returned 0 from new, in which case operator delete is not being invoked because calling delete on a 0 pointer is equivaent to an empty statement.
malloc something in new and return it, and operator delete will be invoked
Let's be more specific here:

Your core dump is obviously because you don't return a value.
delete o is a delete expression which will only eventually call your operator delete, and it will do so ONLY if the pointer is not NULL. As said, it must be a valid pointer
Comment: ScaryAardvark: If you're so damned sure of what the problem is why are you bothering to ask questions on StackOverflow?  It does indeed have EVERYTHING to do with whether memory was allocated or not and whether the return value is random or not.  (C.f. my answer and a few others for details.)  Humility is one of the most powerful weapons in the arsenal of a developer.
Comment: it's just an example. I don't care what hte return value is because I don't use it in operator delete().
Comment: @ScaryAardvark: Can you give a complete compilable crashig example? 'Cause yours is NOT compilable
Comment: Not returning a value means your stack gets corrupted - this is why you crash.
Comment: Please don't focus on the core dump.. Focus on why operator delete() isn't being called as that was my original question.....
Comment: Please look at the problem.. It has NOTHING to do with wether memory was allocated or the return value is (RANDOM). THE PROBLEM IS THAT MY OPERATOR DELETE() ISN'T BEING INVOKED...
Comment: @Armen, this is compilable on gcc4.1.2
Comment: @ScaryAardvark: That's the reason for the core dump. You MUST return a value of type void* from ANY functino that is declared to return void*, otherwise it is undefined behavior, including core dump. It DOES matter whether memory is allocated. If you return 0, delete will NOT be invoked. Try it :)
Comment: Sorry couldn't resist the urge to reply this, but "Humility is one of the most powerful weapons in the arsenal of a developer. – JUST MY correct OPINION" reads like a great oxymoron :)  +1 for the comment from me!
Comment: @usta: Irony, too, is a very powerful weapon in the arsenal of the developer.  ;)
Comment: @usta, @JUST: Guys, you'd be better off opening a new thread for that: "What could count as a very powerful weapon in the arsenal of the developer?" I'd vote it up :)
Answer: I would have thought that the fact your constructor wasn't being called either was a bit of a clue.  As is the fact that you've got a segmentation fault going on when you run it.  What happens with new Object()?  Your memory is allocated (this is your operator new) and then your constructor is called.  How is your constructor called?  By dereferencing the pointer to your allocated memory....
If you stub out your operator new, everything works fine: you get the memory from the runtime, the constructor is called, the operator delete is called.  If you make an operator new that actually does things, you'll see operator delete (and your constructor) getting called too.


What is meant by "Top-End" and "Bottom-End"?

Question: When guitarists describe the sound of their guitars, a lot of terms are used.
What does a guitarist mean when they talk about top and bottom end?
Comment: Probably a great example of bottom-end is Spinal Tap's "Big Bottom", which has dual lead bass lines. :-)
Comment: There are several versions on the YouTube. It's a tongue-in-cheek song, in the typical crude Spinal Tap style. Oh, it's three basses, one of which is a double-neck. They were having some fun when they filmed that song.
Comment: I'll also recommend "Boris the Spider", by John Entwhistle, and almost any song Chris Squire is on with Yes. Both are well recognized for super-clean, high-fidelity, solid bass sound.
Answer: Top end refers to the treble tones on your guitar and bottom end refers to the bass tones; these are also referred to as 'highs' and 'lows'; and can be adjusted using the EQ on your amp.
Comment: The tone control on your guitar is the first stop, for those guitars with them.
Comment: Not just the EQ on your amp is used to adjust this. Pedals, rack mount equalizers, and even different guitars will affect these parameters.
Comment: Of course; EQ can be applied anywhere in the signal path, or at any time during production.  The EQ on the amp however is your first stop for your playing tone.
Comment: @the Tin Man: good point
Answer: DRL's right but, just for completeness, some occassionally use it to describe the overall quality of the sound.  "It's a low-end guitar but it sounds top-end," etc.
Comment: I'm pretty sure this usage is usually "low-end" vs. "high-end," as opposed to top and bottom being asked about here.
Comment: I've heard both, but low- and high-end are definitely more common.
Answer: Low End = bass
Top End = treble  (high end, etc.)
The terms describe the frequency domain of a tone.


Can't resolve spigot dependency in artifactory-snapshot

Question: I want to deploy my maven project from Gitlab to my Artifactory server, but it always says
[main] WARNING org.codehaus.plexus.PlexusContainer - The POM for org.spigotmc:spigot-api:jar:1.14.4-R0.1-SNAPSHOT is missing, no dependency information available
Downloading from artifactory-snapshot: https://maven.***.dev/artifactory/gitlab/org/spigotmc/spigot-api/1.14.4-R0.1-SNAPSHOT/spigot-api-1.14.4-R0.1-SNAPSHOT.jar
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - ------------------------------------------------------------------------
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - BUILD FAILURE
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - ------------------------------------------------------------------------
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - Total time:  14.005 s
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - Finished at: 2019-10-30T20:53:15Z
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - ------------------------------------------------------------------------
[main] ERROR org.apache.maven.cli.MavenCli - Failed to execute goal on project SpigotProject: Could not resolve dependencies for project dev.***:SpigotProject:jar:2.1-BETA: Could not find artifact org.spigotmc:spigot-api:jar:1.14.4-R0.1-SNAPSHOT in artifactory-snapshot

I think I should "import" spigot to my Artifactory server, but how do I do that? Or do I need to change my pom.xml?
I have these repositories
<repositories>
    <repository>
        <id>papermc-repo</id>
        <url>https://papermc.io/repo/repository/maven-public/</url>
    </repository>
    <repository>
        <id>spigot-repo</id>
        <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
    </repository>
</repositories>

And this dependency
<dependencies>
    <dependency>
        <groupId>org.spigotmc</groupId>
        <artifactId>spigot-api</artifactId>
        <version>1.14.4-R0.1-SNAPSHOT</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

I tried adding this to my repositories but it didn't work either
    <repository>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <id>central</id>
        <name>bintray</name>
        <url>https://maven.***.dev/</url>
    </repository>

I even removed the distribution management, but still no luck
<distributionManagement>
    <repository>
        <id>central</id>
        <name>60aee0014b49-releases</name>
        <url>http://maven.***.dev/artifactory/gitlab</url>
    </repository>
</distributionManagement>

Answer: I just forgot to add a remote repository.