Drive Builder Error: MAJOR_VERSION

Question: I am trying to setup Drive API. Once I get the GoogleCredential object, I try to create Drive/Calendar service as:
Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();

When I try in local (or deploy) I get next error:
java.lang.NoSuchFieldError: MAJOR_VERSION
    at com.google.api.services.drive.Drive.<clinit>(Drive.java:48)
    at com.google.api.services.drive.Drive$Builder.build(Drive.java:9189)

The libraries I am using are:

Thank you in advance.
Answer: I found out!
I have created a new project with a servlet to ask for Credentials and then, to create my Drive service and it is working fine.
So, I think my fail is about libraries that my project is using. Maybe, some of them are colliding.

Drive Builder Error: MAJOR_VERSION


Como fazer um crud com Json usando PHP

Question: Eu estou começando uns estudos emm php e quero conseguir fazer um crud usando um json. Eu ja consegui criar o arquivo e escrever nele, ja consigo tambem ler os dados. Mas estou tendo um problema. Na primeira vez, em que gero o arquivo e jogo os dados nele vazio, funciona de boa, mas na segunda vez, o arquivo ja me trás um estrutura errada do arquivo json. Como eu posso consertar isso?
Meu código:
<?php

if(isset($_POST['submit'])) {
    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $telefone = $_POST['telefone'];

    $dados_preenchidos = array(
        'codigo'   => rand(1000, 9999)."",
        'nome'     => $nome,
        'email'    => $email,
        'telefone' => $telefone
    );

    $dados = array($dados_preenchidos);
    $dados_json = json_encode($dados);
    $fp = fopen("bd/dados.json", "a");
    $escreve = fwrite($fp, $dados_json);
    fclose($fp);

    header('Location: index.php');
}
?>

Sore o JSON:
Na primeria vez, ele cria e gera os dados assim:

[{"codigo":"3709","nome":"samuel","email":"email@example.com","telefone":"123456789"}]

Beleza, esta correto e aparece na tela pra mim certinho, mas quando insiro um segundo registro, ele fica assim:

[{"codigo":"3709","nome":"teste1","email":"email@example.com","telefone":"1234567897"}][{"codigo":"8718","nome":"teste2","email":"firstname.lastname@example.com","telefone":"789456123"}]

Repare que o "[" se repete, quando deveria ser assim:

[{"codigo":"3709","nome":"teste1","email":"email@example.com","telefone":"1234567897"},{"codigo":"8718","nome":"teste2","email":"firstname.lastname@example.com","telefone":"789456123"}]

Fiz o teste alterando a mão pra forma correta e o código funcionou perfeitamente...
Como eu faço?
Answer: Uma outra possibilidade é a seguinte:
<?php

if (isset($_POST['submit'])) {

    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $telefone = $_POST['telefone'];

    $dados_preenchidos = array(
        'codigo' => rand(1000, 9999) . "",
        'nome' => $nome,
        'email' => $email,
        'telefone' => $telefone
    );

    $dados_preenchidos = array($dados_preenchidos);
    $dados_recuperados = array();

    //Verifica se um arquivo existe
    if (file_exists("bd/dados.json")) {

        //Lê o conteúdo do arquivo e retona em uma string
        $content = file_get_contents("bd/dados.json");
        if ($content) {
            //Decodifica uma string JSON, passando o parametro true o object retornado será convertido em array associativo.
            $arrayContent = json_decode($content, true);
            foreach ($arrayContent as $valor) {
                //Adiciona o array valor no final do array dados recuperados
                array_push($dados_recuperados, $valor);
            }
        }
    }

    //combina os arrays
    $dados_merge = array_merge($dados_preenchidos, $dados_recuperados);
    $dados_json = json_encode($dados_merge);

    $fp = fopen("bd/dados.json", "w");
    $escreve = fwrite($fp, $dados_json);
    fclose($fp);

    header('Location: index.php');
} ?>

Answer: Olá, SaMuk você pode trabalhar da seguinte maneira (comentei o código para ficar fácil o entendimento):
<?php
if(isset($_POST['submit'])) {
    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $telefone = $_POST['telefone'];

    // Atribui o conteúdo do arquivo para variável $arquivo
    $arquivo = file_get_contents('bd/dados.json');

    // Decodifica o formato JSON e retorna um Objeto
    $dados_preenchidos = json_decode($arquivo);

    //acrescenta a informação que precisa no Objeto
    $dados_preenchidos[] = array(
        'codigo'   => rand(1000, 9999)."",
        'nome'     => $nome,
        'email'    => $email,
        'telefone' => $telefone
    );

//codifica em json
$dados_json = json_encode($dados_preenchidos);

//salva o arquivo
    file_put_contents("bd/dados.json",$dados_json);
}
?>

Espero ter ajudado
Comment: Leandro, obrigado pela resposta, mas deu um erro no seu código, na linha `$dados_json = json_encode($dados_preenchidos);`, o erro é este: `Parse error: syntax error, unexpected '$dados_json' (T_VARIABLE)`
Comment: corrigi. Faltou um ; na linha acima; Pode testar
Comment: cara. ainda sim nao funcionou, de erro nessa linha agora: `$arquivo = file_get_contents('dados.json');`
Comment: bd/dados.json
Vou alterar a resposta
Comment: eu vi isso, e ja tentei alterar tambem, mas continuou com o erro kkk

Como fazer um crud com Json usando PHP


How to turn off recording for an EasyMock object?

Question: I am testing a servlet's doPost() method using EasyMock objects for the HttpServletRequest and HttpServletResponse arguments.  Within the doPost() method I'm testing the request and response objects are used as arguments to a static method class for another class, and I want to disregard (i.e. not record as expected) any calls made on the request and response objects within this method call (it's not relevant to this test anyway). For example the doPost() method of the servlet class I'm testing looks like this:
@Override
protected void doPost(final HttpServletRequest servletRequest,
                      final HttpServletResponse servletResponse)
    throws ServletException, IOException
{
    // handle an "updateFolder" event
    String eventParameter = servletRequest.getParameter("event");
    if ("updateFolder".equalsIgnoreCase(eventParameter))
    {
        // update the news documents folder settings
        String folderId = servletRequest.getParameter("folderId");
        IPortletContext portletContext = PortletContextFactory.createPortletContext(servletRequest, servletResponse);
        IPortletResponse portletResponse = portletContext.getResponse();
        portletResponse.setSettingValue(SettingType.CommunityPortlet, "NEWS_DOCUMENTS_FOLDER_ID", folderId);
    }

    // redirect to the appropriate URL
    servletResponse.sendRedirect(redirectUrl);
}

When the above code gets to the step where PortletContextFactory.createPortletContext() is called I don't really care what method calls are made on the request and response objects within that method, but if I pass in mock request and response objects when testing this method I get errors from EasyMock telling me that there are missing behavior definitions.  For example I have a test method which looks like this:
@Test
public void testPostWithUpdate()
    throws Exception
{
    // create mock objects and record their expected calls
    HttpServletRequest mockServletRequest = createMock(HttpServletRequest.class);
    HttpServletResponse mockServletResponse = createMock(HttpServletResponse.class);
    IPortletResponse mockPortletResponse = createMock(IPortletResponse.class);
    IPortletContext mockPortletContext = createMock(IPortletContext.class);
    expect(mockServletRequest.getContextPath()).andReturn(null);
    expect(mockServletRequest.getParameter("event")).andReturn("updateFolder");
    expect(mockServletRequest.getParameter("folderId")).andReturn(null);
    expect(PortletContextFactory.createPortletContext(mockServletRequest, mockServletResponse)).andReturn(mockPortletContext);
    expect(mockPortletContext.getResponse()).andReturn(mockPortletResponse);
    mockPortletResponse.setSettingValue(SettingType.CommunityPortlet, "NEWS_DOCUMENTS_FOLDER_ID", null);
    mockServletResponse.sendRedirect(EasyMock.anyObject(String.class));

    // take the mock objects out of record state
    replay(mockPortletContext, mockPortletResponse, mockServletRequest, mockServletResponse);

    // instantiate an object of the class and run the method we want to test
    ControllerServlet controllerServlet = new ControllerServlet();
    controllerServlet.doPost(mockServletRequest, mockServletResponse);

    // verify that our mocks behaved as expected
    verify(mockPortletContext, mockPortletResponse, mockServletRequest, mockServletResponse);
}

I get the following error when I run the test class:
com.plumtree.openfoundation.util.XPIllegalStateException: missing behavior definition for the preceding method call getCharacterEncoding()
    at com.plumtree.openfoundation.util.XPException.GetInstance(XPException.java:397)
    at com.plumtree.openfoundation.util.XPException.GetInstance(XPException.java:350)
    at com.plumtree.openfoundation.web.XPRequest.InitRequest(XPRequest.java:201)
    at com.plumtree.openfoundation.web.XPRequest.<init>(XPRequest.java:111)
    at com.plumtree.remote.portlet.PortletContextFactory.createPortletContext(PortletContextFactory.java:32)
    at com.abc.servlet.ControllerServletTest.testPostWithUpdate(ControllerServletTest.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.IllegalStateException: missing behavior definition for the preceding method call getCharacterEncoding()
    at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:43)
    at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:73)
    at $Proxy4.setCharacterEncoding(Unknown Source)
    at com.plumtree.openfoundation.web.XPRequest.InitRequest(XPRequest.java:135)
    ... 25 more

I assume that the errors above are caused by not recording the method calls executed within the PortletContextFactory.createPortletContext() method on the mock request and response objects passed in as arguments.  If this is actually what's happening here then how can I rework things so that the method calls made on the request and response mocks by the PortletContextFactory.createPortletContext() method are disregarded?
Answer: Try Mockito http://mockito.org/.
It is much easier to use from EasyMock, and doesn't force you to code all the method calls.
Comment: Neither does EasyMock - it has _nice mocks_ for that. And ease of use is to a large extent a question of personal taste and experience.
Comment: @Peter I worked with both and now I prefer Mockito. This may be a matter of taste, still IMHO Mockito has a neater API. TO put it in other words, Mockito is a nice mock ;)
Answer: Perhaps you need something like this:
expect(mockServletRequest.getCharacterEncoding()).andReturn("UTF-8");

Or use createNiceMock() as Péter Török suggests.
Comment: You may encounter other methods not implemented by your mock, so createNiceMock() may work unless null causes other errors.
Comment: Yes, the above is what I'm trying to avoid, since I'm not sure what method calls are being made on the mock request within the third party class method, and it's not relevant anyway since I'm not testing that class.  If the third party class implementation changes then my test may break using the approach described above.  For example it looks like PortletContextFactory.createPortletContext() is calling getCharacterEncoding() on the mock request, and if the implementation of that method changes then my test will fail if I have that expectation on the mock object.
Answer: You need to mock PortletContextFactory.createPortletContext call. EasyMock itself does not support static method mocking, however PowerMock extension for EasyMock does. Here is the sample code you should insert into your test:
mockStatic(PortletContextFactory.class);
expect(PortletContextFactory.createPortletContext(mockServletRequest, mockServletResponse)).andReturn(mockPortletContext);
replay(PortletContextFactory.class);

There are also 2 requirements:

Use the
@RunWith(PowerMockRunner.class)
annotation at the class-level of the
test case.
Use the @PrepareForTest(PortletContextFactory.class) annotation at the class-level of the test case.

Read more at: http://code.google.com/p/powermock/wiki/MockStatic
Comment: Yes, PowerMock let you do this, but this approach should only be used with legacy code and having to use Powermock to test classes at design time is certainly a sign of bad design.
Comment: @Pierre-Henri Yes, usage and mocking of static methods should be avoided by all means. However _OP_ didn't explicitly mention in his question whether he's testing legacy code or designing a new one (or at least have permission to modify it).
Answer: Alternative approach to test in similar scenarios :
class Class_Under_Test {
  public void A() {
    B b = C.create(); //create is static
    D d = e.(b);
  }
}

To get around the static reference problem in EasyMock you can change your method definition to :
@VisibleForTesting
B create() {
  return C.create();
}

public A() {
  B b = create();
  D d = e.(b);
}

In your test class you can do this :
Class testSomething {

  private Mock_Class_Under_Test mockOject;//Class Defined below
  private B mockB;

  @Override
  void setup() {
    mockB  =createMock(B.class);
  }

  private class Mock_Class_Under_Test extends Class_Under_Test {

      @Override
      B create() {
        return mockB;
      }
  }

  public void testA() {
    //No need to put expectation on static call as create() will always return mock.
    expect(e.something(mockB)).andReturn(somethingElse);
  }
}

All your further tests will use mockObject to call methods of the Class_Under_Test.
Answer: To turn of the recording, use a nice mock. From the documentation :

On a Mock Object returned by createMock() the default behavior for all
  methods is to throw an AssertionError for all unexpected method calls.
  If you would like a "nice" Mock Object that by default allows all
  method calls and returns appropriate empty values (0, null or false),
  use createNiceMock() instead.

Also, more generally, what you want to mock is createPortletContext(servletRequest, servletResponse). Unfortunately that's a static call.
To achieve this mock, create you own factory that will return the portletContext, and pass this factory to you tested class (preferably in the constructor).
Mock this factory and the portletContext too, so you can test only what matter here : the code you wrote.
Comment: A separate factory for `portletContext` is a good approach. However @OP will not be able to pass it to the constructor since he's testing a servlet (which requires public no-args constructor). But it's possible to create a setter in the servlet and call it in the test-case to pass a mocked version of the factory (obviously the default factory implementation must be set in the servlet default constructor)
Comment: The best approach for this problem is in my opinion to delegate the doPost call to a plan java service you can have total control over.
This might be overkill, so @Idolon approach to use a setter is perfectly valid too.


Where can I find a list of Search Engine Settings variables?

Question: I'm wondering where I can find a list of what every variable is in the Search Engine settings.
When you input a Search Engine into the settings, there are a number of variables attached, for example:

%s - The search query you're running
inputEncoding - The input encoding (i.e. UTF-8)
RLZ - ???
baseURL - ???
assistedQueryStats - ???
Comment: related question regarding the AQS parameter http://superuser.com/questions/653295/what-is-the-aqs-parameter-is-google-search-query
Answer: Google Chrome takes advantage of OpenSearch, "a collection of simple formats for the sharing of search results", as their specification for search query handling. The specification can be found here. But this only applies to any terms that are not prefixed with "google:". Because "google:" prefixed variables are subject to change, it is best to, at this time, reference directly to the source code of the URL management, which can be found here. The source code is also subject to change.

"google:" prefixed search variables can be found here.
All other search variables can be found here.


How to compute the pullback of $f(x,y,z) = (xy, xz, yz)$?

Question:
Let $f(x,y,z) := (xy, xz, yz)$. Compute the pullback $f^*\omega$, where $\omega$ runs through all wedge products of basis forms $dx$, $dy$, $dz$.

The definition of pullback that I know is:

The definition for the pullback of a $\mathcal{C}^{r+1}$ mapping $g: U \rightarrow V$ and a $\mathcal{C}^r$-smooth differential $p$-form $\omega$ in $V$ is
$$ (g^*\omega)_x(v_1,\ldots,v_p) = \omega_{g(x)}(Dg_x(v_1),\ldots,Dg_x(v_p))$$

First of all, I am not quite sure if I understand the statement of the problem correctly as the part

"where $\omega$ runs through all wedge products"

is a bit ambiguous to me. Does this mean that $\omega = dx \wedge dy \wedge dz$? If yes, then I think since $\omega$ is a $3$-form and the Jacobi-matrix is given by
$$(Df)_{(x,y,z)} =\begin{bmatrix}y &x &0\\ z &0 &x\\ 0 &z &y \end{bmatrix}$$
we have for $v_i = (x_i,y_i,z_i)$ and
$$a_i := D_f(v_i)  =\begin{bmatrix} x_i+y_i \\x_i+z_i \\ y_i+z_i  \end{bmatrix}$$
by definition of the pullback that
$$(f^*\omega)(v_1,v_2,v_3) = ((d_x \wedge d_y \wedge d_z))(v_1,v_2,v_3) = \det(D_f(v_1),D_f(v_2),D_f(v_3)). $$
, where the last equation follows from the fact that the wedge product of the canonical basis forms is the determinant.
Could you please tell me if this is correct so far?
EDIT: Using Masacroso's and peek-a-boo's suggestions I came up with the following:
$$f^*(dx) = d(f^*x) = d(x \circ f) = d(xy) = ydx + xdy$$
$$f^*(dy) = d(f^*y) = d(y \circ f) = d(xz) = zdx + xdz$$
$$f^*(dz) = d(f^*z) = d(z \circ f) = d(yz) = zdy + ydz$$
\begin{align}
f^*(dx \wedge dy) &= f^*(dx) \wedge f^*(dy) = (ydx + xdy) \wedge (zdx + xdz) \\
&= ydx \wedge zdx + ydx \wedge xdz + xdy \wedge zdx + xdy \wedge xdz
\end{align}
\begin{align}
f^*(dx \wedge dz) &= f^*(dx) \wedge f^*(dz) = (ydx + xdy) \wedge (zdy + ydz) \\
&= ydx \wedge zdy + ydx \wedge ydz + xdy \wedge zdy + xdy \wedge ydz
\end{align}
\begin{align}
f^*(dy \wedge dz) &= f^*(dy) \wedge f^*(dz) = (zdx + xdz) \wedge (zdy + ydz) \\
&= zdx \wedge zdy + zdx \wedge ydz + xdz \wedge zdy + xdz \wedge ydz
\end{align}
$$f^*(dx \wedge dy \wedge dz) = f^*(dz) \wedge f^*(dy) \wedge f^*(dz)$$
Is this correct or can we do more here?
Comment: They're asking you to compute $f^*({dx}),f^*(dy),f^*(dz),f^*(dx\wedge dy),f^*(dx\wedge dz),f^*(dy\wedge dz)$ and $f^*(dx\wedge dy\wedge dz)$. At least that's how I read the question. Anyway, applying the definition is certainly one way to go, but it's not a good way in general to compute. All you need to know are a few basic rules: pullback commutes with wedge products, and exterior derivatives, and is linear, and you need to know how to calculate $df$ for a smooth function $f$; see [Calculating simple pullbacks](https://math.stackexchange.com/a/4395355/568204) for examples.
Comment: You can do more. Why did you stop? Continue simplifying the calculations for 2-forms and 3-form. Use what you previously calculated, and simplify the algebra (that's what they want you to do). Also, one comment (which you can ignore, since your first few calculations are fine) I have is that it is generally a good idea to use different letters for the coordinates on the domain and target. For example, $(x,y,z)$ on the target, and $(u,v,w)$ say on the domain, so $f^*(dx)=d(f^*x)=d(x\circ f)=d(uv)=u\,dv+v\,du$ (in this specific case, things are easy, so not as confusing, but it could be worse).
Comment: Thanks for your comment, I made an edit.
Comment: @peek-a-boo: Thank you for your comment. However, I am having trouble with "simplifying the algebra". I can not see what to do more here than to "multiply out" the wedge products, but the resulting terms are just messy and I do not see how to simplify them further. Am I missing something?
Comment: Just multiply things out, and group them together. Don't worry if you don't get super simple coefficients. BUT, make sure you simplify completely using alternating nature of the wedge product. For example, you have some terms involving $(\text{stuff}) dx\wedge dx$. THis is automatically $0$. Likewise $dx\wedge dy=-dy\wedge dx$ etc.
Answer: HINT: use the fact that
$$
\begin{align*}
f^*\left(\bigwedge_{k=1}^n dx^k\right)&=\bigwedge_{k=1}^n f^*dx^k\\&=\bigwedge_{k=1}^n d(f^*x^k)\\&=\bigwedge_{k=1}^n d(x^k \circ f)\\&=\bigwedge_{k=1}^ndf^k\\
&=\bigwedge_{k=1}^n\left(\sum_{j=1}^m \partial_j f^k dx^j\right)
\end{align*}
$$
for $f:=(f^1,\ldots ,f^n)$. Example of solution for one case: using the above we have that
$$
\begin{align*}f^*(dx\wedge dy)&=(d(xy))\wedge d(xz))=(xdy+ydx)\wedge (xdz+zdx)\\
&=-xzdx\wedge dy+x^2dy\wedge dz-xydz\wedge dx \end{align*}
$$
Comment: @3nondatur no, it is as I've written. The domain of $f$ have dimension $m$ here, and it image have dimension $n$
Comment: Thanks for your answer, but I think it should be $f := (f^1,\ldots,f^m)$ in the last line.


Is there a $f\in C[0,1]$ such that $f(x)=\frac12 \sin (f(1-x))$

Question: Is there a $f\in (C[0,1],\lVert\cdot\rVert_{\infty})$ such that $f(x)=\frac12 \sin (f(1-x))$?
I feel like you need to apply Banach´s fixed point theorem, which means it suffices to prove that $T:C[0,1]\to C[0,1]: (Tf)(x)=\frac12 \sin (f(1-x))$ is a contraction mapping.
How can I prove the $T$ is indeed a contraction map?
Comment: Hint: $f(x)=0$.
Answer: Let $g(x)=\frac12\sin(x)$. Then $f(x)=g(f(1-x))$ for all $x\in[0,1]$, so in particular each point $f(x)$ is a period-2 fixpoint of $g$, and $f(1/2)$ is a period-1 fixpoint of $g$.
But note the following:

$g(x)\le\frac x2$ for all $x>0$
$g(x)>0$ for all $x\le1$
$g(x)$ is odd.

So for any $x>0$, if $g(x)>0$ then $g(g(x))\le x/4$, and if $g(x)\le 0$ then $g(g(x))\le 0\le\frac x4$. Thus $g(x)$ has no period-2 fixpoints greater than $0$, and by the odd symmetry there are none less than $0$ either. Thus $f(x)=0$ for all $x\in[0,1]$.
PS: The Banach fixed-point theorem (on $\Bbb R$, not $C[0,1]$) is another way to see this, as $g'(x)\le1/2$, which implies that $|g(x)-g(y)|\le\frac12|x-y|$, and the fixpoint at $0$ is trivial to verify.


Problemas com a função realloc() em linguagem C

Question: Olá, galera! Estou implementando um código para inserir uma espécie de tabela em um ponteiro e realocar memória enquanto a função add() está sendo executada, a função name() será executada apenas uma vez para definir o nome da tabela.
O erro: ao adicionar dois nomes à tabela, o código executa normalmente, mas quando ultrapasso duas chamadas à função add(), ocorre um segmentation default.
Exemplo de erro:
add(table, "Lucas\n");
add(table, "Vanessa\n");
add(table, "Marcos\n");

Código completo:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int name(char *table, char *text)
{
    table = (char *) realloc(table, (strlen(text) + 1) * sizeof(char));

    if (table == NULL) {
        return EXIT_FAILURE;
    }

    /* O nome da tabela é copiado para "table" */
    strncpy(table, text, (strlen(text) + 1) * sizeof(char));

    return EXIT_SUCCESS;
}

int add(char *table, char *text)
{
    table = (char *) realloc(table, (strlen(text) + 1) * sizeof(char));

    if (table == NULL) {
        return EXIT_FAILURE;
    }

    /* Os dados da tabela são concatenados */
    strncat(table, text, (strlen(text) + 1) * sizeof(char));

    return EXIT_SUCCESS;
}

int main(void)
{
    char *table = (char *) malloc(sizeof(char));

    if (table == NULL) {
        fprintf(stderr, "Erro ao inicializar o ponteiro!\n");
        exit(EXIT_FAILURE);
    }

    name(table, "Nomes:\n");

    add(table, "Lucas\n");
    add(table, "Vanessa\n");

    printf("%s", table);

    free(table);

    return EXIT_SUCCESS;
}

Desde já, agradeço grandemente! :)
Answer: O erro do seu programa está na utilização do realloc(), nesse trecho:
// Esse trecho eh da funcao add
table = (char *) realloc(table, (strlen(text) + 1) * sizeof(char));

Observe:
void *realloc(void *ptr, size_t size);

A função realloc() modifica o tamanho da memória alocada em ptr e o novo tamanho é igual a size. Quando falo igual estou dizendo que o tamanho anterior não é adicionado ao valor de size, logo realloc() pode diminuir o tamanho ao invés de aumentar e é isso que ocorre no seu código.
Voltando para esta parte do seu programa:
// Esse trecho eh da funcao add
table = (char *) realloc(table, (strlen(text) + 1) * sizeof(char));

Ao você utiliza o realloc(), o valor realocado para table será igual a (strlen(text) + 1).
Considerando o valor de (strlen(text) + 1) igual a 50 e table igual a 30, então os bytes realocados serão 50 e não 80. Quando o programa fizer isto:
strncat(table, text, (strlen(text) + 1) * sizeof(char));

table, que tem uma string de 30 bytes, será concatenada a (strlen(text) + 1), que tem uma string de 50 bytes, entretanto table só pode armazenar 50 bytes e não 80. Quanto mais valores forem adicionados com a função add, mais dados estarão em espaços de memória desconhecidos até que uma hora ou outra um erro ocorrerá.
Para resolver isso basta calcular o tamanho que realmente table precisará ter para armazenar a string concatenada, desta forma:
table = (char *) realloc(table, ((strlen(table)) + (strlen(text) + 1)) * sizeof(char));

Agora o tamanho realocado será (strlen(table)), que é o tamanho da string que já tem nela, mais (strlen(text) + 1), que é o tamanho da nova string.
Veja o código funcionado agora: código.
Comment: Caracaaa, acabei passando por desapercebido! Muito obrigado, mano :D
Realmente eu pensava que a função realloc() unia o tamanho da string alocada anteriormente, mas é errando que aprendemos. Grande abraço, irmão! :)


Does $\mathbb{P}(X < a) = \mathbb{P}(f(X) < f(a))$?

Question: If $f(x)$ is a monotonic increasing function, then does $\mathbb{P}(X < a) = \mathbb{P}(f(X) < f(a))$?  My intuition says it's true but I cannot prove the case nor find the name of the theorem.
Comment: By "monotonic increasing" do you mean *strictly increasing* (if $a < b$ then $f(a) < f(b)$) or *non-decreasing* (if $a < b$ then $f(a) \leq f(b)$)?
Answer: Consider the set of $x$, call it $S$, where $x<a$. You seek for the probability, $P(S)$. Any expression that lead to $S$ produces the exact same probability, $b$, irrespective of its decleration. If $f(x)$ is a monotonic (strictly) increasing function, $x<a$ directly implies $f(x)<f(a)$ and vice versa, i.e. if $f(x)<f(a)$, then $x<a$.
Answer: If $f$ is strictly increasing then you have:
$$\begin{equation} \begin{aligned}
\{ X < a \}
&= \{ \omega \in \Omega | X(\omega) < a \} \\[6pt]
&= \{ \omega \in \Omega | f(X(\omega)) < f(a) \} \\[6pt]
&= \{ \omega \in \Omega | f(X)(\omega) < f(a) \} \\[6pt]
&= \{ f(X) < f(a) \}, \\[6pt]
\end{aligned} \end{equation}$$
which means that $\mathbb{P}(X<a) = \mathbb{P}(f(X)<f(a))$.  If $f$ is only non-decreasing then you cannot derive this result but you can derive an analogous result with non-strict inequality.
Answer: No.
Assuming that you call monotonically increasing a function that is non-decreasing (for all $x$ and $y$ such that $x\leq y$, one has $f ( x ) \leq f ( y )$), consider $X$ following a uniform distribution on $[0, 1]$, $f=0$ and $a=1$.
Then, $P(X<a) = P(X<1) = 1 \neq  0 = P(0<0) = P(f(X) < f(a))$.
 Your assumption is true for strictly increasing functions. If f is strictly increasing, $ \{X<a\} = \{f(X)<f(a)\}$.


How much RAM will Apache web server use if 10 users download a 100 MB file simultaneously?

Question: I'm planning to buy a dedicated server from 1and1.com. There are many configurations on their site. Which one should I go for if I run the LAMP stack on CentOS and host files which users can download?
Comment: Uhhhhhh, me be try it and see? The answer is...Not much.
Comment: possible duplicate of [Can you help me with my capacity planning?](http://serverfault.com/questions/384686/can-you-help-me-with-my-capacity-planning)
Comment: I am a 'professional' system administrator working for a Pvt. Ltd. company. Unfortunately I don't have any seniors to consult. So I ask my doubts on Server Fault... why is this question unprofessional?
Answer: As someone commented, the answer is "not much". But you can easily run a test using a simple PHP script on your computer to see more exact figures. However, it almost sounds like you are trying to do some kind of "load-testing" experiment. Downloading ten files is not going to give you a good idea of that. You might be better of trying several load-testing services concurrently to get a "feel" for it.
Try these:

http://loadimpact.com/ -->> my davourite
https://loader.io/

However, 10 guys downloading 100 Megabyte is hardly testing for load. You might need to consider a paralel load testing app like Jmeter, as it hits apache directly. I might be mistaken when I say you will probably not offer "direct access" to downloads. That said, people will probably need to be authenticated. This means the direct download is not all you should be testing, but rather the entire end-to-end process from getting logged in to, to finishing a download.
This question can also become sort of redundant if you offload the file-saving to a cloud solution or use CDN. I think you might be sweating the small-stuff, and trying to optimize a system way before it's ready to be optimized (i.e. breaking a cardinal programming rule).
Comment: load testing gives me the bandwidth usage; I need the Apache RAM usage...


AOP with Spring and the X-Ray SDK for Java

Question: I am trying to trace a request in spring boot application. I am running AWS X-Ray Daemon locally which is listing on UDP port 2000 but it is not sending the trace data to the AWS X-Ray. My application is a standalone application which does some processing and is not a web-based application so I can't use the X-Ray servlet filter to trace request. Anyone knows the how trace request in non-web based spring boot application with AWS XRay?
Answer: There are various of public APIs for creating segment manually: https://docs.aws.amazon.com/xray-sdk-for-java/latest/javadoc/.
By default the X-Ray recorder uses ThreadLocal to store the created segments so anywhere in the same thread you can easily access the segment and add data to it. You can wrap the entire work done by a segment (which is equivalent to a X-Ray servlet filter would do for a web app request/response cycle) and then create subsegments for subtasks as usual.


trace infinite loop redirection in apache

Question: I have a PHP script causing a infinite redirection loop and i don't know how to detect it. is there any way to detect this? can i add any command to my .htaccess to write redirections into a log?
thanks in advance,
Comment: There should already be a log, it's called an error log. It will usually tell you what file caused the loop and at what time.
Comment: Could you possible update your question with your htaccess in case ?
Comment: @animuson: there is nothing in the error log if the redirect is caused by a script (and I don't think there would be for htaccess redirects either). Which makes sense - the error is raised on the client side, the server does not know about it.
Comment: Use error_log function
Comment: Related: http://stackoverflow.com/questions/9153262/tips-for-debugging-htaccess-rewrite-rules/9261963#9261963
Answer: Debugging in PHP in simple way is actually a cumbersome effort. What you will need is you should provide some "echo" statement (outputting a dummy text) after each line, followed by the "exit" command statement.
Then the redirection loop will not work because "exit" is making the program counter stoppable, and o you can now debug sequentially where you are going wrong.
As regards to the ".htaccess" command, you will not need any such thing. Please check in your root folder for the "error.log" file, where you have hosted your website's index.php file. If you open this file in some text editor (like Wordpad), you will see all the list of errors, along with date & time.
EDIT (providing with one example):-
Let's say you have one page like the following:-
<?php
session_start();
include_once("includes/header.php");

$var1 = 'blah blah';
// some code

$var2 = 'some more blah blah';
// some code again

// may be some more code

include_once("includes/footer.php");
?>

Now change the code to debug in this way:-
<?php
session_start();
echo 'test 1';
exit;

// other code of yours comes after this line
?>

If it works, change again to:-
<?php
session_start();
include_once("includes/header.php");
echo 'test 2';
exit;

// other code of yours comes after this line
?>

Now if it works, that means you have no problem in the "header.php" file, otherwise you are having some problem in that included file & you will need to start debugging in the same way in that "header.php" file.
Hope it helps.
Comment: well, actually i have literally hundreds of php scripts; sincerely, i can't use this technique for every script... :( I've readed something about redirect logs for rewrite engine in apache, but i don't know how to use it...
Comment: But I think this is the best solution at hand, if you want to understand the problem lying in your script.
Answer: Change instances of
header ("Location: foo.php");

to
//header ("Location: foo.php");
echo "redirecting to foo.php on line ## of bar.php";
exit;

(Most likely foo = bar, but you could have a loop containing more than one page...)
Answer: I'm currently struggling with infinite redirection myself. Due to complexity of the aplication and afterhours programming cycle not all redirections have been made the right way.
If you've set session at the beginning (let say autloader file) you cannot simply check if session loops itself.
My advice is that you write variables redirection to an external file (i.e. using file_put_contents or fwrite) so that you can follow execution even if your browser detects some misconception. Writing to an external file gives you an oportunity to follow execution even though you cannot see any echo on screen.
Infinite redirections usually come from unnecessary complication while writing code and misunderstanding in forming project structure.
Good luck!


Absolute value proof in Spivak

Question: Prove (1) using the fact that $|x|-|y| \le |x-y|$
(1) $|(|x|-|y|)| \le |x-y|$
Attempt: as I know $|a| \le b \iff -b \le a \le b$, then proving (2) would allow me to prove (1)
(2): $-|x-y| \le |x| - |y| \le |x-y|$.
From testing different cases of $x$ and $y$, it seems that (2) is true. Furthermore, as $-|a| \le a \le |a|$, it seems that (2) is true.
However, could someone show me a proof why we can assume (2) is true? I can't figure out how to write a rigorous one.
citation: Spivak Calculus 3rd edition, chapter 1 question 12 vi
Answer: $2$ is true because of the triangular inequality :
$$|x|=|x-y+y|\le |x-y|+|y|\implies$$
$$|x|-|y|\le |x-y|$$
and by symetry,
$$|y|-|x|\le |x-y|$$
Remark
$$A\le B \wedge -A\le B \implies |A|\le |B|$$
Answer: Hint: It is much simpler to prove if you observe that $|x-y|=|y-x|$, as there results that we also have
$$|y|-|x| \le |x-y|,$$
whence $\;|x-y|\ge\max\bigl(|x|-|y|, |y|-|x|\bigr)$.

Absolute value proof in Spivak


Invertible elements of monoid $(M_2(Z),\cdot)$

Question: Invertible elements of monoid $(M_ 2(Z),\cdot)$
$A=\begin{pmatrix}a&b\\ c&d\end{pmatrix}$
I calculated $A^{-1}=\frac{1}{ad-bc}\cdot\begin{pmatrix}d&-b\\ -c&a\end{pmatrix}$
$ad-bc\not=0$
I'm not really sure how to go from here to the final answer which is:
$\{A|$ determinant of $A\in \{\pm 1\}\}$
Could anyone point out what I'm missing? Thank you.
Comment: Is $M_2(\mathbb{Z})$ the space of all invertible matrix with coefficients in $\mathbb{Z}$?
Comment: It is the space of all matrices with coefficients in $\mathbb{Z}$. @Skills
Answer: The invertible elements of the monoid $(M_ 2(\mathbb{Z}),\cdot)$ form a group, called
$$
GL_2(\mathbb{Z}).
$$
For a commutative ring $R$ with $1$, the determinant of a matrix in $GL_n(R)$ is a unit in $R$. For $R=\mathbb{Z}$ this means that $\det(A)=\pm 1$.
Related questions:
Find all the units in the indicated rings.
Is $GL(2,\mathbb Z)$ a group?
General linear group over integers
Answer: $A^{-1}$ must be coefficients in $\mathbb{Z}$. So must be,
\begin{equation}
\frac{a}{ad-bc},\frac{b}{ad-bc},\frac{d}{ad-bc},\frac{d}{ad-bc} \in \mathbb{Z}.
\end{equation}
So if $A$ is invertible (i.e. the above statement is true), then $\frac1{|A|}A$ is invertible too. And if $\frac1{|A|}A$ is invertible then $\frac{1}{|A|^2}A$ is invertible and so on. So, the elements of $A$ must be such that
$$\frac{a}{(ad-bc)^n},\frac{b}{(ad-bc)^n},\frac{d}{(ad-bc)^n},\frac{d}{(ad-bc)^n} \in \mathbb{Z} \quad \forall n \in \mathbb{N}.$$
The only solution is $ad-bc=1$ or $ad-bc=-1$.
Answer: Hint: If $A \in M_2(\mathbb Z)$ is invertible with inverse $B \in M_2(\mathbb Z)$, then $AB=I$ implies $(\det A)(\det B)=\det(AB)=\det(I)=1$. What does that say about $\det A$ ?


How to make sudo -u not require password

Question: I'm using ansible with vagrant and ansible is trying to sudo as postgres user to run some postgres commands.
Ansible running as vagrant user seems to run something like sudo -u postgres psql
This fails with error message Missing sudo password
I ssh onto the vm using the same vagrant user and try sudo -u postgres psql and sure enought it prompts for a password. Interestingly though, sudo su postgres switches to the postgres user without password.
Why would sudo -u require password when sudo su doesn't?
There is an entry in /etc/sudoers.d/ called vagrant that has the following contents:
%vagrant ALL=NOPASSWD:ALL

Comment: I downvoted this because it shows no research. It basically amounts to will someone read the documentation for me.
Comment: Whilst I don't think your complaint is completely unfounded, I think you could be overestimating my ability to understand the research (which I had done). These are very new concepts and nuances in why it would work for sudo su and not sudo -u are not easy for a newbie like me to understand. @XavierLucas understood and explained this nuance very succinctly.
Comment: question seems fair enough to me, if everyone was an expert then why have this site? its a tricky area and the syntax of the config file has gotchas
Comment: Not every expert will have expertise in *all* fields of system administration.  But you are expected to be professional at some aspects of sysadmin, and done your homework in areas where you're having problems, before posting here; as [the rubric](http://serverfault.com/help/on-topic) says, "*Server Fault is a site for system and network administrators needing expert answers*"
Answer: Because you try to impersonate user postgres while your sudoers file let you impersonate user root from system group vagrant. When you use sudo su you also impersonate root.
Add this : %vagrant ALL = (postgres) NOPASSWD: ALL
Comment: @Max Yes, replace (postgres) by (ALL). But it's a huge security breach, be careful with that. And be careful it's a group here, not user. So any user part of the vagrant group will have same privelges. Remove `%` if you want only the user vagrant to have these rights.
Comment: Is there a way to allow the vagrant user to impersonate any user rather than add a line per user you want to impersonate?
Comment: @Max http://www.gratisoft.us/sudo/sudoers.man.html
Comment: @XavierLucas, at the moment it can sudo as root which would be the greatest security concern right? Is allowing it to sudo to any user any worse? Going slightly off topic now..


Creating a post project function for a freelancer websites using wordpress

Question: I'm creating a Freelancer website using WordPress. For that, I need to create a posting project function for the employers. I have tried many plugins up to now to create this functionality. This function will let the employer post their project/job using a form (a file uploader should also be included) after submitting the posted project/job should be visible on the projects/jobs page of the site. Can someone give me a solution for this on how should I create this and if there are any good plugin in WordPress that I can use to create this? Thank You
Answer: Have you tried with this plugin https://wordpress.org/plugins/wp-job-manager/.
You can try it. Maybe it'll helpfully for you.
Comment: Thanks, but there is no file uploader in that plugin


How to update the below action for each view bulk operations?

Question: I wants to delete the below folder every time only on each view bulk operations but currently it is getting deleted for each node selected in VBO. I am executing this action in rules module.
Please let men know how to run this only once for each VBO.
<code>$pdfdir = "/var/www/websites/test/sites/default/files/pdffolder";
$directory = escapeshellarg($pdfdir);
shell_exec("rm -rf $directory");
</code>
This code is executed via the Rules module.
Comment: How did you configure your rule?
Comment: In 'Execute custom PHP code in Rules Action' I am writing this code
Comment: What are the events/conditions for the rule?  VBO triggers a batch process of all the items shown in the view, so if you attach your action to an individual node, it will be executed every time.
Comment: Events are after saving new node, condition i have not defined. How to execute this only for each VBO operation
Answer: If you define a VBO event in rules that triggers on every node save, then it will happen once per node saved by VBO.  VBO takes all the selected items in a view and runs them through a batch process, performing operations per item.
So, you need to change the rule event to something else.
If the goal is to run the code once per time, here is one lazy way to do it:

Set the event to be "page is viewed". (doing this from memory, actual event name is different)
Set a condition on the rule to be the path of the VBO page.
Use your execute PHP code as the action.

This will cause the code to execute whenever the VBO url is accessed.  This is not exactly what you asked for, but hopefully this gives you an idea of how to use events and conditions in rules to get what you want.
Comment: Thank you so much for your suggestion. 1. Page is viewed is not available there is 'Content is viewed' i selected this option and set everything but it did not worked. Later is tried using  'content is viewed' of type 'page' then condition-> URL has alias and execute. It worked.Not sure if it will work for all content type in that VBO page.


Why are my Azure deployments to local IIS failing?

Question: I'm deploying an asp.net core web app to local IIS 8.5 with an Azure pipeline. Deployments are failing because the .dll of the site is locked by IIS. This is despite the fact that I explicitly stop the site, using a IIS Web App Manage task, before the deployment.
The specific error is...
ERROR_FILE_IN_USE Web Deploy cannot modify the file'MyApp.dll' on the destination because it is locked by an external process
Why is this. What do I have to do to get IIS to release the .dll and let my pipeline do its thing?

Update
I've tried a powershell script to create a App_offline.htm file. The file's created, but the following Web App Deploy task still fails with the same error.
Comment: maybe something else is using the DLL?  Did you try manually stopping the site, and manually deleting the file?
Comment: https://weblog.west-wind.com/posts/2021/Jun/20/Locked-Files-When-Publishing-NET-Core-Apps-to-IIS-with-WebDeploy and https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-preview-3/#shadow-copying-in-iis
Answer: Ok fixed it. I needed to stop the app pool in addition to the website. So in the IIS web app manage task, in Additional appcmd.exe commands, put
<code>stop apppool /apppool.name:"MyAppPool"
</code>


Adding data from API as new entry to ListView

Question: I'm getting data from an API productObject and display them in the build widget as follows:
  Widget build(BuildContext context) {
    if (_sharedText != null) {
      return Scaffold(
        appBar: AppBar(
          title: Text("Thank you"),
          backgroundColor: Colors.blueGrey.shade900,
        ),
        backgroundColor: Colors.blueGrey.shade400,
        body: Center(
          child: FutureBuilder<ProductInformationModel>(
              future: productObject(),
              builder: (BuildContext context, AsyncSnapshot<ProductInformationModel> snapshot) {
                if (snapshot.hasData) {
                  return
                    ListView.builder(
                        itemCount: 2, //just a number to display at least the result
                        itemBuilder: (BuildContext context, int index) {
                          return Container(
                            //height: 75,
                            child: Center(
                              child: midView(snapshot),
                            ),
                          );
                        }
                    );
                } else if (snapshot.hasError) {
                  return Container(child:
                  Text("${snapshot.error}"));
                } else {
                  return Container(
                    child: Center(child: CircularProgressIndicator(),),
                  );

This is ok so far, but what I want is that every time the API is called again the present displayed API output will remain displayed on the screen and the new called API output will be visible below the present output.
So each API call should be one list entry without deleting the former data from the API.
An example of the productObject:
  Future<ProductInformationModel> productObject({String urlName}) async {
    try {
      return new Network().getProductInformation(urlName: _sharedText);

    } catch (e) {
      print("Image not found: $e");
    }
  }

And I call the API like this:
if (response.statusCode == 200) {
      model (ProductInformationModel from product_information_model.dart
      print("image data: ${response.body}");
      return ProductInformationModel.fromJson(json.decode(response.body));
    }else {
      throw Exception("Error getting image info");
    }

Widget midView(AsyncSnapshot<ProductInformationModel> snapshot) {
  var productName = snapshot.data.objects[0].title;
  var productImage = snapshot.data.objects[0].images[0].url;
  var api_type = snapshot.data.request.api;
  var pageUrl_type = snapshot.data.request.pageUrl;
  Container midView = Container(
    child: Padding(
      padding: const EdgeInsets.all(14.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[Text("$productName, $productImage",
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 18,
          color: Colors.black87
        ),),

I think I need the setState() but where do I set it?
Do I need to create an empty list before?
Thanks a lot, I'm new to flutter and struggle with this.
Answer: There are some issues that I can see, but I can't offer you a complete solution without seeing the rest of the code (midView Widget). You have your ListView.builder with a fixed itemCount of 2 but then you are passing the whole snapshot to the midView Widget. I would actually have expected that the snapshot's data was a list, and you would cycle through the list using the index provided by the builder. That would also mean that you would set the itemCount not as a fixed value but as the length of the list coming from your snapshot. The following code assumes that your snapshot is a List:
ListView.builder(
  itemCount: snapshot.data['objects'].length,
  itemBuilder: (BuildContext context, int index) {
    return Container(
      child: Center(
        child: midView(snapshot.data['objects'][index]),
      ),
    );
  }
);

Comment: Hi Joao, thanks a lot for your answer. Yes, you are right, `snapshot` is not a list but of type `AsyncSnapshot`. How can I transform it into a list to follow your example? Thank you.
Comment: If you share on your question an example of your `ProductInformationModel`, I should be able to help.
Comment: Thanks Joao, I added an example and how I call the API
Comment: So it's the "objects" inside the Model that you want to list?
Comment: You didn't share the code I asked about, `midView`. But from what I can see, you should be able to just access the objects array of your Model directly. I've added it to my code.
Comment: sorry, added midView: If I follow your example I get an error at snapshot.length because snapshot isn't a list. How can I change  from the API to a list to be displayed? Or is it possible to display a  as a new list entry? Thanks a lot!
Comment: You are right, I need to make more modification to the code to accommodate for the new information you shared.
Comment: @user3469337 Please check the changes. I've modified both the `itemCount` and the data in the `mideView`.
Comment: thanks, now I get this error at the line with snapshot['objects'].length: The operator '[]' isn't defined for the type 'AsyncSnapshot'
Comment: I believe it was missing the `.data` property to access the data coming from the `snapshot`. I've made the correction.
Comment: Has it fixed your issue?
Comment: thank you very much. `itemCount: snapshot.data.objects.length`, is working fine but `midView(snapshot)` not (just the solution here). The `[index]` is not usable. And by doing so the first and only entry will always be replaced. Didn't we need to use setState for that? thanks
Comment: I can't see your data. But The FutureBuilder should be doing that for you. Regardless, there are other ways of implement this. Using a listener and saving the data every time there is a change pushed by snapshot, then calling a setState so that the list gets updated. I would have to write all of that code now to show you.
Comment: Can you share your `productObject()` method?
Comment: added productObject()


How to store response data from Axios to a variable in React Functional Component?

Question: I'm using a React functional component. I want to store the data received from an API to a variable so that I can use it in the rest of the code.
const Component = (props) =>{
     let variable = {};

     Agent.API.get(props.id)
     .then((response)=>{
       variable = response.data })

     return(

{variable.name}

      )
}
export default Component;

This is something I want to achieve. How do I go about?
Answer: You want to use axios, so then set response in state.
import React, {useState, useEffect} from 'react'

export default (props) =>{
  const url = 'https://api.example.com'
  const [result, setResult] = useState(null)

  useEffect(() => {
    axios.get(url)
    .then((response)=>{
      setResult(response.data)
      // axios returns API response body in .data
    })
  }, []) // second param [] is a list of dependency to watch and run useEffect

  return(

{result === null ? 'loading' : result.name}

    )
}

Comment: Placing the axios call inside a `useEffect` with an empty dependencies array might be useful too, if you don't want to play the query with every render.
Comment: I've forgotten it. Thank you. I fixed.
Comment: Isn't `result` is going to be `undefined`, not `null`, if you are not giving `useState` a `null` default value ?
Comment: Yes, you're right. Sorry I didn't test enough. Thank you for check.


Tracking down "Connection reset" errors in Linux

Question: I'm handling large numbers of concurrent downloads (approx. 500 per server) using Java.
All the files are being downloaded from Amazon S3, and the downloading server is an EC2 m1.large instance.
Occasionally, 2 or more of the streams will simultaneously be broken, resulting in a java.net.SocketException. Occasionally up to 10 of the streams can be simultaneously broken.
I am having the same results downloading from both Amazon S3 and Akamai servers. It only happens when the load starts to be quite high (200 or more concurrent downloads).
I'm well within normal CPU, network load and memory bounds.
I strongly suspect the problem is on my server, and not S3 and Akamai's. How could I debug this and track down the cause?
Answer: You could capture the traffic with tcpdump and look at that after the connections break. Wireshark for example has an option "follow TCP stream" that allows you to easily isolate a broken one once you locate the last packet.
It might still be quite a lot of data to go through, but as you're saying that it only happens when the load is quite high, I don't think that there's a way around that.
As a start, you could have a look at the errors reported by the network interface (through ifconfig) and see if that number increases significantly when connections are dropped.
Answer: Is there a firewall/NAT on the path between you and S3?
Could you simlutaneously capture (tcpdump -w file -s 0) the traffic at 2 points - between your server and the firewall, and between the firewall and S3, then compare the dumps? Before launching tcpdump, make sure that the clock is precisely synchronized using NTP on the capturing hosts.
Then compare both network captures at the point in time when the connection has been dropped.
I had a similar elusive problem, and by comparing network traffic dumps I've discovered that it was due to SACK being active on my Linux server, but being improperly interpreted by the Cisco ASA firewall that handled the traffic going from the Internet.
Had to disable SACK using sysctl (net.ipv4.tcp_sack).


Translating only Field labels

Question: I'm using Entity Translation and I've enabled "Enabled, with field translation" in a content type but don't want to translate each individual field.
It seems "Field translation" of i18n suit does it and in translate interface at admin/config/regional/translate/translate we can translate the field labels.
But the problem (as in the photo) is that it shows the same field text for all the content types sharing same field with same label. That is for same label I should be able to translate once only.

Is there any more simple way to translate field labels at once?
A similar question is here:  How to translate Boolean field labels? but seems to be more specific.
Answer: You need to download internationalization module and enable field_translation module which comes in this package. How to translate the field labels:

Go to manage fields. For ex. Articles, the path will be admin/structure/types/manage/article/fields/
Click edit for field_tags.
You'll see a translate tab there. I have attached the screenshot.
Translate field name and description there. It works.
Comment: My problem was that English was not the source language. This can be changed at `/admin/config/regional/i18n/strings` (Multilingual settings -> Strings -> Source language)

Translating only Field labels


Find $\lim _{r\to \infty}\frac{\left(\prod_{n=1}^{r}\sin\left(nx\right)\right)}{\left(\frac{1}{r}\right)}$

Question: $\lim _{r\to \infty}\frac{\left(\prod_{n=1}^{r}\sin\left(nx\right)\right)}{\left(\frac{1}{r}\right)}$
I tried using the product sin formula but got nowhere.& even after multipling and dividing by $2cos (x)$,   answer couldnt be obtained as only multiples of two cut out themselves.
it is a 0/0 indeterminate form.
Also I didn't get the answer by using the l's-hopital rule.
I even tried graphing it on desmos, but the graph was strange---( I think even desmos couldn't compute it further)
please help.
thanks in advanced..............
Comment: You seem to have the wrong function, the term in the product $\prod_{n-1}^r\sin(rx)$ doesn't depend on $n$...
Comment: thanks. corrected that
Comment: The product is zero if $x$ is a rational multiple of $\pi$. This would lead me to believe the product tends to zero for any real $x$ by a density argument, though I can't quite prove it. I don't believe the product has a known closed-form either, which doesn't help.
Answer: If $x$ is a rational multiple of $\pi$, then for some integer $N > 0$, $\sin(Nx) = 0$. This forces $\prod_{n=1}^r \sin(nx) = 0$ whenever $r \ge N$. In this case, the limit is $0$.
Otherwise, $x$ is not a rational multiple of $\pi$ and $|\cos x| < 1$. Notice
$$|\sin(nx)\sin(n+1)x| = \frac{|\cos x - \cos((2n+1)x)|}{2} \le \mu \stackrel{def}{=}\frac{1 + |\cos x|}{2}$$
By grouping the factors in the numerator in pairs, we have following bound
for the weighted product at finite $r$.
$$r\left|\prod_{n=1}^r \sin(nx)\right|
\le r\prod_{k=1}^{\lfloor r/2\rfloor} |\sin((2k-1)x)\sin(2kx)|
\le r\mu^{\lfloor r/2\rfloor}
$$
Since $\mu < 1$, the limit of the weighted product is again $0$.
Answer: If $x=\frac pq \pi$ for $p,q\in \mathbb Z, (q\ne 0)$, then the limit would evaluate to zero as for any $q$ we have the term $\sin(qx)$ in our product. If $x$ is not a rational multiple of $\pi$, then no term in the numerator equals zero and we have to take the limit.
$\because -1 \lt \sin(mx) \lt 1$ doesn't vary much, the limit can be reasonably approximated as:
$$\lim_{r\to\infty} r\prod_{n=1}^r \sin(nx) \sim \lim_{r\to\infty} r (\sin x)^r \\ =\lim_{r\to\infty} \frac{r}{(\csc x)^r} =0$$
$ \because|\csc x| \gt 1$, the limit equals zero due to the fact exponentials grow way faster.
Comment: Having spent some time on this, could you please elaborate on passing the product to $r$ powers of $-\sin(x)$?
Comment: @Integrand Sorry, the $(-1)^r$ wasn't meant to be there.
Comment: Even the passing to $r$ powers is not obvious. For instance, the locations of extrema and zeroes change.
Comment: @Integrand That's true, but it's a good approximation , especially as $r$ gets large. The idea is that a bunch of numbers ranging from $-1$ to $1$ when multiplied together infinitely many times produce the same result as multiplying one particular number among them, infinitely many times.


Chef server will not start - Starting chef-server In 16011 Fail

Question: olrHow do I deal with the below?
<code>/etc/init.d/chef-server-webui start
 * Starting chef-server-webui
 ~ In 15468
  ...fail!

root@li409-115:/etc/init.d# /etc/init.d/chef-server start
 * Starting chef-server
 ~ In 16011
  ...fail!
</code>
There is nothing in the logs files in /var/log/chef/server.log or
server-webui.log
starting chef client and solr works.
So... how to resolve?
Comment: It would be good to know the environment you are installing on and the steps you followed.
Answer: Workaround:

Make sure the chef-server-webui service is stopped: sudo /etc/init.d/chef-server-webui stop
Start the web UI process manually (it will log to the console, not the log file):        sudo /usr/sbin/chef-server-webui
When the process is up ("Successfully bound to port 4040"), stop it with Ctrl-C
Start the chef-server-webui service: sudo /etc/init.d/chef-server-webui start

The service should start now and log to /var/log/chef/server-webui.log.
Answer: I looked at this link and it worked for me https://tickets.opscode.com/browse/CHEF-3204
I executed below commands on my chef server VM (ubuntu 12.04). You might have to sudo su. I think my problem was couchdb was not running. Please note the sequence is important

/etc/init.d/couchdb stop
/etc/init.d/couchdb start
/etc/init.d/rabbitmq-server stop
/etc/init.d/rabbitmq-server start
/etc/init.d/chef-solr stop
/etc/init.d/chef-solr start
/etc/init.d/chef-expander stop
/etc/init.d/chef-expander start
/etc/init.d/chef-server stop
/etc/init.d/chef-server start
/etc/init.d/chef-server-webui stop
/etc/init.d/chef-server-webui start


Inequality between two Random Walks

Question: Let's consider two Random Walks,
$$x^{(1)}_t = x_0 + \sum_{i=1}^{t}\xi^{(1)}_i,$$
$$x^{(2)}_t = x_0 + \sum_{i=1}^{t}\xi^{(2)}_i.$$
The random variables $\xi^{(1)}_i$ are i. i. d. They take values on a set $K \subset \mathbb{Z}$ which is not necessarily finite. Their probability distributions are respectively $P^{(1)}$ and $P^{(2)}$. Assume that these distributions are such that
$\forall k \in \mathbb{Z}$,  $P^{(1)}(\{  \xi^{(1)}_i \geq k \}) \geq P^{(2)}( \{ \xi^{(2)}_i \geq k \} )$.
Now $\forall m \in \mathbb{Z}$ define the event,
$$\{ \forall t \in \mathbb{N}, \, \, \, x_t  \geq x_0 - m \},$$ i.e. the walk will never cross a certain barrier placed in $x_0 - m$. How can I prove formally that the probability of this event for the random walk (1) is larger or equal to the probability of the same event for random walk (2)?
The expectations $E_{P^{(1)}}[\xi^{(1)}]$ and $E_{P^{(2)}}[\xi^{(2)}]$are both larger than $0$.
Answer: Edit: The induction proof failed. See the addendum for a proof of $(1)$ from a different direction.

An approach via mathematical induction. First of all, note that:
$$\{\forall t \in \Bbb N: x_t \ge x_0-m\} = \bigcap_{t \in \Bbb N} \{\forall s \le t: x_s \ge x_0-m\}$$
Let $S^m$ be the set on the LHS, and $S^m_t$ those on the RHS. By the fact that $P^{(1)}$ and $P^{(2)}$ are probability measures, we have:
$$P^{(i)}(S^m) = \lim_{t \to \infty} P^{(i)}(S^m_t)$$
Since limits preserve inequalities, it will suffice to show the inequality holds for all $S^m_t$; this makes our life a lot easier because we can deal with one time-step at once, reducing the number of events and the complexity of them.
We can now show by induction on $t$ that:
$$\forall m \in \Bbb N: P^{(1)}(S^m_t) \le P^{(2)}(S^m_t) \tag{1}$$
which leads us to the desired conclusion. Can you take it from this outline?

Addendum: As requested, a more explicit outline. Sadly, my purported sketch proof didn't work out as I made some irreparable errors. Thus we will have to turn to a direct approach using sums (for the moment; I'm sure there are elegant arguments as well).
Despite the fact that $P^{(i)}$ are not the formally correct symbols, they naturally induce the measures playing a role so I will stick with this abuse of notation. Observe that:
$$P^{(i)}(S^m_2) = \sum_{k_1 \ge -m} \,\sum_{k_2 \ge -k_1-m} P^{(i)}(\xi^{(i)}_1 = k_1)P^{(i)}(\xi^{(i)}_2 = k_2)$$
and in general, denoting $\sigma_\ell = \sum_{j=1}^{\ell-1} k_j$:
$$\begin{align}P^{(i)}(S^m_t) &= \sum_{k_1 \ge -m} \cdots \sum_{k_t \ge -\sigma_t-m} \ \prod_{j=1}^t P^{(i)}(\xi^{(i)}_j = k_j)\end{align}$$
where the summation subscripts contain $k_\ell \ge \sigma_\ell - m$ for $1 \le \ell \le t$.
By investigating the collection of $t$-tuples included in our summation, we can always exchange the summations to have the last one range over $k_i$ (of course, taking care to describe our collection of $t$-tuples accordingly). Let us restrict to the case $t=2$ to make the idea clear; general $t$ would only obscure the heart of the argument (besides being verbose and error-prone to formulate):
$$\begin{align}
P^{(2)}(S^m_2) &= \sum_{k_1 \ge -m} \,\sum_{k_2 \ge -k_1-m} P^{(2)}(\xi^{(2)}_1 = k_1)P^{(2)}(\xi^{(2)}_2 = k_2) \\
&= \sum_{k_1 \ge -m} \, P^{(2)}(\xi^{(2)}_1 = k_1)P^{(2)}(\xi^{(2)}_2 \ge -m -k_1)\\
& \le \sum_{k_1 \ge -m} \, P^{(2)}(\xi^{(2)}_1 = k_1)P^{(1)}(\xi^{(1)}_2 \ge -m -k_1) & & \text{by assumption} \\
& = \sum_{k_2 = -\infty}^\infty \, \sum_{\substack{k_1 \ge k_2-m \\ k_1 \ge-m}} P^{(2)}(\xi^{(2)}_1 = k_1)P^{(1)}(\xi^{(1)}_2 = k_2) & & \text{rearranging of indices} \\
& = \sum_{k_2 = -\infty}^\infty \, P^{(2)}(\xi^{(2)}_1 \ge \min\{k_2-m,-m\})P^{(1)}(\xi^{(1)}_2 = k_2) \\
& \le \sum_{k_2 = -\infty}^\infty \, P^{(1)}(\xi^{(1)}_1 \ge \min\{k_2-m,-m\})P^{(1)}(\xi^{(1)}_2 = k_2) \\
& = P^{(1)}(S^m_2)
\end{align}$$
The careless exchanging of summations is justified because all of them converge absolutely. For general $t$, the idea is the same, only the amount of characters necessary to describe the summation limits increases.
Hopefully there will be other answers because this is very inelegant. (My original approach tripped over some unaccounted conditional probabilities, which I later observed to violate desired inequalities in some cases. Thus I had to start again from scratch.)
Comment: Actually am not able to show how to prove the inequality by induction, as I am not able to find the explicit expression for $P(S_t^m)$ given the probability at the previous time. This expression should contain explicitly the terms $P(\xi \geq k) $ to prove the inequality, right? Could you please clarify this point? Thanks a lot!
Comment: Moreover is it formally correct writing the probability of the event $S^m$ using the measures $P^{(1)}$ or $P^{(2)}$? Shouldn't one define a new probability measure on the product of the spaces $K$?  The event involves sequences of outcomes of $\xi$ and not a single outcome of $\xi$...
Comment: You are correct regarding the second point. I think one can consider a sequence of ever finer sigma-algebras on the set $\Bbb Z^{\Bbb N}$ (which only pay attention to the first $t$ coordinates and use some measures naturally derived from $P^{(i)}$; I won't have time to elaborate on the induction (turns out I made a small but likely repairable mistake somewhere) before dinner. It should be up later tonight - apologies for any inconvenience.
Comment: Thanks a lot for the new answer. In any case would like to see whether is it possible to prove it more elegantly, because this doesn't seem to me to be a rigorous proof...
Comment: It is actually rigorous, but the expressions involved are so ugly that lots of trees would have to die to state then and prove them correct. Part of the issue is that: $$\Pr(\xi_{1,i} \ge k) \ge \Pr(\xi_{2,i}) \ge k \implies \Pr(\sum_i \xi_{1,i} \ge k) \ge \Pr(\sum_i \xi_{2,i} \ge k)$$ is a nontrivial thing to prove because of the "diagonal alignment" of the latter points in $\Bbb Z^n$.
Comment: * Sorry for misplacing that closing bracket in the displayed equation.

Inequality between two Random Walks


How to change drupal views filter from string to in opreator

Question: <code>/**
 * Implements hook_views_data().
*/
function ***_views_data_alter(array &$data) {
  $data['content_moderation_state_field_data']['moderation_state']['filter']['id'] = 'content_moderation_state_select';
}

/**
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("content_moderation_state_select")
 */
class ModerationStateFilter extends InOperator {

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->definition['options callback'] = array($this, 'generateOptions');
  }

  /**
   * Helper function that generates the options.
   * @return array
   */
  public function generateOptions() {
    $workflow = \Drupal::entityTypeManager()->getStorage('workflow')->load('editorial');
    $destinations = $workflow->getStates();
    $options = [];
    foreach ($destinations as $item){
      $options[$item->id()] = $this->t($item->label());
    }
    return $options;
  }
}
</code>
This works fine on config views,but can't save views conrrect.
Comment: You are aware that the core team is working on a patch for this in this issue? https://www.drupal.org/node/2862041 Perhaps that will get you further?
Comment: @Neograph734 Thank you very much,that is what i need.I miss the schema file for filter value.
Answer: Add filter value schema file in your module config/schema dir works fine.
***.views.schema.yml
<code># Schema for the views filter value.
views.filter.content_moderation_state_select:
  type: views.filter.in_operator
  label: 'Moderation state'

views.filter_value.content_moderation_state_select:
  type: views.filter_value.in_operator
</code>


Comparing two logit models

Question: Folks,
Would appreciate any advice on the following topic.
My question I would like to answer is the following.
What are the determinants of being a First Time Buyer of a House?
Based on a survey I have a dataset which contains a binary indicator if an individual identified themselves as a First Time buyer or not. The idea is to fit a logistic regression model where my dependent variable would be the binary indicator and I would have a number of controls such as; Age, Income, House Price, Region where house is located, nationality of owner.
However, I have a suspicion that the FTB indicator in the survey may underestimate the proportion of first time buyers i.e. individuals who should be a FTB are not denoting themselves as one.
Therefore, I have developed my own method to independently identify whether someone may be a first time buyer. This involves examining administrative records based on property purchases.
I would like to fit a logit model for this too and compare results. Note that the cohorts are exactly the same.
Is it possible to compare and contrast the results of these two models and identify whether one is a better predictor or not?
Basically I need some way to validate my own methodology.
Any ideas are welcomed.
Comment: Then I don't see how it makes sense to assess whether a model for one is more predictive than a model for the other.  The issue as I understand it is which variable is more accurate.  How well you can predict what might be the wrong value in the first place is beside the point.
Comment: The dependent variable has different values in each case?
Comment: The Dependent variable is binary in both cases. For example we sample of 100 people. Are dependent variable based of the survey response has a split of 40/60. The split based on the new methodology is 20/80. We know for the 100 individuals where the values match and where they do not.
Answer: Is your personal method more reliable than the self-reported information (SRI)? If so, then forget about the self-reported information. If your method does not make use of the SRI then you could specify the SRI as a model predictor (as a control variable). First thing I would do is to cross-tabulate the 2 variables - Eventually you could specify another logistic model of the matching proba. Or you could also use a multinomial logistic regression with 3 modalities: (1) FTB (The 2 methods are in agreement); (2) Not FTB (The 2 methods are in agreement); (3) Uncertain (The 2 methods disagree).
Answer: You could compare log likelihoods for sake of model fitting, but that's not predictive validity, which is what you are wanting. You say they are the same cohort. Can you make exact matches? Maybe follow up on those people where the models disagree, via interview or questionaire, and use that new data to re-train your model.
Answer: Just a quick idea: first you can do the Likelihood Ratio Test for each of the 2 models, just to check if a certain model (logit) fits the dataset well enough
If resulting p-value is under a certain threshold (e.g. 0.05) you can drop the related model (as it does not fit the dataset well enough) : so you succeed to reject the null hypothesis (that model fits the dataset)
If in both cases you fail to reject the null hypothesis (so both the models fit the dataset well enough) you can check whether one fits better than the other, comparing the p-values and keeping the higher one
Another idea could be to use a metric focused on representing unexplained variance: even if in case of logit, contrary to linear regression, you do not have R^2 there are pseudo R^2 developed for this purpose (let me check and come back to you later with an edit)
Comment: LR test should only be used to compare nested models (eg Y = X1 + X2 vs Y = X1).
Comment: @Umka 1) can you provide source for your claim? 2) Does my answer deserve a -1 considering it also includes another point which you have not criticized?
Comment: Don't have a particular reference in mind. Any stat textbook would explain how/when LR test can be used. Wiki page too. LR test is based on the difference in loglik between the "large" (unconstrained) and "small" (constrained) models. This difference is known as "deviance" and this quantity has to be positive. When you use LR test to compare models with different DVs, there is no guarantee that the "large" (or reference) model will perform better than its competitor, such that you could end up with a negative deviance.  If the 2 models have the same number of model parameters, then 0 DF test
Comment: Re the down vote, I did not intended to be mean - I simply believed your answer was misleading but will see if I can remove it later on
Comment: Being a bit more specific: I haven't heard of doing an LR test on one model. Your first sentence seems to read as: do an LR test on each model, to check if each model fits well enough. We definitely use LR tests to compare a pair of nested models - the null hypothesis is that the more restrictive model, i.e. the one with fewer parameters, and the less restrictive one fit the data equally well. Was that what you meant?
Comment: OK I understand I explained that part in a bad way: what I wanted to say is to run each LR against a model with fewer predictors so to check if logit is actually an improvement
I'd like to edit the answer to better specify this and so, hopefully, I'll have the malus points removed
Comment: LR test do require models to be nested as mentioned.  They are most commonly used to test a reduced model vs a full model to reduce complexity. A link from minitab, which i have never used, but is considered a reliable source.  https://support.minitab.com/en-us/minitab/18/help-and-how-to/quality-and-process-improvement/capability-analysis/supporting-topics/distributions-and-transformations-for-nonnormal-data/what-is-the-likelihood-ratio-test/

Comparing two logit models


Convergence of $\frac{\sin(x)}{x}$

Question: For every $x \in \mathbb{R}$ holds that $ - 1\le \sin(x) \leq 1$. So in my opinion the following inequality is true $ -\frac{1}{x} \leq \frac{\sin(x)}{x} \leq \frac{1}{x}$ and we have $\lim _{n \rightarrow \infty} \frac{1}{x}$, $\lim _{n \rightarrow \infty} -\frac{1}{x} = 0$. But $\lim _{n \rightarrow \infty}  \frac{\sin(x)}{x} \neq 0 $. Where's my fallacy?
Comment: But that limit is zero. Are you thinking of the limit as $x\to 0$? In that case the squeeze theorem won't work as you've set it up.
Answer: I think you meant $\lim_{x \to  \infty} \dfrac{\sin x}{x}$, in which case, yes this limit is $0$. What I believe you are confusing this with is an entirely different limit: $\lim_{x \to 0} \dfrac{\sin x}{x}=1$. Notice one is to infinity, the other is to $0$.
Comment: Thanks a lot, that was exactly the problem!
Answer: The inequality you used is just an application of the well-known Squeeze-theorem.
For $\displaystyle\lim_{x\to 0}\frac{\sin x}{x}=1$ See:How to prove that $\lim\limits_{x\to0}\frac{\sin x}x=1$?

Convergence of $\frac{\sin(x)}{x}$


Array value replacement from array within array in iPhone

Question: I have array output like this.
<code> {
    id = 1;
    user = {
            name="ABC"
            }
 },
{

    id = 2;
    user = {
            name="XYZ"
            }
 },
</code>
I have to change id with number 5 and 6 and name with "asd" and "fgh". My array definition is here.
<code>      myArray=[[NSMutableArray alloc]initWithArray:statuses];
</code>
And here is my approach for chaning of "id".
<code> [[myArray objectAtIndex:0]replaceObjectAtIndex:0 withObject:@"5"];
 [[myArray objectAtIndex:0]replaceObjectAtIndex:0 withObject:@"6"];
</code>
But I am getting following acception.
<code> [__NSCFDictionary replaceObjectAtIndex:withObject:]: unrecognized selector sent to  instance 0x6511810
 Terminating app due to uncaught    exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x6511810'
</code>
Answer: myArray seems to be NSArray which is Immutable.
How did you declare myArray?
EDIT:
<code>First:
</code>
myArray = [statuses mutableCopy];
Second:
<code>[[myArray objectAtIndex:0] setObject:@"5" forKey:@"id"];
[[myArray objectAtIndex:1] setObject:@"6" forKey:@"id"];
[[[myArray objectAtIndex:0] objectForKey:@"user"] setObject:@"asd" forKey:@"name"];
[[[myArray objectAtIndex:1] objectForKey:@"user"] setObject:@"fgh" forKey:@"name"];
</code>
Comment: Try instead :  myArray= [statuses mutableCopy];
Comment: I changed but still same problem.
Comment: [[myArray objectAtIndex:i] setObject:@"5" forKey:@"id"]; - this is the mistake ; this is the way you update because you have a dictionary inside.
Comment: Will it not change "id" to 5? and how will i change username which is inside of "user"? Thanks


Adding Google maps to a page

Question: I'm trying to add google maps into the header of a view, nothing fancy, as I just used the demo code from the google maps page.
<code><script src="http://maps.google.com/maps?file=api&v=2&key=myKey"
          type="text/javascript"></script>
        <script type="text/javascript">

        jQuery(document).ready(function() {
          if (GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("map_canvas"));
            map.setCenter(new GLatLng(37.4419, -122.1419), 13);

            var marker = new GMarker(map.getCenter());
            GEvent.addListener(marker, "click", function () {
              marker.openInfoWindowHtml("Hello");
            });
            map.addOverlay(marker);
          }
        })

        </script>
</code>
But for some reason I'm getting this error:

Uncaught TypeError: Cannot read property 'firstChild' of null

I have no idea what is going wrong.
Answer: Do you have an HTML element with the id of "map_canvas" anywhere on the page?
Also I'm assuming you actually have your API key in your first script tag and it doesn't actually say "myKey".
Comment: Oh snap, I totally forgot to add the div to my page, everything works fine now. Thank you.
Comment: Glad it works - sometimes it's the simplest answers

You also might want to check out http://drupal.org/project/gmap if you're using Drupal 6, or http://drupal.org/project/openlayers for integrating maps into Drupal.

Both let you apply geocoded nodes to a map really easily with Views support.

Adding Google maps to a page


simple dataframe to a complex list conversion in R

Question: Need to create an options group to be used by selectizeInput widget in Shiny.
Starting sample dataframe
df <- data.frame("Region" = c("Eastern", "Eastern", "Western", "Western"),
              "City" = c("New york", "New Jersey", "California", "Washington"),
              "Abb" = c("NY", "NJ", "CA", "WA"))

Wanted list
 l <- list(Eastern = c(`New York` = 'NY', `New Jersey` = 'NJ'),
     Western = c(`California` = 'CA', `Washington` = 'WA'))

Manual solution is
Eastern <- df[which(df$Region == "Eastern"),]
Western <- df[which(df$Region == "Western"),]
list(Eastern = setNames(Eastern$Abb, Eastern$City), Western = setNames(Western$Abb, Western$City))

Is there a better way to do this
Answer: You can try split
with(df, split(setNames(as.character(Abb), City), Region))
#$Eastern
#  New york New Jersey
#     "NY"       "NJ"

#$Western
# California Washington
#     "CA"       "WA"


Altering nodes title value

Question: I am trying to alter the title of my nodes to prevent URLS appearing in any title. This is the code I am using.
function mytemplate_preprocess_node(&$variables) {
  $node = $variables['node '];
  $variables['title'] = cleaner(check_plain($node->title));
}

cleaner() removes URLs from nodes. The above works perfectly on teasers, but not on full view or when the title is displayed in a list with other articles inside a block.
How can I make sure that the URL disappear whenever the concerned node's title is listed?
Comment: You should do this cleanup in node_presave(https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_presave/7)
Comment: @Yaz: Have a got answer to your problem, and if found some other work around than please share. Thanks
Answer: You need to implement both

template_preprocess_page() : this will take care of node full view mode.
temaplte_proprocess_node() : this will take care of node teaser view mode

In your theme template.php
function mythemename_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "your content type") {
    drupal_set_title("your_title");
  }
}

/**
 * Override or insert variables into the node template.
 */
function mythemename_preprocess_node(&$variables) {
  if($variables['type'] == "your content type") {
    $variables['title'] = "your title";
  }
}

Note:

only changing in template_preprocess_node(), will now reflect on node teaser view as it will be overridden by page template.
in order to change  you should use drupal_set_title() instead of $variables['title'].
Comment: Thanks this works perfectly for the existing nodes, but for the new ones i ll use the above solution with node_presave
Comment: true, but its wiser according to me having one solution
as keeping the other two proprocess hooks will be fired anyway! so take your pick honestly I do not see difference between existing and new if you have all the codes put to work.Preferably you can dry run with node_save function keeping code mentioned in hook_node_presave() and remove the preprocess function from template file
Answer: Use template_preprocess_page() in the template.php to update the page title for full view, However please don't your code for hook_preprocess_node() as that code would be required for updating the page title for teaser view.
Examples:
// Example of updating the nodes title for all content types.
function MYTHEME_preprocess_page(&$vars) {
  // Check if the variable is of node type.
  if (!empty($vars['node']) {
    $updated_title = cleaner(check_plain($node->title));
    drupal_set_title($updated_title);
  }
}

To update the page title of specific page just update the if condition as below:
if (!empty($variables['node']) && $variables['node']->type == 'CONTENT_TYPE') {
  $updated_title = cleaner(check_plain($node->title));
  drupal_set_title($updated_title);
}

The above things will update the page title at the time of rendering, however the better solution is to clear the URL's from the node title before saving (insert/update) the node so that you wont need to modified at the time of rendering:
// Using the hook_node_presave() for removing the URL's from title.
function MyModule_node_presave($node) {
  $node->title = cleaner(check_plain($node->title));
}

Note: The hook_node_presave() will help you for new nodes and the nodes those you are going to update.
Comment: You shouldn't really call drupal_set_title() from a template like that. If you must, then put it in template_preprocess_page() in the tempalte.php, otherwise in a module in hook_node_view() or similar.
Comment: hook_view_pre_render is not suppose to use here!this hook is invoked jus before rendering a view
Comment: you might be confusing with "The above works perfectly on teasers, but not on full view" node full view and view are two different things :)
Comment: @arpitr He wants to update the title of his views too

Altering nodes title value


Partition of $\Bbb R^2$ arising from matrix multiplication.

Question: Describe the partition of $\Bbb R^2$ arising from the action, by matrix multiplication, of the subgroup $H=\left\{\begin{pmatrix}
    1 & 0\\
    a & 1
\end{pmatrix}:a\in\Bbb R\right\}$ of $GL_2(\Bbb R)$.
First of all I don't think I really understand the question itself. Does it means I pick elements of $H$ and apply matrix multiplication to $\begin{pmatrix}
    x\\
    y
\end{pmatrix}$ where $x,y\in\Bbb R$? I don't know how to describe the partition of a cartesian in terms of matrix multiplication And don't know what partition to describe I am confused. And why is the answer like this:"The lines $x=c$ for $c\neq0$ and the points $(0,b)$"?
Answer: Let's first prove that indeed $H\le\operatorname{GL}_2(\mathbb{R})$, and that we really have a $H$-action on $\mathbb{R}^2$.

Subgroup - closure:
$\space\begin{pmatrix}
1 & 0 \\
a & 1 \\
\end{pmatrix}
\begin{pmatrix}
1 & 0 \\
b & 1 \\
\end{pmatrix}=
\begin{pmatrix}
1 & 0 \\
a+b & 1 \\
\end{pmatrix}\in H$;

Subgroup - "closure by inverses":
$\space\begin{pmatrix}
1 & 0 \\
a & 1 \\
\end{pmatrix}^{-1}=
\begin{pmatrix}
1 & 0 \\
-a & 1 \\
\end{pmatrix}\in H$;

Action - property #0:
$\space\begin{pmatrix}
1 & 0 \\
a & 1 \\
\end{pmatrix}
\begin{pmatrix}
x \\
y \\
\end{pmatrix}
=
\begin{pmatrix}
x \\
ax+y \\
\end{pmatrix} \in \mathbb{R}^2
$

Action - property #1:
$\space\begin{pmatrix}
1 & 0 \\
0 & 1 \\
\end{pmatrix}
\begin{pmatrix}
x \\
y \\
\end{pmatrix}
=
\begin{pmatrix}
x \\
y \\
\end{pmatrix}
,\space\space\forall \begin{pmatrix}
x \\
y \\
\end{pmatrix}\in \mathbb{R}^2$

Action - property #2:

$
\space\biggl(\begin{pmatrix}
1 & 0 \\
a & 1 \\
\end{pmatrix}
\begin{pmatrix}
1 & 0 \\
b & 1 \\
\end{pmatrix}
\biggr)
\begin{pmatrix}
x \\
y \\
\end{pmatrix}
=
\begin{pmatrix}
1 & 0 \\
a+b & 1 \\
\end{pmatrix}
\begin{pmatrix}
x \\
y \\
\end{pmatrix}
=
\begin{pmatrix}
x \\
(a+b)x+y \\
\end{pmatrix}
=
\begin{pmatrix}
x \\
ax+bx+y \\
\end{pmatrix}
=
\begin{pmatrix}
1 & 0 \\
a & 1 \\
\end{pmatrix}
\begin{pmatrix}
x \\
bx+y
\end{pmatrix}
=
\begin{pmatrix}
1 & 0 \\
a & 1 \\
\end{pmatrix}
\biggl(
\begin{pmatrix}
1 & 0 \\
b & 1 \\
\end{pmatrix}
\begin{pmatrix}
x \\
y \\
\end{pmatrix}
\biggr)
,\space\space
\forall \begin{pmatrix}
1 & 0 \\
a & 1 \\
\end{pmatrix}, \begin{pmatrix}
1 & 0 \\
b & 1 \\
\end{pmatrix}\in H, \space\space\forall \begin{pmatrix}
x \\
y \\
\end{pmatrix}\in \mathbb{R}^2
$
From the general action theory, we know that the "acted upon" set, i.e. here $\mathbb{R}^2$, is partitioned into "orbits", given by (here $X$ is the generic point of $\mathbb{R}^2$):
$$O(X)=\{AX, A\in H\}=\biggl\{\begin{pmatrix}
x \\
ax+y \\
\end{pmatrix}, \space \space a\in \mathbb{R}\biggr\}\tag 1$$
By $(1)$, the orbits by $x=0$ points "don't feel" the action of $H$ (via the parameter $a$): the points of the $y$-axis ($x=0$) constitue each a "degenerate" orbit:
$$O(X_{x=0})=O(y)=\biggl\{\begin{pmatrix}
0 \\
y \\
\end{pmatrix}, \space \space a\in \mathbb{R}\biggr\}=\biggl\{\begin{pmatrix}
0 \\
y \\
\end{pmatrix}\biggr\}$$
Off $y$-axis points ($x\ne 0$), instead, are moved all along the "vertical" direction by the point $(x,y)$. Summarizing, the partition of $\mathbb{R}^2$ induced by this action is made of single-point orbits (one for each point of the $y$-axis) and "vertical", straight lines for the rest of the real plane.
Answer: If you multiply the mentioned matrix by $\begin{bmatrix}x\\y\end{bmatrix}$, what happens is that $x$ remains constant and $y$ is translated by $ax$. Since $a$ can be any number in $\mathbb R$, and only $y$ will change then all the resulting vectors will end up with
$$\begin{bmatrix}x\\y+ax\end{bmatrix}$$
We will have one special case which occurs if $x=0$, then we get $$\begin{bmatrix}0\\y+a\cdot 0\end{bmatrix} = \begin{bmatrix}0\\y\end{bmatrix}$$
So these will be the isolated points $(0,b)$ in the answer, where $y=b$.
Whenever $x\neq 0$ we will have a parametrized line $\begin{bmatrix}x\\y\end{bmatrix} +a\begin{bmatrix}0\\x\end{bmatrix}$ for the parameter $a$.
Comment: Yes $y$ will become equal to $b$ in the answer in this case.


How would you add a share to smb.conf via a script?

Question: I'd like to script adding a share to a smb.conf file. My current script just appends it to the end of the file, but that's not ideal. I'd rather have something that will add a new share if it doesn't exist, and replace it if it does.
I'm currently scripting this on a CentOS 7 distro, but would ideally like something that would work across distros, though that's not a requirement.
Also, I'm using bash to do this because the script is run before other packages are added to the system. The script uses yum to install the samba packages, and then is supposed to configure it and add shares.
Comment: Check for pre-existing modules for your favourite scripting language. For example, I quickly found [File::Samba](https://metacpan.org/pod/File::Samba) for perl
Comment: Can you tell us more about the environment and context of what you are doing?  If I had a server and I wanted to programmatically change shares often, then I would create a directory, setup an include for that directory.  Then I would just place one file per share in that directory.
Comment: @glennjackman - That would be ideal, but I was hoping to not have to add additional scripting languages and packages. This is part of an rpm and I'd rather not have a lot of pre-requirements. If I'm going to do that, I might as well use saltstack, puppet, chef or another tool like that. I was hoping for something more lightweight. Too bad there isn't a smbconfmerge command. I wonder what saltstack uses?
Answer: To fit with modern sysadmin best practices it would be good to add your configs as individual files in /etc/smb/smb.d and then reference them with an include.  Sadly samba does not support wildcard includes so you have to do add something like:
include = /etc/smb/includes.conf

in your smb.conf and then generate the includes.conf with something like:
ls /etc/smb/smb.d/* | sed -e 's/^/include = /' > /etc/smb/includes.conf

For a bit more context:
chicks@silver 23:57:23 smb !531 $ ls smb.d
a.conf  c.conf  e.conf
chicks@silver 23:57:29 smb !532 $ ls /etc/smb/smb.d/* | sed -e 's/^/include = /' > /etc/smb/includes.conf
chicks@silver 23:57:40 smb !533 $ cat includes.conf
include = /etc/smb/smb.d/a.conf
include = /etc/smb/smb.d/c.conf
include = /etc/smb/smb.d/e.conf

So now you can stick any additional samba configs into /etc/smb/smb.d, regenerate includes.conf and restart samba and life is good.
Comment: Yep, that should work well regardless of distro (unless the distro comes with something like this already, but I haven't seen one yet). It'd be the same procedure no matter what you're changing: make x.conf changes/additions/removal, rebuild includes.conf, restart the daemon.
Comment: Is that independent of the distro? Also, how does that work if you want to update parameters as well as add/remove shares?
Comment: This doesn't work with global settings. It also doesn't fix the issue that a particular share name could be added to one of the a.conf, b.conf, or c.conf files already.
Comment: There's nothing to stop you from grepping through all of the configs and making sure they are up to some standard.  You could use a similar mechanism for global settings too.  One include for global settings would point to `*.conf` and another for shares would point to `*.share`.
Comment: https://docs.ansible.com/ansible/latest/modules/lineinfile_module.html would be another way to handle this.
Answer: This is an old topic but still useful.
This are my scripts to create and delete users in a simple samba installation for storing backups.
Tested on CentOS
Prepare directory and permissions
Run this commands on a terminal

sudo mkdir /backups
sudo mkdir /etc/samba/smb.conf.d
sudo groupadd sambashare
sudo chgrp sambashare /backups
sudo useradd -M -d /home/sadmin -s /usr/sbin/nologin -G sambashare sadmin
sudo smbpasswd -a sadmin
sudo smbpasswd -e sadmin

smb.conf

[global]
    workgroup = TUAITI
    security = user

    passdb backend = tdbsam

    printing = cups
    printcap name = cups
    load printers = yes
    cups options = raw

include = /etc/samba/includes.conf

smbaddshare.sh

#!/bin/bash
USER=$1
if [ -z "$1" ]
then
    echo "No username given"
    exit 1
fi

useradd -M -d /backups/$USER -s /usr/sbin/nologin -G sambashare $USER
mkdir /backups/$USER
chown $USER:sambashare /backups/$USER
chmod 2770 /backups/$USER
smbpasswd -a $USER
smbpasswd -e $USER

cat  /etc/samba/smb.conf.d/$USER.conf
[$USER]
    path = /backups/$USER
    browseable = no
    read only = no
    force create mode = 0660
    force directory mode = 2770
    valid users = $USER @sadmin
EOF

ls /etc/samba/smb.conf.d/* | sed -e 's/^/include = /' > /etc/samba/includes.conf

smbcontrol all reload-config

smbremoveshare.sh

#!/bin/bash
USER=$1
if [ -z "$1" ]
then
    echo "No username given"
    exit 1
fi

read -r -p "Are you sure you want to delete the user ? [y/N] " response
response=${response,,}    # tolower
if [[ "$response" =~ ^(yes|y)$ ]]
then
    smbpasswd -x $USER
    userdel $USER
    mv /backups/$USER /backups/$USER.`date +"%Y%m%d%H%M%S"`.deleted
    rm /etc/samba/smb.conf.d/$USER.conf

    ls /etc/samba/smb.conf.d/* | sed -e 's/^/include = /' > /etc/samba/includes.conf

    smbcontrol all reload-config
else
    echo "Nothing done"
fi


C5.0, boosting, and mislabeled data

Question: I'm trying to model a binary classification problem.  5 continuous features, slightly imbalanced dataset (about 60 in one class, a little more than 200 in another).
So far I've tried kNN, LDA, and C5.0.  C5.0 works very well (e.g. the AUC for ROC is very good).
However, I've read that boosting a la AdaBoost has problems in the presence of mislabeled data, and that C5.0's boosting is reminiscent of AdaBoost.  My data is mislabeled insofar as perhaps 5% of them are probably wrong.  (I'm vague here, because it's a real-world problem where the ground truth is fuzzy---good, but not perfect.)
Does anyone know how well C5.0 boosting performs in the presence of mislabeled data?
Comment: The problem is that nobody has really studied C5.0 so far (it has been in the private domain until a year or so ago).
Answer: AdaBoost is indeed susceptible to mislabeled data (aka noise).  Friedman et al's paper "Additive logistic regression: a statistical view of boosting" offers an explanation.
However, C5.0's boosting is somewhat different from AdaBoost, e.g. additive rather than multiplicative weight adjustment of misclassified cases, with the goal of improving performance in the presence of moderate noise.
C5.0 was released under GPL in Jan 2011.

C5.0, boosting, and mislabeled data


Multisample SEM in R: Differences in significance level using UVI vs ULI

Question: I'm a graduate student in psychology trying to examine the factor invariance of some psychological constructs worry (using a two-factor model) using Structural Equation Modelling (SEM) in R, using the lavaan package. I am comparing two groups (male & female).
According to Beaujean (2014), there are different types of measurement invariance (1. Configural invariance, 2. Weak invariance, 3. Strong invariance etc). Different genders survived Configural invariance by demonstrating a good fit in terms of CFI, SRMR, RMSEA etc. However, upon testing weak invariance (testing whether the factor loadings are the same across groups), the model doesn't show a good fit.
To see where the discrepancies lie, I then compared the estimates of factor loadings in males and females using Unit Variance Identification.
CFA.model.UVI <- '
# measurement equations
Factor1 =~ c(m1,f1)*item_1 + c(m2,f2)*item_2 + c(m3,f3)*item_3
Factor2 =~ c(m4,f4)*item_4 + c(m5,f5)*item_5 + c(m6,f6)*item_6

# compare estimates
diff1 := m1 - f1
diff2 := m2 - f2
diff3 := m3 - f3
diff4 := m4 - f4
diff5 := m5 - f5
diff6 := m6 - f6
'

I examined the significance level of diff1 to diff6 and found that most of them are NOT significantly different. HOWEVER, I then fit a Unit Loading Identification (ULI) model.
CFA.model.ULI <- '
# measurement equations
Factor1 =~ 1*item_1 + c(m2,f2)*item_2 + c(m3,f3)*item_3
Factor2 =~ 1*item_4 + c(m5,f5)*item_5 + c(m6,f6)*item_6

# compare estimates
diff2 := m2 - f2
diff3 := m3 - f3
diff5 := m5 - f5
diff6 := m6 - f6
'

Surprisingly, the model shows that diff2 and diff3 are significantly different but diff5 and diff6 are not. In other words, UVI and ULI give different estimates and different significance levels.
I have two questions:

Is it legitimate for me to compare estimates of two groups?
If it is legitimate, which model (UVI or ULI) should be more reliable?

Thanks so much.
Answer: Brief response to your two queries: yes, and UVI. But, as brief responses...there are many scenarios where these answers are actually incorrect.
I'll elaborate more, but in the reverse order you asked the questions.
The issue you raise is less about reliability with the models, and more about the estimation process and structure (artificially) imposed on the latent variables. The latent variables can be anchored to one item (meaning the latent variable shares the same scale) or standardized like a $z$-score. And, it is possible for the resulting models to produce different cross-group results. So, in this case, you should focus on what you are asking: ¿are the factor loadings the same for the groups? Because of this, you can answer this better by fixing the variance and freely estimating the loadings. In the ULI model, you essentially go in with the assumption that item 1 has the same factor loading.  And if it doesn't, this means the latent variables will be different for each group.
So, if you run the UVI, you can indeed compare estimates for each group. However, I would suggest a more conventional test.  If you decide that an item may have different factor loadings, then do a model comparison. Run the UVI model with all the loadings constrained, and then run another model with only one of the pairs freely estimated for each group. E.g., for all, use c(mf#,mf#); for the second model, go back to c(m#,f#). You can then do a chi-square test to see if the models are statistically significantly different.  If so, they should be estimated separately.  If not, they can be equated and you can move to the next model invariance test.
Hope this helps.
Comment: No worries...those sample sizes are fine for multi group comparisons.
Comment: Thank you very much! You certainly helped a lot! I have a follow-up question: If the sample size of my two groups are not equal (I have roughly 300 males and 700 females), is it gonna be a problem? @Gregg H
Comment: Thanks a lot. I'm extremely grateful to your clear and prompt help!