text:
Q: Looping through a specific column and then assigning a value to a button I'm working on a school assignment where I import data into a DataGridView in WinForm from a CSV file. This all works perfect, however, now I want to assign a value to a button (In column 5, 6 and 8) These can all vary depending on what the value in the same row, in column 3 is. If the value from column 3 is "Input" on the same row, in column 5, the button needs to be "Input", the rest of the cells in that row after column 5 need to be readonly textboxes.
If the value from column 3 is "Output" on the same row, in column 5, the button needs to be "On", in column 6 it needs to be "Off" and in column 8 it needs to be "On #s"
I've tried:
Looping through all the cells, foreach loops, looping through column 3, but I'm not sure how I can change the value of button in the same row. (They also need to have a different function when you click them, but I think that is easier when I understand how this works)
Here is a preview of the CSV file that needs to be used.
This is the code I've written so far (thats working):
private void btnBevestig_Click(object sender, EventArgs e)
{
    try
    {
        LaadCSVToDataGrid(openFile.FileName);
        dataGridView1.Sort(dataGridView1.Columns[3], ListSortDirection.Ascending);
        dataGridView1.Columns[0].Visible = false;
        dataGridView1.Columns[1].ReadOnly = true;
        dataGridView1.Columns[2].Visible = false;
        dataGridView1.Columns[3].ReadOnly = true;
        dataGridView1.Columns[4].Visible = false;

        DataGridViewButtonColumn btnInput = new DataGridViewButtonColumn();
        dataGridView1.Columns.Add(btnInput);
        btnInput.HeaderText = "Functie";
        btnInput.Text = "Input";
        btnInput.Name = "colInput";
        btnInput.UseColumnTextForButtonValue = true;

        DataGridViewButtonColumn btnOff = new DataGridViewButtonColumn();
        dataGridView1.Columns.Add(btnOff);
        btnOff.HeaderText = "";
        btnOff.Text = "Off";
        btnOff.Name = "colInput";
        btnOff.UseColumnTextForButtonValue = true;

        DataGridViewTextBoxColumn txtAantalSeconden = new DataGridViewTextBoxColumn();
        dataGridView1.Columns.Add(txtAantalSeconden);
        txtAantalSeconden.HeaderText = "";
        txtAantalSeconden.Name = "txtAantalSec";
        txtAantalSeconden.ReadOnly = false;

        DataGridViewButtonColumn btnOnSec = new DataGridViewButtonColumn();
        dataGridView1.Columns.Add(btnOnSec);
        btnOnSec.HeaderText = "";
        btnOnSec.Text = "Aantal seconden";
        btnOnSec.Name = "colInput";
        btnOnSec.UseColumnTextForButtonValue = true;

        btnOntgrendel.Enabled = true;
        comboBoxProfiel.Enabled = false;
        btnBevestig.Enabled = false;
        btnKiesProfiel.Enabled = false;
        btnNieuwProfiel.Enabled = false;

    }
    catch (Exception error)
    {
        MessageBox.Show(
            error.Message,
            "Fout",
            MessageBoxButtons.OK,
            MessageBoxIcon.Warning
            );
    }
}

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    Console.WriteLine(e.ColumnIndex);
    Console.WriteLine(e.RowIndex);
    if (e.ColumnIndex == 3 && e.RowIndex >= 0)
    {
        if (dataGridView1[e.ColumnIndex, e.RowIndex].ToString() == "Input")
        {
            dataGridView1[5, e.RowIndex].Value = "Input";
            Console.WriteLine(e.ColumnIndex);
            Console.WriteLine(e.RowIndex);
        }
    }
}

A: Since the additional columns are added after populating the data, you need to loop over and set the values of the target cells according to the value of the Input cells.
private void UpdateCells()
{
    foreach (var r in dataGridView1.Rows.OfType<DataGridViewRow>()
        .Where(x => !x.IsNewRow))
    {
        var v = r.Cells[3].Value?.ToString();

        if (v == "Input")
        {
            r.Cells[5].Value = "Input";
            // other changes ...
        }
        else
        {
            r.Cells[5].Value = "On";
            // Other changes ...
        }
    }
}

Call this method after setting up the grid:
private void btnBevestig_Click(object sender, EventArgs e)
{
    try
    {
        LaadCSVToDataGrid(openFile.FileName);
        dataGridView1.Sort(dataGridView1.Columns[3], ListSortDirection.Ascending);
        dataGridView1.Columns[0].Visible = false;
        btnInput.UseColumnTextForButtonValue = false;
        // ...

        UpdateCells()
    }
    catch { ... }
}

If the values of the read-only third column are changed at runtime by code, then handle the CellValueChanged event as well to update the target cells:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 3 && e.RowIndex >= 0 && !dataGridView1.Rows[e.RowIndex].IsNewRow)
    {
        var v = dataGridView1[e.ColumnIndex, e.RowIndex].Value?.ToString();

        if (v == "Input")
        {
            dataGridView1[5, e.RowIndex].Value = "Input";
            // other changes ...
        }
        else
        {
            dataGridView1[5, e.RowIndex].Value = "On";
            // Other changes ...
        }
    }
}


text:
Q: R: cbind function in for loop c <- readline(prompt="Enter an integer: ")
b <- readline(prompt="Enter an integer: ")

for(i in 1:c){
assign(paste("a", i, sep = ""), i)
}

This gives a1, a2 ... ac variables containing 1,2 ... c
How can I use cbind based on the value of b? For example, take the following:
# assume b = 3 and c = 12:

t1 <- cbind(a1,a2,a3)
t2 <- cbind(a4,a5,a6)
t3 <- cbind(a7,a8,a9)
t4 <- cbind(a10,a11,a12)

# assume b = 4 and c = 12:

t1 <- cbind(a1,a2,a3,a4)
t2 <- cbind(a5,a6,a7,a8)
t3 <- cbind(a9,a10,a11,a12)

Another example to clarify: assume b = 3, c=6
a1 <- c(3,5,2)
a2 <- c(4,7,3)
a3 <- c(3,5,2)
a4 <- c(4,5,3)
a5 <- c(5,5,5)
a6 <- c(4,3,1)

t1 <- cbind(a1,a2,a3)
t2 <- cbind(a4,a5,a6)

Expected value of t1:
3 4 3
5 7 5
2 3 2

A: I am making some assumptions about your data. I am assuming you have values assigned with the columns you are trying to cbind.
a <- 12
b <- 3
test <- NULL
index <- NULL
for(i in 1:a){
 test[i] <- paste0("n_", i)
 index[i] <- paste(i)
}

start <- seq(1,a-b+1, by=b)
end <- seq(b,a, by=b)

s = list()
k=1
for(k in 1:length(start)){
cbind_list <- start[k]:end[k]
s[[k]] <- rbind(test[seq(cbind_list[1],cbind_list[length(cbind_list)],by=1)])
}
list_cols <- do.call(rbind, s)

n_1 <- rep(1,4)
n_2 <- rep(2,4)
n_3 <- rep(3,4)
n_4 <- rep(4,4)
n_5 <- rep(5,4)
n_6 <- rep(6,4)
n_7 <- rep(7,4)
n_8 <- rep(8,4)
n_9 <- rep(9,4)
n_10 <- rep(10,4)
n_11 <- rep(11,4)
n_12 <- rep(12,4)
df <- data.frame(n_1,n_2,n_3,n_4,n_5,n_6,n_7,n_8,n_9,n_10,n_11,n_12)

t=list()
for(p in 1:nrow(list_cols)){
nam <- paste0("t",p)
assign(nam,cbind(df[,match(list_cols[p,], colnames(df))]))
}

OUTPUT:
> t1
  n_1 n_2 n_3
1   1   2   3
2   1   2   3
3   1   2   3
4   1   2   3

UPDATED:
a <- 6
b <- 3
test <- NULL
index <- NULL
for(i in 1:a){
  test[i] <- paste0("n_", i)
  index[i] <- paste(i)
}

start <- seq(1,a-b+1, by=b)
end <- seq(b,a, by=b)

s = list()
k=1
for(k in 1:length(start)){
  cbind_list <- start[k]:end[k]
  s[[k]] <- rbind(test[seq(cbind_list[1],cbind_list[length(cbind_list)],by=1)])
}
list_cols <- do.call(rbind, s)

n_1 <- c(3,5,2)
n_2 <- c(4,7,3)
n_3 <- c(3,5,2)
n_4 <- c(4,5,3)
n_5 <- c(5,5,5)
n_6 <- c(4,3,1)

df <- data.frame(n_1,n_2,n_3,n_4,n_5,n_6)

t=list()
p=1
for(p in 1:nrow(list_cols)){
  nam <- paste0("t",p)
  assign(nam,cbind(df[,match(list_cols[p,], colnames(df))]))
}

OUTPUT:
> t1
  n_1 n_2 n_3
1   3   4   3
2   5   7   5
3   2   3   2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Formula for curl in polar coordinates using covariant differentiation For the plane in polar coordinates $(r,\theta)$ with metric $$ds^2=dr^2+r^2d\theta^2,$$
the curl on a vector field $v^a\partial_a$ is given by the rank-2 antisymmetric tensor $\nabla_av_b-\nabla_bv_a$. This tensor  has only one independent & non-zero component:
$$\nabla_rv_\theta-\nabla_\theta v_r=\partial_rv_\theta - \Gamma_{r\theta}^av_a -\partial_\theta v_r +\Gamma^a_{\theta r}v^a=\partial_rv_\theta-\partial_\theta v_r$$
since $\Gamma^a_{\theta r} = \Gamma^a_{r \theta }$. Expressed in contravariant vector components, $$\nabla_rv_\theta-\nabla_\theta v_r=\partial_r (g_{\theta a}v^a)-\partial_\theta (g_{rb}v^b)=\partial_r(r^2v^\theta)-\partial_\theta(v^r)=2rv^\theta+r^2\partial_rv^\theta-\partial_\theta v^r$$
I am trying to compare this to the formula for curl in vector calculus:
$$\nabla\times \textbf{v} = \frac{1}{r}\left[\frac{\partial}{\partial r}(rv^\theta) - \frac{\partial}{\partial\theta}v^r\right] \vec{\hat{z}}=\left[\frac{1}{r}v^\theta+\partial_rv^\theta-\frac{1}{r}\partial_\theta v^r\right]\vec{\hat{z}}$$, where $\vec{\hat{z}}$ is the unit vector pointing out of the plane.
The difference in the two formulas is because in manifolds we used the coordinate basis $\partial_\theta$ while in vector calculus we used the normalized coordinate basis $\frac{1}{r}\partial_\theta$. In the coordinate basis, $\textbf{v}=v^r\partial_r+v^\theta\partial_\theta$ while in the normalized coordinate basis, $\textbf{v}=v^r\partial_r+v^\theta\frac{1}{r}\partial_\theta$.
Thus to convert between  the 'manifold' formula and the 'vector calculus' formula, we just have to rescale the $v^\theta$ component of the vector.
From the 'manifold' formula, replace $v^\theta\rightarrow \frac{v^\theta}{r}$ to get the 'vector calculus' formula:
$$\nabla_rv_\theta-\nabla_\theta v_r=2rv^\theta+r^2\partial_rv^\theta-\partial_\theta v^r \rightarrow2r\frac{v^\theta}{r}+r^2\partial_r\frac{v^\theta}{r}-\partial_\theta v^r =v^\theta+r\partial_rv^\theta -\partial_\theta v^r$$
However, this answer larger than the correct formula by a factor of $r$. Why is that so?

A: Say $(M,g)$ is a $2$-dimensional oriented Riemannian manifold, and let $\star$ be the Hodge star operator. Given a vector field $F$ on $M$, we define
\begin{align}
\text{curl}(F)&:=\star d(g^{\flat}F)
\end{align}
i.e we take our vector field $F$, convert it to a covector field $g^{\flat}(F)$, take its exterior derivative (so we now have a $2$-form) and finally take its Hodge dual to get a smooth function (since we're on a $2$-dimensional manifold). The fact that the curl of a vector field in $2$-dimensions yields a smooth function corresponds to your observation that there's only one non-vanishing term. The thing you're missing is the final Hodge star (the extra $r$ you have is the same $r$ in $dx\wedge dy=r\,dr\wedge d\theta$).
Explicitly, suppose we're in the plane and using polar coordinates. Suppose $F=f^r\mathbf{e}_r+ f^{\theta}\mathbf{e}_{\theta}$ is the expansion in terms of unit vector fields (as in vector calculus). Then, $g^{\flat}(F)=f^r\,dr +f^{\theta}\,rd\theta$ (here this factor of $r$ is the norm of $\frac{\partial}{\partial \theta}$, i.e $\sqrt{g_{\theta\theta}}=\sqrt{r^2}=r$). So,
\begin{align}
d(g^{\flat}(F)) &=
\left(\frac{\partial f^r}{\partial r}\,dr+\frac{\partial f^r}{\partial \theta}\,d\theta\right)\wedge dr +
\left(\frac{\partial (rf^{\theta})}{\partial r}\,dr+\frac{\partial (r f^{\theta})}{\partial \theta}\,d\theta\right) \wedge d\theta\\
&=\left(\frac{\partial (r f^{\theta})}{\partial r}-\frac{\partial f^r}{\partial \theta}\right)dr\wedge d\theta\tag{$*$}\\
&=\frac{1}{r}\left(\frac{\partial (r f^{\theta})}{\partial r}-\frac{\partial f^{r}}{\partial \theta}\right)\, rdr\wedge d\theta
\end{align}
In the last line, I simply divided and multiplied by $r$.
The reason for this is that the area-form in the plane is $dx\wedge dy=r\,dr\wedge d\theta$, and the nice thing about the Hodge star is that for any function $\phi$ and the area form $\omega$, we have $\star(\phi \, \omega)=\phi (\star\omega)=\phi\cdot 1$, i.e $\star(r\,dr\wedge d\theta)=1$. Therefore,
\begin{align}
\text{curl}(F)&=\star d(g^{\flat}(F))=\frac{1}{r}\left(\frac{\partial (r f^{\theta})}{\partial r}-\frac{\partial f^{r}}{\partial \theta}\right)
\end{align}

Where you went 'wrong'
Note that in your calculation, you stopped at $(*)$, i.e the expression you found is the component of a $2$-form (the coefficient of $dr\wedge d\theta$). Inherently, there's nothing wrong with that, but the classical definition of curl requires an extra Hodge star application. So really, it boils down to the fact that your initial expression $\nabla_av_b-\nabla_bv_a$ is the component of a $2$-form, but it is NOT the usual definition of curl.

Extra Ramblings.
For a vector field $F$ in $\Bbb{R}^3$, the definition of curl must be modified slightly:
\begin{align}
\text{curl}(F)&:=g^{\sharp}(\star d(g^{\flat}F))
\end{align}
i.e we convert the vector field $F$ to a $1$-form $g^{\flat}(F)$, take its exterior derivative (so we have a $2$-form now), then take the Hodge star (so we get a $3-2=1$-form) and finally use $g^{\sharp}$ to convert it back to a vector field (as a side remark: from this one can already see that the curl of a vector field is an EXTREMELY unnatural operation, and it's unfortunate we use it so often in elementary vector calculus).
BTW, if you want to think of a vector field in $\Bbb{R}^2$ as a vector field in $\Bbb{R}^3$, you can do so by thinking of it as having no $z$ component, in which case applying this 3-D definition of curl will yield a vector field having only a $\mathbf{e}_z$ component, which matches with what we found above (so overall there's no inconsistency in jumping between $2$ and $3$ dimensions).


text:
Q: Detect shutdown/reboot in OSX from C++ app How can I detect a shutdown/reboot on OSX from a C++ application?
I need to report that the system is gonna shutdown/reboot to a central server sending a packet so it should be fast enough so network interfaces don't go down before the packet is sent.
Thanks


text:
Q: Execute Query on a Specific Date and Time Is there a possible way to execute a query on a specific given Date and Time using PHP or ODBC
$date = '11/30/2013 11:59 AM';

Insert into tbl1 (id,name,age) values ('$id','$name','$age');

A: The software utility CRON is something that can help you schedule jobs and this is generally found in Unix based operating Systems. So if you are using some Unix based hosting, they maybe providing you a scheduler that can help you execute a particular PHP script at a particular interval.
This is the link to BlueHost page that tells you ways to set up CRON with your PHP. Similarly you can find ways to do this at your own hosting. I am sure there is not a lot of programming involved, just you need to make sure how can you initialize CRON at your server or hosting and then you can write your PHP scripts in normal fashion (like you always do)
One thing more, if your hosting is providing you Cpanel (which most hostings do these days), this link might then be helpful for you. Happy Scheduling :)


text:
Q: Can anyone explain the unit for rate of expansion of universe? If you google for 'what is rate of expansion of universe' you get

Space itself is pulling apart at the seams, expanding at a rate of 74.3 plus or minus 2.1 kilometers (46.2 plus or minus 1.3 miles) per second per megaparsec (a megaparsec is roughly 3 million light-years).

Can anyone please explain what does the unit mean? what is 'per second per megaparsec'?
I believe x km/s would suffic the rate of expansion. Not sure what 'per megaparsec' specifies?

A: The hubble relation is:
$$v = H d$$
where $v$ is the velocity of the galaxy relative to the Milky way, and $d$ is the distance of the galaxy relative to the milky way.  The velocity is measured using redshift.  The distance is measured through a complicated series of standard candles, along with the relationship $I = \frac{I_{0}}{4\pi r^{2}}$.
If you notice, these are related by Hubble's constant $H$.  This tells us how fast something is moving apart, based on how far away it is.  Namely, it's the rate of expansion of the universe.  Since astronomers measure distance in a unit called a parsec, and velocity at these high speeds is naturally measured in km/s, we can see that the "natural" units astronomers use for $H$ are (km/s)/parsec., since that's the only way to get km/s out when you multiply by something measured in parsec.

A: As time goes along, everything in the universe expands by a dimensionless scale factor a(t).  This $a(t)$ is the scale factor seen in the Robertson-Walker metric.  Some galaxy at a distance $x_0$  at time $t_0$, will be at $x(t)$ at time $t$.
$$
x(t)=a(t) \quad x_0
$$
Taking the derivative wrt t gives
$$
\dot{x}=\dot{a}\quad x_0
$$
and dividing by the first equation gives
$$
\frac{\dot{x(t)}}{x(t)}=\frac{\dot{a(t)}}{a(t)}\equiv H(t)
$$
where the Hubble Constant is a function of time and its value now is measured to be $H_0=70 [\frac{km/sec}{Mpc}]$ so we get the familiar "now" Hubble Law
$$
\dot{x}=H_0 x
$$
Astronomers like megaparsecs (Mpc) as a unit of distance, where
$$
1 [Mpc] = 3*10^6[lyrs] = 3 * 10^{22}[m]
$$
The Hubble Constant can be expressed in may different units.  For example
$$
H_0=70[\frac{km/sec}{Mpc}]*10^3[\frac{m}{km}]*\frac{1}{3*10^{22}}[\frac{Mpc}{m}]
=2*10^{-18}[\frac{m/sec}{m}]
$$
or
$$
c*H_0=70[\frac{km/sec}{Mpc}]*10^3[\frac{m}{km}]*\frac{1}{3*10^{22}}[\frac{Mpc}{m}]*3*10^8[\frac{m}{sec}]
=7*10^{-10}[\frac{m}{sec^2}]
$$
which is an acceleration in nice everyday mks units.

A: Can anyone please explain what does the unit mean? what is 'per second per megaparsec'? I believe x kms per sec would suffic the rate of expansion. Not sure what 'per megaparsec' specifies?
The mega-parsec unit is required because each mega-parsec of distance is expanding at a rate of 74.3 km/s. So, if two side-by-side mega-parsecs expand in one second, the total expansion is 148.6 km. The "per mega-parsec" forces you to do a summation over vast distances.
Great question BTW!


text:
Q: Maintaining event order in log4j + MongoDB I'm investigating MongoDB as a log repository. I've set up a basic MongoDB server, configured Log4j, and everything seems to work.
However:

*

*I'm aware that MongoDB writes are asynchronous (and I don't want to kill performance by making them synchronous)

*The timestamp in the log records appears to be accurate only to the millisecond

*My app logs more than once per millisecond

*I need to be able to see the sequence in which the events were logged

Is there a way I can get more granular timestamps?
Is there a way I can inject sequence numbers on the client side (short of having the client put them in the log message)?

A: MongoDB inserts are sequential since write locks are process wide. As such you are guaranteed that MongoDB will return the log entries in the order it received them. Use sort({$natural:1}) to get them back in order.
Note that although writes are asynchronous they are ordered.


text:
Q: bash variables: expanding the values of variables whose names match a pattern Let's say in bash I have several variables: POD3_1, POD3_A, POD3_2, POD3_B, etc. Each of the variables names begins with "POD3". Let's say I want to expand the value of all the variables on the command line so that I can use these values in a script:
for H in $POD3_1 $POD3_A ...
do
...
done

Instead of writing out each of the variable names by hand as shown above (because there are so many), is there a way to do this so that any variable name matching "POD3" is expanded? In other words, a "wildcard" for variable name?

A: You can use bash's curly brace expansion. {..}
If for instance, your variables are POD3_1, POD3_2 till 9 and POD3_A, POD3_B, till M, you can do something like this -

  for H in $POD3_{1..9} $POD3_{A..M}
  do
     ...
  done

If the variable names are not a sequence, you can use the comma separator -
$POD3_{1,A,F}

A: You can simply loop over the output of env.
env | awk -F = '$1 ~ /^POD3_/ { print $1 }' |
while read var; do
    :
    :
done

The Awk script examines each variable name, and only prints it if it matches the pattern.
What you have inside the loop is the variable's name, not its value.  In Bash, you can use ${!var} to interpolate it; in POSIX sh, I imagine you would have to resort to evak, or modify the loop to directly loop over values instead of variable names.
This will still somewhat suck if you have multi-line variables, but the probability for a false positive is rather low. (Less so if you switch to looping over values.)

A: If you're using bash version 4, use an associative array instead of having to manage dozens of variables:
declare -A POD3=(
  [1]=value_1
  [2]=value_2
  [A]="value a"
  [B]="value b"
  [C]="value c"
)

echo "${POD3[A]}"

for key in "${!POD3[@]}"; do
  echo "$key => ${POD3[$key]}"
done


text:
Q: NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null Occurs exception when I get the chapter list.
So how can I solve this problem?
Please help.
Here is my API response.
{
  "success": 1,
  "chapter": [
    {
      "chapter_id": "609cb13f497e3",
      "chapter_name": "test",
      "subject_id": "5e32874c714fa",
      "medium_id": "5d15938aa1344",
      "standard_id": "5d1594e283e1a",
      "material": null,
      "textbook": null,
      "test_paper": null,
      "test_paper_solution": null,
      "subject_memory_map": null,
      "active": "1"
    }
  ]
}

The model class which I created in chapter_model.dart file.
// To parse this JSON data, do
//
//     final chapterBySubjectModel = chapterBySubjectModelFromJson(jsonString);

import 'dart:convert';

ChapterBySubjectModel chapterBySubjectModelFromJson(String str) => ChapterBySubjectModel.fromJson(json.decode(str));

String chapterBySubjectModelToJson(ChapterBySubjectModel data) => json.encode(data.toJson());

class ChapterBySubjectModel {
    ChapterBySubjectModel({
        required this.success,
        required this.chapter,
    });

    int success;
    List<Chapter> chapter;

    factory ChapterBySubjectModel.fromJson(Map<String, dynamic> json) => ChapterBySubjectModel(
        success: json["success"],
        chapter: List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "success": success,
        "chapter": List<dynamic>.from(chapter.map((x) => x.toJson())),
    };
}

class Chapter {
    Chapter({
        required this.chapterId,
        required this.chapterName,
        required this.subjectId,
        required this.mediumId,
        required this.standardId,
        this.material,
        this.textbook,
        this.testPaper,
        this.testPaperSolution,
        this.subjectMemoryMap,
        required this.active,
    });

    String chapterId;
    String chapterName;
    String subjectId;
    String mediumId;
    String standardId;
    dynamic material;
    dynamic textbook;
    dynamic testPaper;
    dynamic testPaperSolution;
    dynamic subjectMemoryMap;
    String active;

    factory Chapter.fromJson(Map<String, dynamic> json) => Chapter(
        chapterId: json["chapter_id"],
        chapterName: json["chapter_name"],
        subjectId: json["subject_id"],
        mediumId: json["medium_id"],
        standardId: json["standard_id"],
        material: json["material"],
        textbook: json["textbook"],
        testPaper: json["test_paper"],
        testPaperSolution: json["test_paper_solution"],
        subjectMemoryMap: json["subject_memory_map"],
        active: json["active"],
    );

    Map<String, dynamic> toJson() => {
        "chapter_id": chapterId,
        "chapter_name": chapterName,
        "subject_id": subjectId,
        "medium_id": mediumId,
        "standard_id": standardId,
        "material": material,
        "textbook": textbook,
        "test_paper": testPaper,
        "test_paper_solution": testPaperSolution,
        "subject_memory_map": subjectMemoryMap,
        "active": active,
    };
}

Method which i Created in api_manager.dart file.
Future<List<Chapter>> getChapterBySubject() async {
    final chapterUrl =
        '$baseUrl/subject/get_by_user_plan?user_id=609cab2cd5b6c&order_id=1620889722609cd07a601af469889697609cab2cd5b6c&standard_id=5d1594e283e1a&medium_id=5d15938aa1344';
    final response = await http.get(Uri.parse(chapterUrl));
    if (response.statusCode == 200) {
      final chapterData = chapterBySubjectModelFromJson(response.body);

      final List<Chapter> chapters = chapterData.chapter;
      print(chapters);
      return chapters;
    } else {
      return <Chapter>[];
    }
  }

And view as below in chapter_widget.dart file.
class _ChapterWidgetState extends State<ChapterWidget> {
  late bool _loading;
  var _chapters = <Chapter>[];

  @override
  void initState() {
    super.initState();
    _loading = true;

    ApiManager().getChapterBySubject().then((chapters) {
      setState(() {
        _chapters = chapters;
        _loading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: null == _chapters ? 0 : _chapters.length,
        //itemCount: _chapters.length,
        itemBuilder: (context, index) {
          Chapter chapter = _chapters[index];

          return Container(
            padding: EdgeInsets.all(8),
            child: Card(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(20.0),
                child: InkWell(
                  //child: Image.asset("assets/logos/listbackground.png"),
                  child: Text(chapter.chapterName),
                ),
              ),
            ),
          );
        });

  }
}

It throws an Exception in Model Class in below line.
List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),

A: You set chapter as required but it seems API says it can be null. So, you should convert your parameters from required to nullable like this:
import 'dart:convert';

ChapterBySubjectModel chapterBySubjectModelFromJson(String str) => ChapterBySubjectModel.fromJson(json.decode(str));

String chapterBySubjectModelToJson(ChapterBySubjectModel data) => json.encode(data.toJson());

class ChapterBySubjectModel {
    ChapterBySubjectModel({
        this.success,
        this.chapter,
    });

    int success;
    List<Chapter> chapter;

    factory ChapterBySubjectModel.fromJson(Map<String, dynamic> json) => ChapterBySubjectModel(
        success: json["success"] == null ? null : json["success"],
        chapter: json["chapter"] == null ? null : List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "success": success == null ? null : success,
        "chapter": chapter == null ? null : List<Chapter>.from(chapter.map((x) => x)),
    };
}


text:
Q: How does one factor out reusable components in views in the Play framework? I'm looking to properly factor my views, to not generate much duplication. I'm using the Play framework, and the elements I'd like to factor out are basic common ones - headers, footers, navigation elements.
What is the standard pattern for this type of factoring? When I read about the view inheritance features, they sound as if they don't allow for reuse of components.
I'm working with version 2.0 of Play.

Say, for example, that I have a common layout for multiple pages, and I'm looking to have swappable bits - say, the central content bit, and the footer, where different pages I'm displaying have different combinations of footer and content.

A: There's two things that I can think of. The first one is when you have the skeleton of a page and you want each of your views to fill in one of the parts of that skeleton, for example, this would be your skeleton:
main.html:
<!DOCTYPE HTML>

        <title>#{get 'title' /}</title>

        #{doLayout /}

And this would be one of the pages that uses it:
ex1.html:
#{extends 'main.html' /}
#{set title:'Your title' /}

   Your content

That way you don't have to worry about all the common "wrapper" code, and the same way you set the title in that example, you can also add stylesheets or javascript links to the headers.
The second way is to have a page that includes snippets that you do in separate templates, so that you can reuse them:
example2.html:

   #{include 'Application/footer.html' /}

footer.html:
This will be rendered inside the "footer" div

Not sure if from such a simple explanation is clear when to use which one, I think once you get the difference is pretty natural, I use both all the time.

A: You should use combination of layouts and tags as described in the documentation.
Layout wraps current view, so it's best place for starting and ending the HTML structure, adding scripts into head section of the hTML doc, and placing typical elements - such as stable header with logo, footer with copyrights etc. If you have the same main navigation on all pages, you can put it in layout too, then you can add params to the layout view to make it possible easily changing CSS classes for the active item. Note, that if you have for an example 2 different versions of main nav (for an example, one for common users, second for administrators only), you can just create 2 different layouts or use one layout and display two different versions depending on some param passed from the initial view.
Tags are used for injecting code into current view (so they has just opposite role than layouts). They are a common views without layout, and are functions with params too. They are used mainly for placing things that are changing on every page or even request - for an example notice boxes (from the doc: success, error, etc). Also they are useful for subnavigation, especially, when it's changes on every 'branch' from main navigation and it's possible, that on some pages it should not be displayed at all.
You can also use tags in the layouts (and probably, vice versa) so as you can see, there are many possibilities :)
Note: palako's sample illustrates it quite well, but it's typical for Play 1.x templating engine, for Play 2.x check referenced documentation and/or sample application delivered with the source of Play.


text:
Q: Регулярное выражение (выбор блоков span из разметки) Есть например такая переменная:
$htm = <<<<HTML

.....

....
....
....
....
....

.....

......
......
....
....
HTML;

т.е. переменная содержит html код, в котором встречаются элементы , они могут находиться в разных блоках и вообще по всему коду разбросаны, как с помощью регулярки отпарсить их таким образом, чтоб получился массив, значения которого были эти span'ы, т.е.
for ($i = 0; $i < count(array); $i++) {
echo $array[$i];
}

чтоб вывел span'ы вместе с их содержимым:
....
....
....
....
....
....
....

A: Используйте лучше библиотеку SimpleHTMLDOM. Регулярки не лучшее решение для парсинга html. На счет сложности не волнуйтесь, библиотека очень проста в использовании.
A: Для объявления строки подобным образом используется три угловые скобки
$htm = <<<HTML

....
....
....
....
....

....
....
HTML;

preg_match_all('~.*~Uis',$htm,$arr);

в $arr список span'ов с содержимым

вложенные span'ы могут доставить проблем, там нужен иной подход или пользоваться DOM
A: @.*@i


text:
Q: Android Studio start activity when detected an bluetooth device by MAC Address/UUID? I am making application that will run specific activity when detected an bluetooth iBeacon (not when connected because iBeacon is just transmiting signal)
I have multiple iBeacons each one will start different activity so the application need to recognize each beacons by MAC Address/UUID
My Application are now able to scan iBeacon device
but to make them start activity and recognize each one. I don't know how to start

I used the code from here (not my project)
https://github.com/danasf/hm10-android-arduino/tree/master/Android/BT4LEDTest
I didn't change his code much so it should be similar to my current code (if I post all my code it's exceed 30000 char limit)

A: for specific device, you will get list of available device nearby apart from it you will get information like  mac as each device as unique mac id
You can start activity from service once you get onConnectionStateChange callback where Bluetooth device is connected.
or
you can broadcast event for successful connection event and 'onreceive()'  start activity.


text:
Q: Load file and copy it and save to new folder? How can I copy a file and save it to a new specified folder?
String pathOne = "path";
File file1 = new File(pathOne);

String pathTwo = "path";

save file1 to new directory

A: You can use apache commons library. It has FileUtils class that makes that kind of operations easy
https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
in your case copyFile(File srcFile, File destFile) function is what you are looking for


text:
Q: Python urlib and authentication I need help authenticating logging into this site using urllib. I am using python 3, but I'm willing to revert to 2.x.
This is what I have sofar (basically from the documentation), it gives not errors, but its not logging in.
file =open("loggedinsource.html",'wb')

# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='kalahari.net',uri='https://www.kalahari.net/profile/pipeline/signin.aspx?',user='myuser',passwd='mypass')

opener = urllib.request.build_opener(auth_handler)

# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
f=urllib.request.urlopen('https://www.kalahari.net/profile/pipeline/signin.aspx?')

page=f.read()
file.write(page);
file.close()

I have been struggling with this for ages, any help please.

A: The site you are trying to log into is not using HTTP basic auth; it is using a regular HTML form.
If you want to log into something like this, you probably want to look at something like mechanize


text:
Q: MySQL LOAD_FILE() loads null values I'm attempting to load a directory of xml files into a database table as blobs.  Each row would contain a corresponding blob file.  When loading files via a python script into the table, values are inserted as null.  This is also the case when running an equivalent command in the mysql command line.
At one point I was able to insert values after changing some folder permissions to mysql, but due to needed scripting privileges I had to modify ownership of the directory /var/lib/mysql/foo, thus values are being reinserted as null effectively breaking the script I wrote.  I cannot remember the necessary change of directory permissions to do so.
The following are discussions of the topic:
http://bugs.mysql.com/bug.php?id=38403
along with
MySQL LOAD_FILE returning NULL

A: Make sure:

*

*there is execute permission on the parent directory

*The FILE privilege must is explicily granted. (GRANT FILE on . TO user@localhost)

*You have flushed privileges

*You have logged out and logged back in

Example of permission on parent dir:

mysql> \! ls -ld `dirname /home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg`
drwxrwxr--. 2 jlam jlam 4096 May 12 14:22 /home/jlam/code/projectName/doc/filesForTesting/images

mysql> select hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/image

Test01.jpg'));
+-------------------------------------------------------------------------------------------------------------+
| hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg')) |
+-------------------------------------------------------------------------------------------------------------+
| NULL                                                                                |
+-------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> \! chmod o+x /home/jlam/code/projectName/doc/filesForTesting/images
mysql> \! ls -ld `dirname /home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg`
drwxrwxr-x. 2 jlam jlam 4096 May 12 14:22 /home/jlam/code/projectName/doc/filesForTesting/images
mysql> select hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg'));
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg'))
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| FFD8FFE1001845786966000049492A00080000000000000000000000FFEC00114475636B7900010004000000500000FFE10407687474703A2F2F6E732E61646F62652E636F6D2F7861702F312E302F003C3F787061636B657420626567696E3D22EFBBBF222069643D2257354D304D7043656869487
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Example of user privileges:

16:38:09 (getImages) ~/code/projectName/doc/filesForTesting/images$ mysql -u eventCal -p eventCal
Enter password:

mysql> show grants;
+-----------------------------------------------------------------------------------------------------------------+
| Grants for eventCal@localhost                                                                                |
+-----------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'eventCal'@'localhost' IDENTIFIED BY PASSWORD '*xxxx' |
| GRANT ALL PRIVILEGES ON `tmp`.* TO 'eventCal'@'localhost'                                                       |
| GRANT ALL PRIVILEGES ON `eventCalTesting`.* TO 'eventCal'@'localhost'                                           |
| GRANT ALL PRIVILEGES ON `eventCal`.* TO 'eventCal'@'localhost'                                                  |
| GRANT ALL PRIVILEGES ON `eventCal_categoryMigration`.* TO 'eventCal'@'localhost'                                |
+-----------------------------------------------------------------------------------------------------------------+
5 rows in set (0.00 sec)

mysql> select hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg'));
+-------------------------------------------------------------------------------------------------------------+
| hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg')) |
+-------------------------------------------------------------------------------------------------------------+
| NULL                                                                                |
+-------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

In other root session:

mysql> grant file ON *.*  to eventCal@localhost;
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

Back in user session, I still can't load the file

mysql> select hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg'));
+-------------------------------------------------------------------------------------------------------------+
| hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg')) |
+-------------------------------------------------------------------------------------------------------------+
| NULL                                                                                |
+-------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

.....But if I log out and back in:

mysql> exit
Bye

16:40:14 (getImages) ~/code/projectName/doc/filesForTesting/images$ mysql -u eventCal -p eventCal
Enter password:

mysql> select hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg'));
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| hex(LOAD_FILE('/home/jlam/code/projectName/doc/filesForTesting/images/imageTest01.jpg'))
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| FFD8FFE1001845786966000049492A00080000000000000000000000FFEC00114475636B7900010004000000500000FFE10407687474703A2F2F6E732E61646F62652E636F6D2F7861702F312E302F003C3F787061636B657420626567696E3D22EFBBBF222069643D2257354D304D7043656869487
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

A: I have lost some time with this problem. In my case, the problem had to do with secure_file_priv variable defined in "my.ini".
From MySQL documentation:

If the secure_file_priv system variable is set to a nonempty
  directory name, the file to be loaded must be located in that
  directory

So, there are two ways:
1)remove this option
2) use the default folder for uploading files ("C:\ProgramData\MySQL\MySQL Server 5.7\Uploads"). I also had to use double slash in Windows.

A: In order for load file to work make sure that all permissions are granted for the MySQL owner and group.
chown mysql:mysql /var/lib/mysql/foo/*
chmod go+rw /var/lib/mysql/foo/*

A: I copied my file to the location where MySQL has access to.
To know the location I used:
select @@secure_file_priv;

and it gave me /var/lib/mysql-files/.

Nothing else worked: neither turning off apparmor, nor changing ownership and permissions, nor merely granting the file privilege. So I rolled back most of that but the right directory still works. In my case.

My source is Raymond Nijland, here: https://dba.stackexchange.com/questions/190380/load-file-producing-null

A: I had tried all the other answers here. After quite a bit of trial and error discovered that my issue was that secure-file-priv was not set to anything at all. When I set this value to a directory path in my.conf and ensured the permissions were set correctly, files could finally be accessed
add to my.conf:
secure_file_priv="/test/"
I think this answer is specific to mysql running on mac

A: I copied the image in /var/lib/mysql/images ( after creating images folder) and it worked!

A: It could be due to the SO security constraits. In fact, I was able to solve the problem by disabling the MySQL profile in AppArmour
The procedure I followed was to check whether there was a profile loaded for mysql
sudo aa-status

and then disabling it
sudo ln -s /etc/apparmor.d/usr.sbin.mysqld /etc/apparmor.d/disable/
sudo apparmor_parser -R /etc/apparmor.d/usr.sbin.mysqld

https://www.cyberciti.biz/faq/ubuntu-linux-howto-disable-apparmor-commands/

A: Acubo solved my issue with the Null Blob inserts. In the MySql my.ini file, the secure-file-priv was set to a specific folder that I do not use, that is why it ignored my path in the LOAD_FILE. Acubo said to make sure the secure-file-priv setting is set to empty. It will then use the hardcoded path in the LOAD_FILE statement.
my.ini
Secure File Priv. Modified by Frank Salinas 12/11/2019 secure-file-priv must null in order to query directories other than the hard coded directory
secure-file-priv="C:/ProgramData/MySQL/MySQL Server 5.7/Uploads"
secure-file-priv=""

A: I was running mysql 8.0.26 in a docker container and I checked all the conditions mentioned in the docs:

*

*File privilege on my mysql user

*secure_file_priv not set to any non-empty dir. I actually had it set to NULL

*I didn't exceed max_allowed_packet with the file I tried to load

*The file was located on the host

*I specified full, correct path to the file

Plus I extra added

*

*All the parent folders had at least 755 mod

*The immediate parent folder belonged to user running mysql process

...and I still was getting NULL from select load_file('...');
I even tried to set the secure_file_priv explicitly to various locations in /home/..., while making sure all conditions are fulfilled, and still nothing.
Finally, setting the secure_file_priv to /var/lib/mysql-files worked. I created that folder myself to see if /var might be the right place, and even though root owns that folder, it still works.


text:
Q: Error: Validation failed: cannot load kubecfg settings for "demo.k8s.naveen.tk": context "demo.k8s.naveen.tk" does not exist I'm trying to validate Kubernetes cluster using kops validate command, but it throws this error:

Error: Validation failed: cannot load kubecfg settings for "demo.k8s.naveen.tk": context "demo.k8s.naveen.tk" does not exist

A: Did you run kops update cluster --name demo.k8s.naveen.tk --yes yet? That command should automatically create the context.
You can also run kops export kubecfg --name demo.k8s.naveen.tk --admin, which will create a temporary admin certificate.


text:
Q: selectRowAtIndexPath not called I have a class that allows a user to add entries to a server-side table. Everything works correctly until I attempt to refresh the UITableView with the new data. I make a server call to get the new dataset, use it to refresh the NSArray that is the data source for the table, and then attempt to reload the table. Here is the method that is called when the data comes back from the server:
- (void) logEntriesRefreshed : (NSNotification *) notification {

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"log_entries_refreshed"
                                                  object:nil];

    NSLog(@"returned from log entries fetch");

    _logEntriesArray = [LogEntriesDataFetcher getLogEntriesArray];
    [_tableView reloadData];

    _activityIndicator.hidden = YES;
    [_activityIndicator stopAnimating];

    NSLog(@"log entries array count: %lu", [_logEntriesArray count]);

    [_tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
                            animated:NO
                      scrollPosition:UITableViewScrollPositionNone];
}

It's this last line that is the problem. I want to programmatically select the first row in the table (there has to be at least one, since I just added a row). But it appears that this line never executes. Note this method, which should go next:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"here");

    UITableViewCell *previousCell = (UITableViewCell *)[_tableView cellForRowAtIndexPath:_previousIndexPath];
    previousCell.backgroundColor = [UIColor clearColor];
    previousCell.textLabel.textColor = [SharedVisualElements primaryFontColor];

    UITableViewCell *cell = (UITableViewCell *)[_tableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [SharedVisualElements secondaryFontColor];
    cell.textLabel.textColor = [SharedVisualElements primaryFontColor];

    _previousIndexPath = indexPath;

    // get the file attributes for the cell just selected
    _currentEntry = (LogEntry *)[_logEntriesArray objectAtIndex:[indexPath row]];

    NSLog(@"array count: %lu", (unsigned long)[_logEntriesArray count]);
    NSLog(@"current entry: %ld", (long)[indexPath row]);

    _isExistingEntry = YES;
    _arrayPositionOfEntryBeingEdited = [indexPath row];

    [self initializeValues];
    [self initializeObjects];
    [self captureStartingValuesForStateMachine];
}

I have break points set on the selectRowAtIndexPath line and also on the first NSLog(@"here") line in didSelectRow.... I get to the selectRowAtIndexPath line but never to the didSelectRow method. My console output is consistent with that:
returned from log entries fetch
log entries array count: 7

and that is the end of it. Nothing from the didSelectRow... method. There are no errors thrown, either.
What am I missing. Seems pretty straightforward, but nothing I do seems to work.

A: As per Apple's documentation, calling selectRowAtIndexPath will NOT invoke the didSelectRowAtIndexPath. Take a look here.

Calling this method does not cause the delegate to receive a
  tableView:willSelectRowAtIndexPath: or
  tableView:didSelectRowAtIndexPath: message, nor does it send
  UITableViewSelectionDidChangeNotification notifications to observers.

To specifically invoke the didSelectRowAtIndexPath delegate method, use the following code:
[[tableView delegate] tableView:tableView didSelectRowAtIndexPath:indexPath];

Hope this helps.


text:
Q: How does a linear operator having constant eigenvalues imply integrability of its eigenvector distribution? I am reading a paper where the authors have constructed a linear operator, say $A$, on vector fields.  They claim that this operator having locally constant eigenvalues is enough to imply that the distribution generated by the eigenvectors of $A$ is integrable.  I am having trouble understanding this.
In order to have integrability, I believe we must show that $A([v,w])$ is an eigenvector for any eigenvectors $v,w$ of $A$.  Say that $\lambda_1,\lambda_2$ are the eigenvalues associated to $v,w$, respectively.  The constant eigenvalue condition seems to imply that $$\nabla(Av) = A(\nabla v) = \lambda_1\nabla v,$$ but I do not understand how this implies the distribution is closed under Lie brackets.  In particular, it is clear from the above that $[Av,Aw] = \lambda_1\lambda_2[v,w]$, and it is also clear that the bracket is $A$-linear in both arguments separately.  With that said, why is it that $[v,w]$ is also an eigenvector of $A$?  I do not see it.
EDIT:  The operator $A$ is (as I understand it) not a priori a homomorphism of Lie algebras.  It is something related to the shape operator of an immersed submanifold.


text:
Q: How can i make this factorial function recursive? A function that calculates (n-1)! , but with steps.
def function1(n, step):
    result = 1
    for i in range(1, n, step):
        result *= i

    return result

I'm not allowed to add any more parameters and I need to make it recursive.
I've tried this:
def function2(n, step):
    if n < 0:
        return 1

    return n * function2(n-step, step)

But for let's say:
function2(6,3)

it wouldn't work, the first function will give me 1 * 4
and the second one would give me 6 * 3 * 1
I don't know how to make it work with the step argument.
Edit:
Some more samples:
First function
function1(13, 3) == 280
function1(11, 3) == 280
function1(6, 3) == 4
function1(11, 2) == 945
function1(8, 2) == 105
function1(4, 2) == 3
More sample:
function1(12, 3) == 280
function1(5, 2) == 3
function1(5, 3) == 4

Second function (same values):
function2(13, 3) == 3640
function2(11, 3) == 880
function2(6, 3) == 0
function2(11, 2) == 10395
function2(8, 2) == 0
function2(4, 2) == 0

Edit2: Some more clarifications: The function computes (n-1)!, but with steps. The step argument would just "step over" or "skip" some numbers (e.g.: function1(12, 3) should compute 1*4*7*10, like with the step argument from range(), cause it's used in the first function)
Thank you!

A: The obvious difference is that you are building range starting at 1 and counting up to n by step, and in the recursive example you are starting at n and counting down by step. This will result in different numbers being multiplied.
Because you are required not to use any additional function parameters, I would suggest an inner helper function, loop -
def fact (n, step):
  def loop (m):
    if m >= n:
      return 1
    else:
      return m * loop(m + step)
  return loop(1)

If you don't want to use a helper function like loop above, you are constrained to complex modulus arithmetic -
def fact (n, step):
  if n % step != 1:
    return fact(n + 1, step)
  elif n < step:
    return 1
  else:
    return (n - step) * fact(n - step, step)

No matter which way you shake it, the modulus operation for this problem is messy -
def fact (n, step):
  q = (n - 1) % step
  if q:
    return fact(n + step - q, step)
  elif n < step:
    return 1
  else:
    return (n - step) * fact(n - step, step)

Once academic constraints like "do not use additional parameters" go away, you can multiply the ascending series in a more familiar way -
def fact (n, step, m = 1):
  if m >= n:
    return 1
  else:
    return m * fact(n, step, m + step)

All variations of fact above produce identical output -
print(fact(13, 3) == 280) # True
print(fact(11, 3) == 280) # True
print(fact(6, 3) == 4) # True
print(fact(11, 2) == 945) # True
print(fact(8, 2) == 105) # True
print(fact(4, 2) == 3) # True
print(fact(5, 2) == 3) # True
print(fact(5, 3) == 4) # True

A: Because the steps is calculated beginnig with 1 You have to normalize n to be a multiple of step plus 1 before you begin
And you can cheat the number of arguments by setting the steps negative on recursive calls.
def function2(n, step):
    if n <= 1:
        return 1
    if step > 0:
        n = n - 2
        n = n - n % step + 1
        step = -step
    return n * function2(n + step, step)


text:
Q: usb Ethernet adapter disapear after Stoping network-manager service I am using D-Link (DUB-E100) for handling 2 seperated network under linux ubuntu 14.04. at first i have 2 eth on my system .
ifconfig yields:
eth0      Link encap:Ethernet  HWaddr b8:ae:ed:70:27:3e
          inet addr:192.168.1.200  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::baae:edff:fe70:273e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:13717 errors:0 dropped:35 overruns:0 frame:0
          TX packets:452 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1262738 (1.2 MB)  TX bytes:82012 (82.0 KB)
          Interrupt:20 Memory:f7c00000-f7c20000

eth1      Link encap:Ethernet  HWaddr 54:b8:0a:ef:cf:c6
          inet addr:192.168.0.183  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::56b8:aff:feef:cfc6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:117675 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:17937811 (17.9 MB)  TX bytes:3777428 (3.7 MB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:344851 errors:0 dropped:0 overruns:0 frame:0
          TX packets:344851 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:26624855 (26.6 MB)  TX bytes:26624855 (26.6 MB)

but after this command :
sudo service network-manager stop
Here is what I get in ifconfig:
eth0      Link encap:Ethernet  HWaddr b8:ae:ed:70:27:3e
          inet addr:192.168.1.200  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::baae:edff:fe70:273e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:13717 errors:0 dropped:35 overruns:0 frame:0
          TX packets:527 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1262738 (1.2 MB)  TX bytes:96519 (96.5 KB)
          Interrupt:20 Memory:f7c00000-f7c20000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:346012 errors:0 dropped:0 overruns:0 frame:0
          TX packets:346012 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:26759532 (26.7 MB)  TX bytes:26759532 (26.7 MB)

,So in this situation i lost my second network ,(i have to stop network-manager beacaus before stopping it,I dont recieve any udp packet from other local devices on my local area network (eth0)), how can I have two connection simultaneously,
is there any way to have eth1 after stopping network-manager?
UPDATE1:
My /etc/network/interfaces is:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address 192.168.1.200
netmask 255.255.255.0
gateway 192.168.1.1

UPDATE 2:
I changed My /etc/network/interfaces is:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address 192.168.1.200
gateway 192.168.1.1

auto eth1
allow-hotplug eth1
iface eth1 inet dhcp
gateway 192.168.0.1

and it could not solve my problem.

A: This happens because your eth1 interface is managed by Network Manager.
When you stop the service, the interface is disabled.
You can setup /etc/network/interfaces and not use NM for both devices.
But your problem is mainly because you did not set proper routing and iptables.


text:
Q: displaying command output on webpage using perl cgi below is the code,
please give me any suggestions to display the result of the command output.
#!/usr/bin/perl
use strict;
use warnings;
print "content-type:text/html\r\n\r\n";
print <<EOF;

<title>command</title>

EOF
my $d=qx(perl -cw 1.cgi);
print <<EOF;

$d

EOF

A: qx will return the STDOUT in variable but you are trying to store the Perl compiling result into your variable, In Linux it is called as STDERR not a STDOUT so we need to do as follow
my $d=qx(perl -cw 1.cgi 2>&1);

More about  2>&1


text:
Q: CreateQuery is not valid without active transaction I'm trying to use the Spring @Transactional annotation, but i have problems when the method findAll is called and i have this error:
  org.hibernate.HibernateException: createQuery is not valid without active transaction
  at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
  at com.sun.proxy.$Proxy57.createQuery(Unknown Source)
  at org.munaycoop.taskmanager.daos.PersonDataAccesObject.findAll(PersonDataAccesObject.java:20)
  at org.munaycoop.taskmanager.services.PersonService.findAll(PersonService.java:26)
  at org.munaycoop.taskmanager.controllers.PersonController.ShowAllPersons(PersonController.java:20)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:606)
  at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
  at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
  at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
  at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
  at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
  at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
  at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
  at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
  at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
  at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
  at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:390)
  at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
  at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
  at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
  at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:440)
  at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
  at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
  at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
  at org.mortbay.jetty.Server.handle(Server.java:326)
  at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
  at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:926)
  at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
  at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
  at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
  at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
  at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

the Person DAO:
@Repository
@Transactional
public class PersonDataAccesObject implements IPersonDataAccesObject {

    @Autowired
    private SessionFactory session;

    @Override
    public List findAll() {
        return session.getCurrentSession().createQuery("from persons").list();
    }

and this is my servlet-context.xml:

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/bootstrap/" />

<!-- Database Configuration -->
<context:property-placeholder location="classpath:database.properties" />

<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <beans:property name="driverClassName" value="${jdbc.driverClassName}" />
    <beans:property name="url" value="${jdbc.databaseUrl}" />
    <beans:property name="username" value="${jdbc.username}" />
    <beans:property name="password" value="${jdbc.password}" />
</beans:bean>

<!-- Hibernate session factory -->
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"/>

    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.connection.pool_size">${hibernate.pool_size}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
            <beans:prop key="hibernate.current_session_context_class">${hibernate.current_session}</beans:prop>
            <beans:prop key="hibernate.cache.provider_class">${hibernate.provider_class}</beans:prop>
            <beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
            <beans:prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl}</beans:prop>
        </beans:props>
    </beans:property>

    <beans:property name="mappingResources">
        <beans:list>
            <beans:value>hibernate.cfg.xml</beans:value>
        </beans:list>
    </beans:property>
</beans:bean>

<!-- Hibernate TransactionManager -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <beans:property name="sessionFactory" ref="sessionFactory"/>
</beans:bean>

I tried removing this line <beans:prop key="hibernate.current_session_context_class">${hibernate.current_session}</beans:prop>, but another error has came, why this is not working?

A: You have to explicitly declare  support for transaction manager annotation
Add to your config:
<tx:annotation-driven transaction-manager="transactionManager"/>

tx is xmlns:tx="http://www.springframework.org/schema/tx" namespace.
and delete this line:
<beans:prop key="hibernate.current_session_context_class">${hibernate.current_session}</beans:prop>

A: remove this code
<beans:prop key="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext </beans:prop>

and add this line
<tx:annotation-driven transaction-manager="transactionManager"
  mode="proxy" proxy-target-class="true" />

in your xml file
where you set your hibernate transaction property.


text:
Q: Modification For AJAX Instant Search I have build an instant search with AJAX using this tutorial, I am getting instant result but the problem is the div in which result comes stays open there.
I want to modify it like after getting instant result, then

*

*when clicked anywhere on page the result(div) should disappear.

*and when mouse-over again on input field result(div) should reappear.

AJAX Code

HTML Code

<form action="" method="get" id="search-form" >

<input name="" type="" size="" id="search-input" onkeydown="showResult(this.value)"/>

<select name="" id="search-select">
<option value="all" >All</option>
<input type="hidden" name="" value="" />
</select>

<input type="submit" value="Search" id="search-btn" />

</form>

PHP Codes are simple MySQL Full Text Search query.
I tried like adding this but nothing happens
        <input name="keyword" type="text" size="50" id="search-input" onkeydown="showResult(this.value)" onclick="(this.value==this.defaultValue) this.value='';"  onmouseout="showResult(this.value='';)"/>

Please suggest any way of doing this.
Thanks.

A: A nasty way

<form action="" method="get" id="search-form" >
<input name="" type="" size="" id="search-input" onkeydown="showResult(this.value)"/>
<select name="" id="search-select">
<option value="all" >All</option>
<input type="hidden" name="" value="" />
</select>
<input type="submit" value="Search" id="search-btn" />
</form>

A: Got it finally, hope this helps others too.


text:
Q: Suppressing messages in RMarkdown - not working I have the below code:

    eng <- rgdal::readOGR(paste0("https://opendata.arcgis.com/datasets/",
                                 "8d3a9e6e7bd445e2bdcc26cdf007eac7_4.geojson"))

    countries <- rgdal::readOGR(paste0("https://opendata.arcgis.com/datasets/",
                                       "92ebeaf3caa8458ea467ec164baeefa4_0.geojson"))

    eng <- sf::st_as_sf(eng)
    countries <- sf::st_as_sf(countries)
    UK <- countries[-1,]
    names(eng)[3] <- "Region"
    names(UK)[3] <- "Region"
    UK$objectid <- 10:12
    eng <- eng[-2]
    UK <- UK[c(1, 3, 9:11)]
    UK <- rbind(eng, UK)
     UK<-UK%>% arrange(Region)
    UK$Sales<-c(49, 118, 51, 27, 53, 140,76,45,51,11,55,48)

    ggplot2::ggplot(UK, ggplot2::aes(fill = Sales)) + ggplot2::geom_sf()+
      scale_fill_gradient(low='green', high='blue')+
      theme(axis.line.x.bottom = element_blank(),
            panel.grid.major = element_blank(),
            panel.grid.minor = element_blank(),
            panel.border = element_blank(),
            panel.background = element_blank(),
            axis.line.y.left = element_blank(),
            axis.text.x = element_blank(),
            axis.text.y = element_blank())+labs(fill = "Number of car sales\n (7th October 2019\n - 26th

    January 2020)")

I get this output in the final PDF:
## OGR data source with driver: GeoJSON
## Source: "https://opendata.arcgis.com/datasets/8d3a9e6e7bd445e2bdcc26cdf007eac7_4.geojson", layer: "Region__December_2015__Boundaries"
## with 9 features
## It has 5 fields
## OGR data source with driver: GeoJSON
## Source: "https://opendata.arcgis.com/datasets/92ebeaf3caa8458ea467ec164baeefa4_0.geojson", layer: "Countries__December_2019__Boundaries_UK_BUC"
## with 4 features
## It has 10 fields

Is there any way I can stop this, I have set messages=FALSE, Warning=FALSE, Echo=FALSE, but still get the same

A: Ok I have solved this. This seems to have worked
```{r, echo=FALSE, message=FALSE, results='hide'}


text:
Q: Notification Not received when app closed in Lollipop using GCM I'm new to android. In my app, I didn't receive notification when the app is closed. If it is running it received. I tried all the way but still I didn't get the solution. Please find what I make wrong
Here my code:
Manifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.c2dm.permission.REGISTER" />
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
<permission android:name="com.h2o.permission.C2D_MESSAGE"
 android:protectionLevel="signature" />
 <uses-permission android:name="com.h2o.permission.C2D_MESSAGE" />
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver
     android:name="com.h2o.ExternalReceiver"
 android:permission="com.google.android.c2dm.permission.SEND" >
 <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED"/>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
    <action android:name="com.google.android.c2dm.intent.REGISTER" />
    <category android:name="com.google.android.gcm.demo.app" />
  </intent-filter>
</receiver>

<service
android:name="com.h2o.MessageReceivingService"
android:label="com.h2o.MessageReceivingService" >
<intent-filter>
   <action android:name="com.h2o.ExternalReceiver" />
   <category android:name="com.h2o"/>
</intent-filter>
</service>

Receiver:
public class ExternalReceiver extends WakefulBroadcastReceiver {
  public void onReceive(Context context, Intent intent) {
    // Explicitly specify that GcmIntentService will handle the intent.
       ComponentName comp = new ComponentName(context.getPackageName(),MessageReceivingService.class.getName());
       startWakefulService(context,(intent.setComponent(comp)));
       setResultCode(Activity.RESULT_OK);
  }
}

Service:
public class MessageReceivingService extends Service{
private GoogleCloudMessaging gcm;
public static SharedPreferences savedValues;

public static void sendToApp(Bundle extras, Context context){
    Intent newIntent = new Intent();
    newIntent.setClass(context, AndroidMobilePushApp.class);
    newIntent.putExtras(extras);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(newIntent);
}

public void onCreate(){
    super.onCreate();
    final String preferences = getString(R.string.preferences);
    savedValues = getSharedPreferences(preferences, Context.MODE_PRIVATE);

    gcm = GoogleCloudMessaging.getInstance(getBaseContext());
    SharedPreferences savedValues = PreferenceManager.getDefaultSharedPreferences(this);
    if(savedValues.getBoolean(getString(R.string.first_launch), true)){
        register();
        SharedPreferences.Editor editor = savedValues.edit();
        editor.putBoolean(getString(R.string.first_launch), false);
        editor.commit();
    }
    if(savedValuess.getBoolean(getString(R.string.first_launch), true)){
        // Let AndroidMobilePushApp know we have just initialized and there may be stored messages
        sendToApp(new Bundle(), this);
    }
}

protected static void saveToLog(Bundle extras, Context context){
    SharedPreferences.Editor editor=savedValues.edit();
    String numOfMissedMessages = context.getString(R.string.num_of_missed_messages);
    int linesOfMessageCount = 0;
    for(String key : extras.keySet()){
        String line = String.format("%s=%s", key, extras.getString(key));
        editor.putString("MessageLine" + linesOfMessageCount, line);
        linesOfMessageCount++;
    }
    editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
    editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
    editor.putInt(numOfMissedMessages, savedValues.getInt(numOfMissedMessages, 0) + 1);
    editor.commit();
    postNotification(new Intent(context, AndroidMobilePushApp.class), context);
}

protected static void postNotification(Intent intentAction, Context context){
    final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentAction, Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL);
    final Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Message Received!")
            .setContentText("")
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .getNotification();

    mNotificationManager.notify(R.string.notification_number, notification);
}

private void register() {
    new AsyncTask(){
        protected Object doInBackground(final Object... params) {
            String token;
            try {
                token = gcm.register(getString(R.string.project_number));
                Log.i("registrationId", token);
            }
            catch (IOException e) {
                Log.i("Registration Error", e.getMessage());
            }
            return true;
        }
    }.execute(null, null, null);
}

public IBinder onBind(Intent arg0) {
    return null;
}

}

Thanks in advance!

A: To be able to receive notifications when your application is closed, you have to register a service listener with the following permission
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"

See the documentation for more details
https://developer.android.com/reference/android/service/notification/NotificationListenerService.html

A: you need to define your broadcast receiver in manifest like this:
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
    <!-- Receives the actual messages. -->
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    <category android:name="com.google.android.gcm.demo.app" />
</intent-filter>

and in the broadcast receiver class add the following codes:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // Explicitly specify that GcmIntentService will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(),
            GcmIntentService.class.getName());
    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}}

there is some problem with wakeful broadcast receiver, read this
Confusion about WakefulBroadcastReceiver
For best practice it is recommended that you should use Firebase cloud messaging (FCM) instead of GCM.


text:
Q: Using constant objects in objective-c I have a piece of code similar to this:
//Foo.h
OBJC_EXPORT MyObject *const myObj;

// Foo.m
MyObject *const myObj;

@implementation Foo

+(void) initialize
{
    if (self = [Graph class])
    {
          myObj = [Config get:@"Foo"]; // <--- ERROR! assignment of read-only variable 'Foo'

          // ....
    }
}

// ....

@end

This needs to be accomplished like this, as the constant variable must be loaded exactly once from a config file. How can I use constants in that way (yes, it needs to be constants, because if it is changed, it will present a whole other group of problems..)?

A: There's likely a better way, but my first thought is assign it through an extra pointer indirection, e.g.:
MyObject** nonConstObj = (MyObject**)&myObj;
*nonConstObj = [Config get:@"Foo"];

If it were C++, const_cast<> would be appropriate, but I'm unsure as to the most common/equivalent C idiom.


text:
Q: PHP hanging on socket_read I am trying to read a response from a socket I have written on a Java application. However the PHP is just hanging. Here is the code I am using to read from the socket:
while($resp = socket_read($socket, 1000)) {
   $str .= $resp;
   if (strpos($str, "\n") !== false) {
        break;
   }
}

When I run the socket call from terminal there is deffinately a response. This is what my response code is in Java:
out.println(request.seed);

Where request.seed is an int. I have also tried:
out.println(request.passcode + "\n");

But this didnt fix the problem.

When I request the following in terminal:
josephs-macbook:~ jf$ echo "pairBankRequest|userID=305,bankID=12," | nc 127.0.0.1 3030

I get the following reply:
830039

which is what is expected.

A: In the PHP client program, insert usleep(500) between socket writes and read.

A: The reason your code is hanging is because your buffer is larger than the data being sent.
If you lower your buffer from 1000 bytes to 1 byte, youll see that the script no longer hangs.

A: From the PHP manual:

Optional type parameter is a named constant:
PHP_BINARY_READ (Default) - use the system recv() function. Safe for reading binary data.
    PHP_NORMAL_READ - reading stops at \n or \r.

Source: http://www.php.net/manual/en/function.socket-read.php
Have you tried using PHP_NORMAL_READ as the 3rd argument to socket_read()? This would also remove the need to check for strpos($str, "\n")....
Just a shot in the dark, but I'd try that.
Edit:
Here's a snippet of code that works for me:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

...
// connecting the socket, etc
...

$result = '';
$numBytes = 100;
$numRead = 0;

while ($numRead < $numBytes)
{
  $tmp = socket_read($socket, $numBytes - $numRead, PHP_BINARY_READ);
  if ($tmp === false)
  {
    $error = socket_last_error();
    socket_close($socket);
    $socket = null;
    throw new Exception('Read error ('.$error.')');
  }
  $numRead += strlen($tmp);
  $result.= $tmp;
}


text:
Q: Access Component state inside NavigationOptions - React Native I was trying to conditionally render HeaderLeft by state value, I cant able to access state value inside NavigationOptions
 static navigationOptions = ({ navigation }) => ({

    headerLeft: (navigation.state.searchText)? <View style={{ flexDirection: 'row', justifyContent: 'center' }}>

        <TouchableOpacity onPress={() => {
           // navigation.navigate('home');
           alert('Coming soon ');
        }}>
            <Image style={{ marginLeft: 20,height:20,width:20,resizeMode:"contain" }} source={require('../assets/header_icons/three_logo.png')} />
        </TouchableOpacity>
    </View> : <View style={{ flexDirection: 'row', justifyContent: 'center' }}>

<TouchableOpacity onPress={() => {
   // navigation.navigate('home');
   alert('Coming soon');
}}>
    <Image style={{ marginLeft: 20,height:20,width:20,resizeMode:"contain" }} source={require('../assets/header_icons/icon_arrow_left.png')} />
</TouchableOpacity>
</View>

});

My component did mount
  componentDidMount(){
  this.setState({threebool:true});
  this.props.navigation.setParams({

    searchText: this.state.threebool,
  });
}

My constructor
constructor(props) {
  super(props)
  this.state = {
    threebool:true,

  }
}

Please let me know how to resolve this.

A: Navigation is static, that`s why it doens't access state.
if you want your navigator to update with your state you need to call setparams everytime you update state. I would create a function to update state and call setparams to it easier.
updateNavAndState(bool){
    this.props.navigation.setParams({
        searchText: bool,
      });
    this.setState({threebool:bool})
}

A: this.props.navigation.setParams({
  handleSubmit: this.handleSubmit,
  state: this.state;
});
handleSubmit = () => {}

in navigation option you will get values by
static navigationOptions = ({ navigation = this.props.navigation }) => {
const state = navigation.state.params.state;
const handleSubmit = navigation.state.params.handleSubmit;}


text:
Q: Anyone used SQl Server 2008 HierarchialID type to store genealogy data I have a genealogical database (about sheep actually), that is used by breeders to research genetic information. In each record I store fatherid and motherid. In a seperate table I store complete 'roll up' information so that I can quickly tell the complete family tree of any animal without recursing thru the entire database...
Recently discovered the hierarchicalID type built into SQL server 2008, on the surface it sounds promising, but I and am wondering if anyone has used it enough to know whether or not it would be appropriate in my type of app(i.e. two parents, multiple kids)? All the samples I have found/read so far deal with manager/employee type relationships where a given boss can have multiple employees, and each employee can have a single boss.
The needs of my app are similar, but not quite the same.
I am sure I will dig into this new technology anyway, but it would be nice to shortcut my research if someone already knew that it was not designed in such a fashion that it would allow me to make use of it.
I am also curious what kind of performance people are seeing using this new data type versus other methods that do the same thing.

A: Assuming each sheep has one male parent and one female parent, and that no sheep can be its own parent (leading to an Ovine Temporal Paradox), then what about using two HierarchyIDs?
CREATE TABLE dbo.Sheep(
    MotherHID hierarchyid NOT NULL,
    FatherHID hierarchyid NOT NULL,
    Name int NOT NULL
)
GO
ALTER TABLE dbo.Sheep
ADD CONSTRAINT PK_Sheep PRIMARY KEY CLUSTERED (
    MotherHID,
    FatherHID
)
GO

By making them a joint PK, you'd be uniquely identifying each sheep as the product of its maternal hierarchy and it's paternal hierarchy.
There may be some inherent problem lurking here, so proceed cautiously with a couple simple prototypes - but initially it seems like it would work for you.

A: I can't see how it would work; in a regular hierarchy, there is a single chain to the root, so it can store the path (which is what the binary is) to each node. However, with multiple parents, this isn't possible: even if you split matriarchy and partiarchy, you still have 1 mother, 2 grandmothers, 4 great-grand-mothers, etc (not even getting into some of the more "interesting" scanerios possible, especially with livestock). There is no single logical path to encode, so no: I don't think that this can work in your case.
I'm happy to be corrected, though.

A: Using two separate HierarchyID to indicate father and mother would work well.
However, you definitely would NOT want to use those as a unique indicator of the row, since it's a 2-to-many situation.  (Two sheep can have multiple children.)
I don't see anything inherently wrong with using HierarchyId for ancestry--for Sheep at least.  For people, the relationships are much more complicated than "this person begat that person", so obviously the use would be limited to breeding.

A: SQL Server hierarchyID is not a robust solution for many genealogy analytic questions. It is based on ORDPATH and I've used it for awhile in genealogy; but there are too many scenarios in genealogy that cannot be readily addressed with ORDPATH methods for directed acyclic graphs. A graph database is much more robust and well suited for genealogy. I use Neo4j: http://stumpf.org/genealogy-blog/graph-databases-in-genealogy.


text:
Q: Difference between apache2 and apache2-bin? My digitalocean server is running Ubuntu 14.04, and I'm trying to install Apache.
When I just type in "apache2" to PuTTy, it says:
The program 'apache2' is currently not installed. You can install it by typing:
sudo apt-get install apache2-bin

Yet on digitalocean's official tutorial, it says to install apache2 by using:
sudo apt-get install apache2

What's the difference? Will it function the same with either command? What  will the differences be if not, and why would I choose one over the other?

A: Basically, the apache2 package just provides a part of the Apache2 infrastructure, and doesn't contain the binary files. As you run the apache2 command, the shell told you in which package that binary is located (in apache2-bin), but it doesn't mean that that's the only package you have to install.
In my raspberry pi architecture, the apache2 package contains this files:
pi@rpi ~ $ dpkg -L apache2
/.
/usr
/usr/share
/usr/share/bug
/usr/share/bug/apache2
/usr/share/bug/apache2/control
/usr/share/doc
/usr/share/bug/apache2/script
/usr/share/doc/apache2

Please note that this may differ between different distributions. The apache2.2-bin package indeed contains all the binaries used.
You should install apache2 as the tutorial says because it will install the whole infrastructure and will have apache2-bin as a dependency, so it will be installed as well.


text:
Q: xsl namespace and mapping nodes Trying to understand how 3rd party xsl namespace is used to reference xml data.
There are 2 xsl files used to generate html from xml and I don't see how the root node is referenced as "Datasource" as it is in these files.
The primary xsl file includes the secondary xsl file. The secondary "common" xsl file has snippets like:
<msxsl:script language="JScript" implements-prefix="z79">
  function GetCurrentTime()
  {
  return String(new Date());
  }
</msxsl:script>

Both xsl files have namespaces defined as:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:z79="Acme.Hammer" xmlns:msxsl="urn:schemas-microsoft-com:xslt" version="1.0">
<xsl:include href="Common\Common.xsl"/>
   <xsl:output method="html"/>

And the input xml file starts of as:
<TopData xmlns="Acme.Hammer">
    <Middle name="middleLayer">
        <Lower>
            <Characteristic  name="UNIQUEID">
                <Value>@708</Value>
                <Timestamp>2016-10-23T11:35:22</Timestamp>
            </Characteristic>

In the primary xsl file variables are declared:
<xsl:variable name="language" select="/z79:Datasource/@xml:lang"/>
<xsl:template match="/">
    <xsl:variable name="StartTimeCharac" select="/z79:Datasource/z79:Middle/@startTimeCharacteristic"/>

So z97 is a shortcut for the "Acme.Hammer" namespace. Which matches the xmlns of the root xml node 'TopData'.
But from there I'm guessing "Datasource" is mapped to the TopData node?
Does this xsl make sense?
I know it's only fragments but it is proprietary and I can't post whole files.
I've read several xsl tutorials but I haven't come across this type of configuration.
Please tell me how "Datasource" is mapped to "TopData".


text:
Q: Xaml Assign extra Class after Listview is Set A Quick Description:
The Project i'm busy with is using a wrapper for the Woo-commerce API Called Woo-Commerece.Net
I can get everything loaded fine except for Image's From my side I believe its a oversight and im missing a way to do this.
Heres the Model:https://github.com/XiaoFaye/WooCommerce.NET/blob/master/WooCommerce/v3/Product.cs#L503
When the list is generated I end up with the Product Class being iterated. However the Images are stored in a different model and I have no idea how I can call Another class for the Xaml after my listview has already been set.
I just need 1 Image to Passthrew I know Product model has a List called Images But I have no idea how youd pass a list into a image source binding
My Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Ecombeta.Views.Products"
             Title="Productsold"
             BackgroundColor="#c4c3c0">

    <ContentPage.Content>
        <StackLayout>

            <ListView x:Name="productsListView"
                      HasUnevenRows="True"
                  VerticalOptions="FillAndExpand"
                      SeparatorVisibility="None">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.View>
                                <Frame HasShadow="True" Margin="8">
                                    <StackLayout>
                                        <Label x:Name="something" Text="{Binding name}" FontSize="Large"/>
                                        <Image Source="{Binding     }"/>
                                        <Label Text="{Binding date_created, StringFormat='{0:dd/MM/yyyy}'}" FontSize="Small" FontAttributes="Italic"/>
                                        <Label Text="{Binding price }"/>
                                        <Label Text="{x:Binding enable_html_description  }" FontSize="Medium"/>
                                        <Label Text="{x:Binding sku}" FontSize="Medium"/>
                                        <Button BindingContext="{Binding id}" Clicked="ProductClicked"></Button>
                                    </StackLayout>
                                </Frame>

                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

The Back end
 public Products()
        {
            InitializeComponent();

            InitAsync();

        }
        private async void Back_Clicked(object sender, EventArgs e)
        {
            await Navigation.PopAsync();
        }

        private async Task InitAsync()
        {

            RestAPI rest = new RestAPI("http://example.co.za/wp-json/wc/v3/", "CK_XXXXXX", "cs_xXXXXX");
                WCObject wc = new WCObject(rest);
            var products = await wc.Product.GetAll();
            var p = await wc.Product.GetAll(new Dictionary<string, string>() {
                    {"tag", Suppliers.tagid },
                    { "per_page", "80" } }); ;

            List<ProductImage> z = new List<string> { p.images };
            productsListView.ItemsSource = p;

        }

        async void ProductClicked(object sender, EventArgs args)
        {

            var btn = (Button)sender;

           var a = btn.BindingContext;

            Orders.singleID = Convert.ToInt32(a);

           await Navigation.PushAsync(new Orders());

A: I Found no way to do this the exact thing I wanted at the time.
The issue in Short was that Product had a Image[] as an example and I needed to access
Product Image[].src  So In the Binding I just ended up Saying
Image[W.e Index the image You want is].src
Just in case if you wanted to check What that index is Dynamically You can try something like this
so If you have the List Initialized
E.g

  var p = await wc.Product.GetAll(new Dictionary<string, string>() {
                    {"tag", Suppliers.tagid },
                    { "per_page", "80" } }); ;

  foreach (var item in p)
            {
                foreach (var z in item.images)
                {
                    if (item.images != null)
                    {
                        var YourBinding = z.src;
                    }
                }
            }

//There is more then likely a better way to go about it but its how I ended up sorting the problem for one of the Pull Methods of mine


text:
Q: click gesture detection on part of edittext android I am working on a text editor for a programming language, it has two parts, the line number box (2) and the code box (1) like in the figure below
..................
.  .             .
.  .             .
. 2.      1      .
.  .             .
.  .             .
.  .             .
..................

*

*If the user clicks in the line number box (2), I need to execute some code, here I just show a toast with the message 'Click' but ignoure the default behavior of edit text.

*If the user clicks inside box 1, just delegate the default edittext behavior by calling super.onTouchEvent(event).
Here's what I did, but I don't know how to get it to work properly, i need to play with the return value of onTouchEvent:
public class MyEditText extends AppCompatEditText {

    private Rect drawingBound;
    private Rect leftRect; // area 2
    private Paint rectPaint;
    private static final int PADDING = 100;
    private boolean down = false;

    public MyEditText(@NonNull Context context) {
        super(context);
        init(context);
    }

    public MyEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyEditText(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        setPadding(PADDING, 0, 0, 0);
        drawingBound = new Rect();
        leftRect = new Rect();

        rectPaint = new Paint();
        rectPaint.setColor(Color.GREEN);
        rectPaint.setStyle(Paint.Style.STROKE);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        getDrawingRect(drawingBound);
        leftRect.set(drawingBound);
        leftRect.right = drawingBound.left+ PADDING;
        canvas.drawRect(leftRect, rectPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getActionMasked();

        if (action == MotionEvent.ACTION_DOWN) {
            down = true;
            return false;
        }
        else if (action == MotionEvent.ACTION_UP) {
            if (down) {
                down = false;
                int x = (int) event.getX();
                int y = (int) event.getY();

                if (leftRect.contains(x, y)) {
                    Toast.makeText(getContext(), "Click", Toast.LENGTH_SHORT).show();
                    return true;
                }
            }
            return super.onTouchEvent(event);
        } else {
            return super.onTouchEvent(event);
        }
    }
}


text:
Q: Edit/Read Mode & Disabled Styles Is there anyway for me to keep the style of multi line text box when it is disabled in edit mode, the same when viewed in read mode?
In screenshot 1, in edit mode, the boxes have scroll bars and adhere to my max height and all align.
In screenshot 2, in read mode, there are no boxes, it simply shows all values as text. I assume this is just the way xpages by default styles fields in read/edit mode? But I'd like to keep the boxes and scrollbars in read mode.
Thanks
Screenshot 1 (Edit mode - I want this styling in read mode also)

Screenshot 2 (Read mode)

A: Ignore my question, I somehow missed the showReadonlyAsDisabled="true" flag!
Leaving here incase anyone else misses the property too!

A: I use the following CSS to create a scroll-able panel containing a repeat control but it can be used for individual fields.  Use a computed class for the style to disable it when in edit mode.
.FCHScroll  {
overflow-y:scroll;
max-height:100px;
border-color:rgb(128,128,128);
border-style:solid;
border-width:thin
}


text:
Q: How to get integers out of QCUT while creating Categories for DataFrame Series With two ndarrays:
import pandas as pd
import numpy as np

a = np.arange(0,100, 10)
b = np.random.random_integers(low=9000, high=10000, size=(1000,))

I go ahead and create the DataFrame:
numbers =  np.concatenate((a, b), axis=0)
df = pd.DataFrame({'a':numbers})

Since the most of the numbers values (1000 numbers) fall in a range between 9,000 and 10,000 and only 10 numbers fall in a range between 1 and 100 I am using qcut() method to get the categories that are logically spaced by percentage of the numbers falling in each range:
df['cats'] = pd.qcut(df.a, 10)
print pd.value_counts(df['cats'])

which prints out:
[0, 9103]           102
(9630.4, 9717]      102
(9407, 9519]        102
(9307.4, 9407]      102
(9895.3, 10000]     101
(9717, 9810]        101
(9203.6, 9307.4]    101
(9810, 9895.3]      100
(9103, 9203.6]      100
(9519, 9630.4]       99
Name: cats, dtype: int64

Instead of "(9103, 9203.6]", "(9519, 9630.4]" labels that qcut generates I wish I could get the integer numbers such as 1, 2, 3, 4, 5 ,6 ,7 ,8 ,9 and etc?

A: Here is the solution posted by root:
import pandas as pd
import numpy as np

a = np.arange(0,100, 10)
b = np.arange(9000, 10000)

numbers =  np.concatenate((a, b), axis=0)

df = pd.DataFrame({'a':numbers})

df['cats'] = pd.qcut(df.a, 10, labels=False)

print df['cats'].value_counts()

A: use labels=np.arange(10) + 1
df['cats'] = pd.qcut(df.a, 10, labels=np.arange(10) + 1)
print pd.value_counts(df['cats'])

1     103
3     102
10    101
9     101
8     101
7     101
6     101
4     101
5     100
2      99
Name: cats, dtype: int64


text:
Q: Trigonometry problem. If $ \sin\theta = n\sin(\theta + 2\alpha)$, then $\tan(\theta + \alpha) $ is equal to?
I tried evaluating $n$, however I got no conclusive answer. I tried expanding $\sin(\theta + 2\alpha)$, but to no avail. How do I proceed?

A: To point you in the right direction if $sin\theta = n sin(\theta + 2\alpha)$ and we know that $tan\theta = sin\theta / cos\theta$ then how might we find the next relationship? Another option to consider is Euler's formula:
\begin{align}
\cos x & ={e^{ix} + e^{-ix} \over 2} \\
\sin x & ={e^{ix} - e^{-ix} \over 2i}
\end{align}


text:
Q: Here Document on Platform LSF I am trying to perform process substitution within a command passed to Platform LSF via bsub.
On the worker node that I submit my job to, process substitution is not enabled because it is not a POSIX compliant feature.
I therefore need to enable the feature then submit a second process from within the bsub. I have got this working using a here-document, however, it is not without errors. The final EOF marker is not being read i.e. warning: here-document at line 4 delimited by end-of-file (wanted 'EOF')
set +o posix;
bash <<EOF
    some.program -1 <(gunzip -c some.file) -2 <(gunzip -c some.file);
EOF

submitted to bsub as single string, e.g.
    set +o posix;\nbash <<EOF\nsome.program -1 <(gunzip -c some.file) -2 <(gunzip -c some.file);\nEOF
Any suggestions on how to get the final EOF to be read correctly?
As I say, everything runs fine, so this is just a case of tidying up the code.

A: The shell needs the EOF string to be alone in a complete line, just add a \n after it (and mybe a do nothing : after could also help) :
set +o posix;\nbash <<EOF\nsome.program -1 <(gunzip -c some.file) -2 <(gunzip -c some.file);\nEOF\n:

Note: I meant this to be a comment, but there is no enough space in a comment to write this in full.