How to setState() dynamically in between Parent and Child Component [Logic being run on child & state on the Root App level]

Question: I am fooling around while learning React and I would like to know what would be an elegant solution for the scenario presented below.
Follow this Link to see the complete code set.
I have a child component, that has a
 tag. This tag returns a message that I am displaying dynamically as will be shown below.
App root container
I have my state on this container, and I want to keep it just there.
State:
The object of discussion here is the cockpitAlert object.
 state = {
        state = {
    persons: [
      { id: "a", name: "foo1" },
      { id: "b", name: "foo2" },
      { id: "c", name: "foo3" }
    ],
    CockpitAlert: {
      regular: "Some message",
      alert1: "The array is ending",
      alert2: "There is nothing to show"
    }
  };

Below is how I delete the rendered items - still on App.js
personDeleteHandler = index => {
    const person = [...this.state.persons];
    person.splice(index, 1);
    this.setState({ persons: person });
  };

Below is where I render my JSX
render() {
    return (

        <Cockpit
          regular={this.state.CockpitAlert.regular}
          alert1={this.state.CockpitAlert.alert1}
          alert2={this.state.CockpitAlert.alert2}
          personsLength={this.state.persons.length}
        />
        <Person click={this.personDeleteHandler} persons={this.state.persons} />

    );
  }

Cockpit child
Below is the logic. let message  dynamically changes the props according to the length of the persons array, that gets shortened upon clicks.
import React from "react";

function Cockpit(props) {
  let message = props.regular;
  if (props.personsLength <= 2) {
    message = props.alert1;
  }
  if (props.personsLength === 0) {
    message = props.alert2;
  }

  return (

{message}

  );
}

export default Cockpit;

As you can see this does not look very nice at all.
I don't want to have all of these different props being pointed on my logic:
regular={this.state.CockpitAlert.regular}
alert1={this.state.CockpitAlert.alert1}
alert2={this.state.CockpitAlert.alert2}
personsLength={this.state.persons.length}

I wonder if there is a way that I could pass just one props, e.g props.message and change it dynamically, probably through setState() on the root level, where the state is set without having to move my logic from Cockpit to App.js
Comment: So you want to keep the message value in your `App.js` but you want to update it within your `Cockpit` ?
Comment: Yes. I wonder if there is an elegant way of doing this. As you can see I have created 4 props so the variable would point to different props according to the logic being run on my child component. I wonder if I could keep just on ```props``` and somehow set it to different messages, while keeping the logic on the child component and state on the app root container
Answer: You could pass a function to the Child component. When the message is defined, it calls the function with the message in parameter. The Parent then receive the message via the function.

// Example class component
class Parent extends React.Component {
  state = {
    message: ""
  }

  updateMessage = message => {
    this.setState({
      message: message
    });
  }

  render() {
    return (

This is my parent

        <Child
          usersLength={0}
          alert1="Alert1"
          alert2="Alert2"
          alert3="Alert3"
          updateMessage={this.updateMessage}
        >
        </Child>
        <Child
          usersLength={1}
          alert1="Alert1"
          alert2="Alert2"
          alert3="Alert3"
          updateMessage={this.updateMessage}
        >
        </Child>
         <Child
          usersLength={2}
          alert1="Alert1"
          alert2="Alert2"
          alert3="Alert3"
          updateMessage={this.updateMessage}
        >
        </Child>

    );
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    const {usersLength, alert1, alert2, alert3} = props;
    let message = "";
    if(usersLength <= 2)
      message = alert1;
    if(usersLength <= 1)
      message = alert2;
    if(usersLength === 0)
      message = alert3;
    this.state = {
      message : message
    }
    props.updateMessage(message);
  }

  render() {
    const {message} = this.state;
    return
My child message is : {message}

  }
}

// Render it
ReactDOM.render(
  <Parent />,
  document.getElementById("react")
);

Comment: If the child is the functional prop, just move the  code from ´constructor´ to `render` and instead of setting the message to the state, just keep it in your variable
Comment: Actually this is not exactly what I am looking for. Once I delete the child list items, the array's length will shorten, then on 1 `````` tag i would display different messages according to the array's length.
Comment: I will reformulate the question
Comment: question reformulated!
Answer: Well I have discovered how to solve this issue using React Context API
here is the updated CodeSandBox
I have first created the file auth-context.js in order to pass my state from the Parent component to the child component.
As the logic is already based on the Cockpit.js I will only pass my state through React Context ApI in this case.
auth-context.js file
import React from 'react'

const authContext = React.createContext({
  persons: [
    { id: "a", name: "foo1" },
    { id: "b", name: "foo2" },
    { id: "c", name: "foo3" }
  ],
  message: "Some message",

});

export default authContext

On my App.js container
Now I have set the Provider in the App.js root container:
//first of all, import the file into the root element which will Provide the //initial state on this API

import AuthContext from "./Context/auth-context";

...

class App extends Component {
  state = {
    persons: [
      { id: "a", name: "foo1" },
      { id: "b", name: "foo2" },
      { id: "c", name: "foo3" }
    ],
    CockpitAlert: {
      message: "Some message"
    }
  };

  personDeleteHandler = index => {
    const person = [...this.state.persons];
    person.splice(index, 1);
    this.setState({ persons: person });
  };

  render() {
    return (

        //I am wrapping the whole deal here and set my state so I can manage it at
        // the Cockpit.js file further on
        <AuthContext.Provider
          value={{
            persons: this.state.persons,
            message: this.state.CockpitAlert.message
          }}
        >
         //no more props being passed at Cockpit.js!!!
          <Cockpit />
          <Person
            click={this.personDeleteHandler}
            persons={this.state.persons}
          />
        </AuthContext.Provider>

    );
  }
}

export default App;

Now I will pass my state into the child component
Cockpit.js file
import React, { useContext } from "react";
//must import AuthContent here as well.
import AuthContext from "../../Context/auth-context";

function Cockpit(props) {
  //this is the way of setting it up on a functional component
  // now I have access to the state through authContext
  const authContext = useContext(AuthContext);

  //here I will point my state into different messages
  if (authContext.persons.length <= 2) {
    authContext.message = "running out";
  }
  if (authContext.persons.length === 0) {
    authContext.message = "nothing else to render";
  }
  //as you can see there are no props created
  return
{
{authContext.message}
}
;
}

export default Cockpit;

Now my reflection is:
This is not mutating the original state, at App.js. Would this be a good practice in this case?
What do you guys think?


Is there a method to compare prediction from different models?

Question: I have a problem where I need to classify whether a client is likely to buy or not a service, I have around 10  service and 10.000 times more clients than service, and also rules that do not allow certain clients to buy specific service, say: a teenager can not buy alcohol delivery.
What I'm currently doing is to make a model for each of the 10 products, my problem is:
For a client, how can I compare the prediction of each of the models: say I model 1 return a probability of buying the service_1 of 0.4 and service_2 from model 2 has a probability of 0.6 can I directly compare those values? given that it is possible that the service1 is overall less likely to be bought
The history I have is the list of clients, some of the characteristics and whether they have or not a service.
Comment: Do you have the actual outcome (whether a given client actually did buy the product or not)?
Comment: @StephanKolassa Yes, I do. I have updated the question.
Answer:
can I directly compare those values?

Yes, provided all the models are well-calibrated (calibration) (or, perhaps, all badly-calibrated in the same way).

... given that it is possible that the service1 is overall less likely to be bought

This becomes very similar to the common question about class imbalance, where the general advice around here is to separate decision-making from modeling.
If the models are all well-calibrated, then your scenario puts a 40% chance of buying service_1 and a 60% chance of buying service_2, and that's that.  If every customer comes out as more likely to purchase service_2 as a result of service_1 being less popular, then...well, that's just the truth of the matter.  If you need to push service_1 despite that, then you can make different decisions based on the probabilities, suggesting service_1 even when it's less likely to be purchased, etc.
Answer: You can (and should) assess the quality of probabilistic predictions using a proper scoring rule. We have a scoring-rules tag, and there is a Wikipedia page. Note that most scoring rules are "negatively oriented", i.e., lower is better - but some people prefer the reverse orientation, by including (or removing) a minus sign.
Apply a scoring rule, e.g., the logatithmic score, to both models' predictions, and average them. The model with the lower (or higher, see above) scoring rule does a better job.
Comment: The question is about models with _different_ targets; it's not a question about which model is better.
Comment: @BenReiniger: ah. That may be. OP: can you confirm I misunderstood your question?


Getting the "processed" value of a formatted text field

Question: I have a formatted text field on a content type that I'm using as the body of an email. If I load the node and print out the field I get:
<code>>>> $n->field_thankyou_email_body->getValue()
=> [
     [
       "value" => "<b>Thanks!!</b>",
       "format" => "subscriber_text_lb",
     ],
   ]
</code>
The array is missing the "processed" value, how do I get that? Or alternatively how do I manually run the value through the text format?
Answer: A field property is accessed like an object property:
<code>$node->field_formatted_text->processed
</code>
As a side note, use this only for cases like this which are outside of the page render context. The preferable way is to render the text field in a render array to preserve attached metadata. See How to safely render node body on a custom variable?
Comment: oh so even though the debug doesn't show it, the property is accessible, thanks.
Comment: Yes, this is because it is a computed property. Like `entity` of a reference field or `date` of a datetime field. See https://drupal.stackexchange.com/a/252341/47547
Comment: I'm getting object unless I typecast as below,
`(string) $entity->get('field_formatted_text')->processed;`


How to redirect everything from no-www to www Except for few files, using .htaccess?

Question: How to redirect everything from no-www to www except for few files, using .htaccess?
I am using the following .htaccess to redirect no-www to www.
.htaccess
Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^[^.]+\.[^.]+$ [nc]
rewriterule ^(.*)$ http://www.%{http_host}/$1 [r=301,nc]

How do I add exception for few files?
for example:
1) example.com/page1.html should not be redirected to www.example.com
2) example.com/xml/page2.xml should not be redirected to www.example.com
Everything other then example.com/page1.html and example.com/xml/page2.xml should be redirected to www.example.com
Answer: You could chain your RewriteCond directives, e.g.:
RewriteEngine on
RewriteCond %{REQUEST_URI} ! ^/page1\.html$
RewriteCond %{REQUEST_URI} ! ^/xml/page2\.xml$
RewriteCond %{http_host} ^[^.]+\.[^.]+$ [nc]
RewriteRule ^(.*)$ http://www.%{http_host}/$1 [r=301,nc]


How to have views exposed filter value show as different value in the url?

Question: I have a search page with a Views exposed filter for the name of a taxonomy term. I have added an #autocomplete_route_name to the form element to make this an autocomplete selector for my term names. The autocomplete controller returns this:
foreach ($terms as $term) {
  if($term->hasTranslation($langcode)){
    $translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $langcode);
    $results[] = [
      'value' => $translated_term->getName(),
      'label' => $translated_term->getName(),
    ];
  }
}
return new JsonResponse($results);

this works fine, except the url ends up with the term name in the GET (url). Is there any way to have term id here?
I have seen many answers to this question to use hook_views_pre_view. These are fine to modify the value used in the views query, but has no impact on the url variable.
Comment: Can you bit clarify your query like you want to alter the query parameter name
or specific query parameter value in the URL?
Comment: query is something like term=hybrid+workplace but i want it to be tid=34
Answer: #1: To alter Query parameter value in the url of View page: redirect event subscriber approach used
<?php

    namespace Drupal\custom_module;

    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\HttpKernel\KernelEvents;
    use Symfony\Component\HttpKernel\Event\GetResponseEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Drupal\Core\Routing\RouteMatchInterface;
    use Symfony\Component\HttpFoundation\RequestStack;
    use Drupal\Core\Url;

    /**
     * Execute to changes query parameter value in the url of view page.
     */
    class RedirectSubscriber implements EventSubscriberInterface {

      /**
       * Current Route.
       *
       * @var \Drupal\Core\Routing\RouteMatchInterface
       */
      protected $route;

      /**
       * The request stack.
       *
       * @var \Symfony\Component\HttpFoundation\RequestStack
       */
      protected $requestStack;

      /**
       * Constructs a RedirectSubscriber object.
       *
       * @param \Drupal\Core\Routing\RouteMatchInterface $current_route_match
       *   The route match.
       * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
       *   The request stack.
       */
      public function __construct(RouteMatchInterface $current_route_match, RequestStack $requestStack) {
        $this->route = $current_route_match;
        $this->requestStack = $requestStack;
      }

      /**
       * {@inheritdoc}
       */
      public function redirect(GetResponseEvent $event) {
        $route_name = $this->route->getRouteName();
        // Get category name
        $term_name = $this->requestStack->getCurrentRequest()->query->get('category_name');
        // Get term id from category name
        $ary = preg_split('/[()]/', $term_name);
        $tid = $ary[1];
        if ($route_name == 'view.speaker.page_2' && isset($term_name)) {
          if (isset($tid)) {
            // Get all paramters page
            $params = $this->requestStack->getCurrentRequest()->query->All();
            // Alter the category_name query parameter value
            if ($params['category_name']) {
              $params['category_name'] = $tid;
            }
            // Set redirect url & pass all parameters to it
            $redirect_url = Url::fromRoute('view.view_bulk_test.page_2')->setOptions(['query' => $params])->toString();
            if ($redirect_url) {
              // Pass Redirect URL.
              $event->setResponse(new RedirectResponse($redirect_url, 301));
            }
          }
        }
      }

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events[KernelEvents::REQUEST][] = ['Redirect', 20];
        return $events;
      }

}

File path: : module_name/src/RedirectSubscriber.php
Define: module_name.services.yml (inside custom module)
 services:
  module_name.redirect_subscriber:
    class: Drupal\module_name\RedirectSubscriber
    arguments: ['@current_route_match', '@request_stack']
    tags:
      - { name: 'event_subscriber' }

In this scenario query parameter whose value altered is autocomplete taxonomy referenced type field & if tid passed then error 'll display:
There are no taxonomy terms matching "2".
To fix it: Used hook hook_views_pre_view():
use Drupal\taxonomy\Entity\Term;

function module_name_views_pre_view(ViewExecutable $view, string $display_id, array $args) {
  if (($view->id() == 'speaker')) {
    $exposedInput = $view->getExposedInput();
    // Get term id from category name
    $tid = $exposedInput['category_name'];
    if(isset($tid)){
      // Load term object from term id
      $term = Term::load($tid);
      if(isset($term)){
        // Set value of filter in required format
        $val = $term->label().' '.'('.$tid.')';
        $exposedInput['category_name'] = $val;
      }
      // Set the exposed filter value in the view
      $view->setExposedInput($exposedInput);
    }
  }
}

#2: Query paramter name in the url of view page can be altered by the view  UI.
Steps:

Go to the required view and edit the view

Click the filter & filter settings 'll open in the modal

You will find 'Filter identifier' field , here you can specify the required parameter name.
Comment: Hmm, yes, just redirecting the page to a different url. Seems inefficient but that should work. Thanks. I'll try this out.
Comment: Yeah it's redirecting approach in which redirect to same page with query parameter value altered,
Comment: Tried to work with diff hooks of view before that hook's code execute , the page redirect
so for now found redirect event subscriber approach helps to achieve functionality.


Escrever em imagem com php

Question: Estou tentando imprimir certificados online preenchidos dinamicamente com PHP.
O código que estou usando é:
class Certificado
{

    public $nome_para_certificado = '';
    public $modelo_de_certificado = '';

    function __construct($nome)
    {
        $this->nome_para_certificado = $nome;
    }

    public function gerar()
    {
        header("Content-Type: image/jpeg");
        $texto = 'Certificamos que ' . $this->nome_para_certificado . ' participou do Evento nos dias 21, 22 e 23 de setembro de 2014 na Universidade Federal da Paraíba - UFPB';
        $img = imagecreatefromjpeg($this->modelo_de_certificado);
        $preto = imagecolorallocate($img, 0, 0, 0);
        $font_path = 'http://meu-site.com/custom/TravelingTypewriter.ttf';
        imagettftext($img, 50, 0, 10, 20, $preto, $font_path, $texto);
        // imagestring($img, 5, 300, 400, $texto, $preto);
        imagejpeg($img);
        imagedestroy($img);
    }
}

Quando uso imagestring consigo imprimir o texto direitinho mas com o imagettftext não ta dando certo.
Preciso usar o imagettftext pra poder modificar tamanho de fonte e tipo também.
Answer: Amigo um detalhe muito importante que precisa ser ressaltado, você usou o caminho da fonte com http:
    $font_path = 'http://meu-site.com/custom/TravelingTypewriter.ttf';
    imagettftext($img, 50, 0, 10, 20, $preto, $font_path, $texto);

O correto seria usar o caminho absoluto que está no teu servidor, supondo que no seu servidor o caminho seja:

Se /etc/www/custom então use:
$font_path = '/etc/www/custom/TravelingTypewriter.ttf';
imagettftext($img, 50, 0, 10, 20, $preto, $font_path, $texto);

Se /home/htdocs/custom então use:
$font_path = '/home/htdocs/custom/TravelingTypewriter.ttf';
imagettftext($img, 50, 0, 10, 20, $preto, $font_path, $texto);

Se c:\wamp\custom então use:
$font_path = 'c:/wamp/custom/TravelingTypewriter.ttf';
imagettftext($img, 50, 0, 10, 20, $preto, $font_path, $texto);

O motivo disto está explicado na documentação imagettftext:

Dependendo da versão da biblioteca GD usada no PHP, quando fontfile não começar com / então o caminho do .ttf será acrescentada ao nome do arquivo e a biblioteca tentará procurar esse nome de arquivo um caminho de fonte definido na biblioteca.

Isto quer dizer que se o caminho for relativo e não absoluto, ao invés dele procurar a partir do local que está o script, ele irá procurar pelo PATH definido nas configurações do GD, então provavelmente ele pensa que http é uma pasta dentro da pasta de fontes do sistema.
Um truque que pode funcionar (note que neste caso é necessário remover a extensão .ttf):
<?php
//Define a pasta do script atual como o caminho das fontes
putenv('GDFONTPATH=' . realpath('.'));

class Certificado
{

    public $nome_para_certificado = '';
    public $modelo_de_certificado = '';

    function __construct($nome)
    {
        $this->nome_para_certificado = $nome;
    }

    public function gerar()
    {
        header("Content-Type: image/jpeg");
        $texto = 'Certificamos que ' . $this->nome_para_certificado . ' participou do Evento nos dias 21, 22 e 23 de setembro de 2014 na Universidade Federal da Paraíba - UFPB';
        $img = imagecreatefromjpeg($this->modelo_de_certificado);
        $preto = imagecolorallocate($img, 0, 0, 0);

        //Quando usar GDFONTPATH= não use a extensão .ttf
        $font_path = 'TravelingTypewriter';

        imagettftext($img, 50, 0, 10, 20, $preto, $font_path, $texto);
        imagejpeg($img);
        imagedestroy($img);
    }
}

Comment: Guilherme, muito obrigado! Suas dicas me ajudaram muito a resolver o problema. Um abraço.
Comment: Acho que agora fiz certo. Confere? Abraço.
Answer: olha este rabisco aqui. Fiz as menores alterações possíveis.
<?php

class Certificado {
    public $nome_para_certificado = '';
    public $modelo_de_certificado = '';

    function __construct($nome, $modelo)
    {
        $this->nome_para_certificado = $nome;
        $this->modelo_de_certificado = $modelo;
    }

    public function gerar()
    {
        header("Content-Type: image/jpeg");
        $texto = 'Certificamos que ' . $this->nome_para_certificado;
        $texto1 = 'participou do Evento nos dias 21, 22 e 23 de setembro de 2014 na';
        $texto2 = 'Universidade Federal da Paraíba - UFPB';
        $img = imagecreatefromjpeg($this->modelo_de_certificado);
        $preto = imagecolorallocate($img, 0, 0, 0);
        $font_path = 'arial.ttf';
        imagettftext($img, 12, 0, 10, 200, $preto, $font_path, $texto);
        imagettftext($img, 12, 0, 10, 230, $preto, $font_path, $texto1);
        imagettftext($img, 12, 0, 10, 250, $preto, $font_path, $texto2);
        // imagestring($img, 5, 300, 400, $texto, $preto);
        imagejpeg($img);
        imagedestroy($img);
    }
}

$imagem = new Certificado("Edilson Samuel", "modelo.jpg");
$imagem->gerar();

?>

Tendo como exemplo esta amostra de imagem:

O Resultado impresso seria algo assim:

Há bastantes probabilidades, de o problema, ter sido gerado porque, não definiste o valor de $modelo_de_certificado como também pode ter sido o mau carregamento da fonte.
Quando surgem problemas como este, podes também procurar por soluções na página do PHP.net
Comment: Oi, Edilson, rejeitei uma sugestão de edição sua especialmente por ter colocado Windows e Ubuntu com marcação de código e também porque [tinha várias outras melhorias](http://pt.stackoverflow.com/q/88652/201) que podiam ser feitas. Se puder, dê uma conferida neste meta post: [Como devemos formatar perguntas e respostas?](http://meta.pt.stackoverflow.com/q/1084/201) . . . Depois apago este comentário que não tem a ver com sua resposta. Saudações!
Comment: Caro Edilson, muito obrigado pela resposta muito bem elaborada e bastante didática. Suas dicas me ajudaram a resolver e o problema era exatamente o path da fonte, como voce alertou. Retirei o http e chamei a fonte a partir do path relativo: $font_path = '../custom/TravelingTypewriter.ttf'. Muito obrigado e parabéns por saber tanto sobre o assunto. Um abraço.
Comment: Obrigado eu, boa sorte.

Escrever em imagem com php


find $\lim_{n \to \infty} \frac{5n^{3} + 3n - 7}{11n^{3}+n}$ and use the definition of the limit to verify

Question: Find $\lim_{n \to \infty} \frac{5n^{3} + 3n - 7}{11n^{3}+n}$ and use the definition of the limit to verify that your answer is correct.
I found that the limit = $\frac{5}{11}$ and verified it as follows:
$$ \biggl| \frac{5n^{3} + 3n - 7}{11n^{3}+n} - \frac{5}{11} \biggr| = \frac{28n-77}{121n^3+11n} < \frac{28n}{121n^3 +11n} = \frac{28}{121n^2 + 11n} < \frac{28}{121n^2} < \frac {28}{84n^2} = \frac{1}{3n^2} = \epsilon$$
Then $\forall \epsilon, n = (3\epsilon)^{1/2} $. Is this a valid verification? Do I need to go any further to justify that this is the limit?
I also do not quite understand why I can continue to produce a chain of less than inequalities and still have the statement be true for any $\epsilon$ ?
Comment: I would say $\;n \color{red}{>} (2\varepsilon)^{1/2}$.
Answer: In general, $\sqrt{3\varepsilon}\notin\mathbb N$. So, you have a problem here.
Note that the inequality$$\left\lvert\frac{5n^3+3n-7}{11n^3+n}-\frac5{11}\right\rvert=\frac{28n-77}{121n^3+11n}$$is trivially false if $n=1$ or $n=2$. Otherwise, it is correct.
You should end the proof with: take $N\in\mathbb N$ such that $\frac1{3N^2}<\varepsilon$. Then$$n\geqslant N\implies\frac1{3n^2}\leqslant\frac1{3N^2}<\varepsilon.$$


Parse String with a Tag like Format

Question: What I need to parse:
[at:1761764]@my_nick_name[/at] my random comment.

What I would like to get:
@my_nick_name my random comment.

I need to do it in an android application. Any suggestion would be appreciated.
Comment: you can get the first index of [ and ] and extract a substring.. and so on
Answer: final String a = "[at:1761764]@my_nick_name[/at] my random comment.";
System.out.println(a.replaceAll("\\[.*?\\]", ""));

This will replace anything between [] (including them) by an empty string, which is equivalent to removing it from the string.
Explanation for the regex:
\\[ -> [ character (you need to escape it since it's a special character in regexes)
.*? -> 0 or more of any character, not greedy
\\] -> ] character
Answer: With this regex:
(^\[\w*:\d*\])|(\[/\w*\])

You select the:
[at:1761764] and [/at]
Later you can remove this ;)
Answer: Simple version:
 String[] parts = input.split("]");
 String firstPart = parts[1];
 firstPart = firstPart.substring(0, firstPart.indexOf("["));
 String secondPart = parts[2];

Regular Expressions are another good option in general KISS.
Comment: IMHO a regex is more KISS than this. But I guess this depends on how comfortable you are with regexes :)
Comment: Yup, that's why your answer is better given the way it is asked. Cheers.
Comment: I think it depends on if capturing of the two groups is needed. Your solution is excellent if it is not.
Comment: Thank you, but I don't see any such capturing requirement in the question.

Parse String with a Tag like Format


How renderable array for an image with style should look like?

Question: I have a custom module that outputs some images. Now, I would like to render them properly.
Currently, I use theme() function, kinda similarly to the way shown here1 and here1:
echo theme('image_style', array(
  'path' => $image['uri'],
  'style_name' => 'product_page_thumbnail',
  'attributes' => array(
    'alt' => $image['ImageAlt'],
    'title' => $image['ImageTitle'],
  )
));

Now, the theme() docs says:

Avoid calling this function directly. It is preferable to replace direct calls to the theme() function with calls to drupal_render() by passing a render array with a #theme key to drupal_render(), which in turn calls theme().

So how would I do that?
I know renderable array for links, it's as simple as:
$link = array(
  '#type'    => 'link',
  '#title'   => $title,
  '#href'    => 'http://example.com',
  '#options' => array('html' => TRUE, 'title' => 'link'),
);

So I want the same, but for images. Somehow I can't find any documented example of it.

1Internal Stack Exchange links, just for reference.
Comment: @Mołot I don't think that there is an image element.. Because theme_image() function itself uses somekind of `$attributes['src'] = file_create_url($variables['path'])` and `return ''` lines...
Comment: `$render = array(
    '#theme' => 'image',
    '#path' => $file->uri,
  );

  return render($render);` ?
Comment: @milkovsky usually the more specific questions are closed as duplicates of more generic ones, or ones with lower scores as duplicates of higher ones. Age does not matter much, unless one question was asked recently. But oh well. I won't lose any rep if this will get closed, or anything. In 2013 your vote might really help me ;)
Comment: I'm in the process of experimenting now, as search failed me miserably, resulting with either direct calls to `theme()` I want to avoid, or with even more crude way of directly concatenating parts of `` tag in tpl file, what I want to avoid even more.
Comment: ha Molot your question is dup now http://drupal.stackexchange.com/questions/68381/render-array-with-images
Comment: @Bala Nope, there guy wants to render link with image in it. I want to render image on it's own.
Comment: what if you create you own element type with hook_element_info()?
Comment: @xurshid29 It will work, but I'm pretty sure there is image element already and I just need to find out how to use it. After all, if theme can work, probably high-level functions can, too.
Comment: @xurshid29 but `render()` is supposed to call `theme()`, so it's OK for `theme()` to return concatenated bits.
Comment: possible duplicate of [Block render array image\_formatter](http://drupal.stackexchange.com/questions/30677/block-render-array-image-formatter)
Answer: There's nothing specific for images, but there is for any theme function. Your old code using theme() would be equivalent to:
$build = array(
  '#theme' => 'image_style',
  '#path' => $image['uri'],
  '#style_name' => 'product_page_thumbnail',
  '#alt' => $image['ImageAlt'],
  '#title' => $image['ImageTitle'],
);

Basically you pass the named variables for the theme function as #-prefixed properties, and the render system will do the rest.
Comment: I believe in Drupal 8, `#path` has now become `#uri`
Comment: Thanks, copy-paste worked, now I just need to move things where they belong :)


Dúvidas sobre banco de dados e Android

Question: Estou desenvolvendo um projeto para a faculdade que se trata de um jogo multiplayer para Android de perguntas e respostas (estilo Perguntados). No desenvolvimento do jogo, preciso criar um banco de dados para armazenar as perguntas, suas respostas, e a opção correta. O jogo acessa esse banco de dados e escolhe uma pergunta aleatória. Como nunca mexi com banco de dados antes, tenho dúvidas sobre como implementar esse banco de dados.
Comment: Obrigado pela ajuda!
Comment: Sua dúvida é exatamente em que parte da implementação?
Comment: Como inserir as perguntas no banco de dados
Comment: Pensando rápido, eu criaria uma tabela para as perguntas (coluna questao e coluna codPergunta), uma tabela para respostas erradas (coluna codQuestao, coluna resposta1, coluna resposta2 e coluna cedRespErrada) e uma tabela para resposta certa (coluna cadQuestao, coluna respostaCerta e coluna codResoCerta)
Comment: Era isso que queria saber?
Comment: Precisa de um editor de banco de dados, não é? Qual você me recomenda?
Comment: O valentina studio é bom?
Comment: Desculpe, eu nunca usei um editor, eu uso comandos SQL mesmo. Se você colocar o banco em um servidor web, a maioria deles utiliza o myPHP admin, você conseguirá utilizar tranquilamente.
Comment: Se você for manter os dados em um banco de dados local você irá usar SQLite, caso queira algo remoto, pesquise sobre WebServices.
Answer: Se o jogo é para Android, você vai precisar usar o banco de dados SQLite e o SQLiteMan para gerenciar os dados do seu banco de forma mais fácil.
Um exemplo simples de como estruturar suas informações seria criar uma tabela com os seguintes campos: _id, pergunta,  opcao_a, opcao_b, opcao_c, opcao_d, resposta
Observações:

Como você disse que o jogo é parecido com o Perguntados, eu assumi que as perguntas são de multipla escolha e há 4 opções de resposta (a,b,c,d) para cada pergunta com apenas uma resposta correta.
O campo _id é utilizado para fazer as consultas e mostrá-las utilizando um CursorAdapter, então caso você não vá utilizar CursorAdapter, não precisa usar o _id.

Sendo assim, um passo-a-passo rápido seria:

Instale o SQLite e o SQLiteMan
Crie uma pasta chamada assets em "caminho do seu porjeto/app/src/main"
Abra o SQLiteMan , crie um arquivo meubanco.db
Execute o seguinte código SQL ( essa tabela é apenas uma sugestão, você pode criar o esquema que achar melhor)
CREATE TABLE perguntas (
    _id INTEGER PRIMARY_KEY AUTOINCREMENT,
    pergunta TEXT,
    opcao_a TEXT,
    opcao_b TEXT,
    opcao_c TEXT,
    opcao_d TEXT,
    resposta TEXT
);

Salve o arquivo na pasta assets

Executando esses passos, você já terá o banco de dados pronto para uso em sua aplicação. Depois viria a parte mais chata: Acesso das informações do banco pela aplicação.
Como você disse que nunca mexeu com bancos de dados, sugiro que você dê uma olhada nos conceitos básicos de Banco de Dados e SQL ( principalmente na parte de palavras-chave)
Agora é só meter a mão na massa e quando você tiver dúvidas mais específicas , sinta-se a vontade para tirar suas dúvidas aqui :-)
Answer: Me parece que nesse caso, há somente duas entidades envolvidas: perguntas e respostas.
A resposta estar correta ou não é apenas um atributo da resposta.
Vou colocar um código SQL "genérico", que você vai precisar adaptar para o SQLite.
CREATE TABLE perguntas (
  id NUMBER,
  pergunta VARCHAR(150)
);
CREATE TABLE respostas (
  id NUMBER,
  resposta VARCHAR(150),
  correta BOOLEAN,
  id_pergunta NUMBER
);

Espero que ajude.

Dúvidas sobre banco de dados e Android


Linux - Limit max bandwidth usage per IP

Question: I have been experiencing DDoS attacks on my web server, with some IPs using more than 50 Mbit/s.
Now if I would like to limit the max bandwidth usage for each unique IP to, lets say, 1 Mbit/s, what would be the best approach?
Comment: It will be very hard to limit inbound bandwidth without discussing it with your ISP.  You should be able to control the outbound bandwidth fully though.
Answer: Try to see documentation about iptables there should be some config about caping bandwith.
But on the other end you should try to configure iptables to ban bad IPs so it will clear the problem and also you will be able to report IPs and time of the attack to authorities.
Comment: I have tried to ban bad IPs and also report them, without luck.
Answer: These links will help you to limit bandwidth consumption per domain in an apache server
http://help.directadmin.com/item.php?id=339
http://svn.apache.org/repos/asf/httpd/sandbox/mod_bw/mod_bw.txt
Comment: Thanks but I need something that works without apache
Answer: You can do something better with iptables.
http://www.zoominternet.net/~lazydog/iptables-tutorial.html#HASHLIMITMATCH
My suggestion would be to stop responding (for X time) to any source IP address that make more then X request in a X period of time. What you will need to set X to will depend on the DDOS attack. You want to block the attackers, but not normal traffic.


Cannot generate cluster reports in OpsCenter.

Question: I cannot generate a cluster report in OpsCenter.  The server and clients are running on CentOS 5.9, 64bit.  Software versions:

opscenter-3.2.2-1
opscenter-agent-3.2.2-1

Here is the error reported in the web browser:

There was an error generating the cluster report: u'/dev/mapper/Staging3SSTables_vol1'

That is the file system on the third cassandra node in this cluster.  That underscore should be a hyphen:

$ ls -la /dev/mapper/Staging3SSTables_vol1
ls: /dev/mapper/Staging3SSTables_vol1: No such file or directory

$ ls -la /dev/mapper/Staging3SSTables-vol1
brw-rw---- 1 root disk 253, 0 Oct  7 13:56 /dev/mapper/Staging3SSTables-vol1

$ df -h /dev/mapper/Staging3SSTables-vol1
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/Staging3SSTables-vol1
                      551G  199M  522G   1% /var/lib/cassandra/data

I don't get this error for the other nodes in the cluster.
What could be causing this?
Here is the full output of the error from opscenterd.log:

2013-10-10 08:48:37-0700 [] ERROR: There was an error while generating a cluster report. Traceback (most recent call last):
          File "/usr/lib/python2.6/site-packages/opscenterd/StatsReporter.py", line 132, in generateReport
          File "/usr/share/opscenter/lib/py-redhat/2.6/shared/amd64/twisted/internet/defer.py", line 1018, in _inlineCallbacks
            result = result.throwExceptionIntoGenerator(g)
          File "/usr/share/opscenter/lib/py-redhat/2.6/shared/amd64/twisted/python/failure.py", line 349, in throwExceptionIntoGenerator
            return g.throw(self.type, self.value, self.tb)
          File "/usr/lib/python2.6/site-packages/opscenterd/StatsReporter.py", line 148, in createClusterReport
          File "/usr/share/opscenter/lib/py-redhat/2.6/shared/amd64/twisted/internet/defer.py", line 1018, in _inlineCallbacks
            result = result.throwExceptionIntoGenerator(g)
          File "/usr/share/opscenter/lib/py-redhat/2.6/shared/amd64/twisted/python/failure.py", line 349, in throwExceptionIntoGenerator
            return g.throw(self.type, self.value, self.tb)
          File "/usr/lib/python2.6/site-packages/opscenterd/StatsReporter.py", line 109, in format_node
          File "/usr/share/opscenter/lib/py-redhat/2.6/shared/amd64/twisted/internet/defer.py", line 542, in _runCallbacks
            current.result = callback(current.result, *args, **kw)
          File "/usr/lib/python2.6/site-packages/opscenterd/Cluster.py", line 484, in sumDiskSpace
        KeyError: u'/dev/mapper/Staging3SSTables_vol1'

2013-10-10 08:48:37-0700 [] ERROR: Error generating the cluster report: Traceback (most recent call last):
          File "/usr/lib/python2.6/site-packages/opscenterd/WebServer.py", line 2243, in ClusterReportController
        KeyError: u'/dev/mapper/Staging3SSTables_vol1'
Answer: What's happening here is opscenterd is looping over partitions containing any configured data directories from cassandra.yaml, and comparing those to the output of df --print-type --no-sync --block-size=1G --local.  OpsCenter seems to think that /dev/mapper/Staging3SSTables_vol1 is one of those partitions, which is obviously wrong.
We do some escaping of special characters in partition names, but - is in the list of allowed, non-escaped characters.  So unless that dash isn't really a dash, or there is simply a bug in OpsCenter code, that shouldn't be causing any issues.

I don't get this error for the other nodes in the cluster.

Once this error occurs, the cluster report will stop processing.  So if the offending node is the first to be processed, the other nodes wouldn't have a chance to succeed or fail.
Comment: Thank you very much for your response, although I'm just now seeing it a year later.  This problem disappeared after upgrading OpsCenter sometime after noticing the problem.  I don't know what version brought the fix, but things are working fine now.


What does '_IO(...)' mean in C headers in Linux?

Question: I have a Linux standard header file e.g.
/usr/src/linux-headers-3.2.0-35/include/linux/usbdevice_fs.h

which contain define statements as follows:
#define USBDEVFS_SUBMITURB32       _IOR('U', 10, struct usbdevfs_urb32)
#define USBDEVFS_DISCARDURB        _IO('U', 11)
#define USBDEVFS_REAPURB           _IOW('U', 12, void *)

What does '_IOR', '_IO' and '_IOW' mean? What value is actually given e.g. to USBDEVFS_DISCARDURB?
Comment: See also duplicate question http://stackoverflow.com/questions/22496123/what-is-the-meaning-of-this-macro-iormy-macig-0-int/40465177#40465177
Answer: They define ioctl numbers, based on ioctl function and input parameters.
The are defined in kernel, in include/asm-generic/ioctl.h.
You need to include <linux/ioctl.h> (or linux/asm-generic/ioctl.h) in your program. Before including
/usr/src/linux-headers-3.2.0-35/include/linux/usbdevice_fs.h
You can't "precompile" this values (e.g. USBDEVFS_DISCARDURB), because they can be different on other platforms. For example, you are developing your code on plain old x86, but then someone will try to use it on x86_64/arm/mips/etc. So you should always include kernel's ioctl.h to make sure, you are using right values.
Comment: The IOCTLs are supposed to stay stable from version to version because they represent a user ABI.  Old binaries must work on new kernels.  However the IOCTL values differ on various platforms and that is why one should use the values from the headers: to stay portable across many platforms.
Comment: @Alex, but be beware, that numerical value possibly can be changed in next kernel version (e.g. sizeof struct usbdevfs_urb32 will be changed). You'd better always include this two files and use defined name.
Comment: Now we are getting close. Including this particular header file I was able to compute the numerical value of the `_IO` construct.
Comment: @goertzenator, yes, you are right in general. I was speaking as embedded developer. There are lots of strange things can happen during active development. I have seen how IOCTL values changed on the same kernel version, but yes, it was rather exceptional case. I'll update the answer.
Answer: These are also macros defined elsewhere.
In general if you want to see your code after pre-processor has been computed use
gcc -E foo.c

this will output your code pre-processed
For example:
foo.c
#define FORTY_TWO 42

int main(void)
{
  int foo = FORTY_TWO;
}

will give you with gcc -E foo.c:
int main(void)
{
  int foo = 42;
}

Comment: Daft question but can't you just add a `USBDEVFS_DISCARDURB` to your source file then preprocess it?  Your change doesn't have to compile; you can delete it as soon as you've seen the preprocessor output.
Comment: I cannot see the variable `USBDEVFS_DISCARDURB` in the output of `gcc -E /usr/src/linux-headers-3.2.0-35/include/linux/usbdevice_fs.h` anymore. How can I see the actual value? Or how can I find out where those macros are defined?
Comment: If you want to also see the macro definitions and the `#include` statements, add the `-dDI` flag. To prevent macro expansion, make it `-dDNI`
Comment: @Alex See my edit; you wouldn't see the macro USBDEVFS_DISCARDURB because `gcc -E` has preprocessed it and replaced it in-place by its value. `gcc -E` is also not supposed to be used on a header file but on a source file as stated in my answer.
Comment: @Eregrith: I understand what `gcc -E` is doing, but it does not answer my question. I still need to find out the value of the variable `USBDEVFS_DISCARDURB` for example, or to find the definition of the `_IO` command (to derive the value myself).
Comment: @simonc: Your suggestion worked, but did not answer my question. It turned out that `USBDEVFS_DISCARDURB=_IO('U', 20)`! But what IS `_IO('U', 20)`? I am expecting an int value.
Comment: Then it proves that `_IO('U', 20)` is not a macro but indeed a function
Comment: @Eregrith: Interesting subtlety, but it still does not answer my  question. I need a numerical value (an int) that this variable stands for.
Comment: If you expect an `int` and just need its value why not simply `printf("%i\n", _IO('U', 20));`?
Comment: @Eregrith: Because I have to compile the code. I get a lot of errors, and it is just a header. But I guess I have no choice to write some c code which imports the header code and try to sort out all of the errors...


Batch file code to find and rename all files ending in a space?

Question: We host Macintosh files on our Windows 2008 servers.  They have files like
somegraphic.eps
._somegraphics.eps (hidden)

Many times our users will add non-standard characters to the files, like bullets and spaces at the end of the file names.  It allows them to add the characters, but it won't let them alter the file names once they click enter.
Two questions:

In a batch file, how could you get a list of all files ending in a space?
In a batch file, how could you mass rename all files removing unwanted characters?

For that matter:

How could you get a list of all files on a system, their modified times, and in an XML or easily data import format?

Discussion:
I try to rename with a dir/x filename, but the hidden properties seem to stop that from working.
Usually, I do a dir/b/s to get a full directory search in a bare format, but it doesn't include modified times.
Comment: I think it's probably beyond the capabilities of CMD batch files, but would probably be relatively straightforward in Powershell. Would that be an option for you?
Comment: Can you create a file with a space at the end on demand?
Answer: Create a file with a space at the end:
echo Foo >  "\\?\c:\rcs\boo.txt "

List files on system in a batch file with modified date and bare listing:
for /f "tokens=*" %%A in ('dir /s/b %target%') do @echo %%~tA,"%%~A"

For example, a directory with three files including "boo.txt " looks like:
, "C:\rcs\boo.txt "
02/03/2011 17:48, "C:\rcs\foo1.txt"
02/03/2011 17:47, "C:\rcs\foo2.txt"

Note how the file date is missing. This could be your clue that the file name is illegal.
Take a look at filelist.exe from  [http://www.jam-software.com/freeware/].
This program creates an expanded listing (many more data points) but doesnt balk at attributes like date.
Deleting is easy, renaming is harder.
The following tool renamed "boo.txt " to boo.txt
http://wren.adoxa.cjb.net
wren.exe boo~1.txt boo.txt

took care of the filename.
Note: Wren appears to have a 16 and 32 bit versions - I used the 16 bit one to perform the rename, and was constrained to renaming it to a 8.3 filename.  You should be able to work around this.


Admin menu disappearing

Question: I'm running Drupal 7.54 and for some strange reason my admin menu on top disappears. This happens sporadically, no telling what's going to happen next. I've done some searching and found
$conf['admin_menu_cache_client'] = FALSE;

I added this line of code to the settings.php file and that didn't help.
I was wondering if anyone else had experienced the same problem and tried any solutions.
below is the javascript error
GET https://www.nokidhungry.org/modules/comment/comment.css?otg3j2
smiah:18 Uncaught TypeError: Cannot read property 'prototype' of undefined
    at HTMLDocument.<anonymous> (js_lfuW81Xw_ijrPfg5E_XWjUDemAzqGwWRZunpwj_BL20.js:1032)
    at c (jquery.min.js:4)
    at Object.fireWith [as resolveWith] (jquery.min.js:4)
    at Function.ready (jquery.min.js:4)
    at HTMLDocument.q (jquery.min.js:4)
    at HTMLDocument.nrWrapper (smiah:18)
(anonymous) @ js_lfuW81Xw_ijrPfg5E_XWjUDemAzqGwWRZunpwj_BL20.js:1032
c @ jquery.min.js:4
fireWith @ jquery.min.js:4
ready @ jquery.min.js:4
q @ jquery.min.js:4
nrWrapper @ smiah:18

I think the error below is causing the issue and I don't know how to get rid of it.
Comment: It's very possibly a JavaScript error on your page when it disappears. Next time it happens, open a console and look for an error.
Comment: I have a  X Failed to load resource: the server responded with a status code of 403 comment.css
Comment: CSS won't cause that issue. JS issues are the only thing that would cause it.
Comment: Uncaught TypeError: Cannot read property 'prototype' of undefined ?
Comment: Yep, that's it. Can't really debug it easily from here though. Maybe post the line of code that it refers to, and the previous few lines to that.
Comment: @Jaypan I posted the error in the question
Comment: Looks like your problem is on line 18 of smiah
Comment: @Jaypan How would I find the smiah file, it's not stored at a location. It's a system user. I'm not sure how to access that file to fix the error.
Comment: Access the page and view the HTML sources
Comment: I just did. It's a large javascript file that is being called after the viewport
Comment: I'm wondering what this file is used for and if I need it or if it'll break the website if I try to take it out so I can get my menu back.
Comment: No idea what it's used for - that's something you'd have to research yourself as the site owner.
Answer: Here's a checklist of things to look at:

Drupal simply concatenates files during aggregation. Malformed scripts may cause the entire thing to blow up. Disable aggregation first to see the code in plain so it's easier to debug.
Aggregation can also lead to some weird issues together with caching. Ensure that you've refreshed the cache for both Drupal, browser and any external file systems (i.e. S3) to ensure that you're working with updated code and content.
Malformed CSS, believe it or not, can also cause aggregation to blow up. Chrome does not show any error of this happening. However, Firefox prints a warning if it does. Debug in Firefox to see some errors not shown by Chrome.
If you're using S3 for storage, ensure that all of your resources are present. Sometimes, the file may not be accessible from S3, fail to upload to S3, or just be missing (i.e. deleted accidentally).
You already mentioned disabling admin menu caching. That has solved this problem for me in two projects.
Clear all caches (drush cc all). Always worked. :D
Comment: This keeps happening. I do drush cc all, it goes work but sometimes it doesn't -- ts very random. I want to get rid of the javascript error which I think is causing the issue.

Admin menu disappearing


VAPI problems with GTK+ 3

Question: I'm trying to compile some Vala on ArchLinux, and when I try to include the package gtk+-3.0, it seems GDK and GTK+ 2.0 are being included as well; valac --pkg gtk+-3.0 test.vala gives the following errors:
gdk-2.0.vapi:8.3-8.28: error: `Gdk.Selection' already contains a definition for `convert'
    public static void convert (Gdk.Window requestor, Gdk.Atom selection,     Gdk.Atom target, uint32 time_);
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
gdk-3.0.vapi:8.3-8.28: note: previous definition of `convert' was here
    public static void convert (Gdk.Window requestor, Gdk.Atom selection, Gdk.Atom target, uint32 time_);
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
gdk-2.0.vapi:10.3-10.44: error: `Gdk.Selection' already contains a definition for `owner_get'
    public static unowned Gdk.Window owner_get (Gdk.Atom selection);
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
gdk-3.0.vapi:10.3-10.44: note: previous definition of `owner_get' was here
    public static unowned Gdk.Window owner_get (Gdk.Atom selection);
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
--snip--
Compilation failed: 942 error(s), 0 warning(s)

Is there some way of specifying not to include gtk+-2.0 or of making valac ignore these errors?
Answer: What version of vala? I fear it must be something messed up in your distribution. Can you paste the contents of /usr/share/.../gtk+-3.0.deps?
Also try using valac --verbose so that you see all the vapis being loaded. For each vapi, look the relative .deps file and check whether there is a gdk-2.0 lying around.
Comment: It's Vala 0.12.1. Nothing looks unusual in /usr/share/vala-0.12/vapi/gtk+-3.0.deps:
    `gio-2.0
    atk
    cairo
    gdk-pixbuf-2.0
    gdk-3.0
    pango`
Answer: Without having access to your source code or build environment (assuming you're not merely typing the valac command directly), it's tough to troubleshoot this.  Using a dead-simple test.vala with Vala 0.12.1, it builds fine on my system.
In the past I've seen bad Vala environments due to old versions of Vala (and its support files) lurking around.  I recommend uninstalling Vala 0.12.1 completely, then going through /usr for any remnants.  An easy and thorough way (although time-consuming) is to do this:
$ find /usr -name "*vala*"
$ find /usr -name "*.vapi"

Remove anything that's obviously not part of another package.  (Note that some packages install their own VAPIs, like libgee.)  Then reinstall Vala 0.12.1 and see if the problem persists.
Comment: I recently transitioned a project from GTK+2 to GTK+3 and had similar problems throughout the process.  The reason: some of the other libraries our project depended on (such as libunique and WebKit) relied on GTK+2, which causes the conflict.  Go through all the packages your app relies on and see if any of them depend on GTK+2.  (Easiest way is to check their .deps file, i.e. unique-1.0.deps, which sits alongside their VAPI.)  Then, you have to check if any of *those* packages rely on GTK+2, and so on.  My guess is you'll find the culprit there.
Comment: When I tried this, vala left behind some vapis in /usr/share/vala (as opposed to /u/s/vala-0.12, which got removed). I deleted these and reinstalled vala, but the problem persists. I also tried vala from Git, version 0.14, but it still does it. Argh.

VAPI problems with GTK+ 3


Lower bound on the variance of the maximum of random variables.

Question: I'm trying to figure out a lower bound on the variance of the follow:
$\max_i(x_1,x_2,...x_m)$. Where $x_i, i \in m$ are independent random variables that shares the same variance $\sigma_x$.
I know we can upper bound the above quantity to be: $\text{Var}[max_i(x_1,x_2,...x_m)] \leq \sum^m_i \text{Var}[x_i] $, but what about a lower bound? Also, is there a guarantee that this is the tightest lower bound?
Also, can we find a bound for $\text{Var}[max_i(a_1,a_2,...a_m),max_i(b_1,b_2,...b_m),...,max_i(z_1,z_2,...z_m)] $
Comment: For $\{X_i\}$ i.i.d. with $P[X_i=1]=P[X_i=-1]=1/2$ we have $Var(X_i)=1$ for all $i$, but $Var(\max[X_1, ..., X_n]) = 1 - (1 - (1/2)^{n-1})^2 \rightarrow 0$ as $n\rightarrow\infty$.
Comment: @xsari3x it is just the calculation that $\max[X_1, ..., X_n] = -1 w.p. (1/2)^n$. and 1 otherwise; to add to this discussion, max of $n$ iid standard gaussians has a variance that decays of order 1/(1+log(n)); this answer explains this phenomenon much better than I can, and also has a lower bound for this specific instance https://stats.stackexchange.com/questions/229073/variance-of-maximum-of-gaussian-random-variables
Comment: Just a suggestion : with markov : $Var(max) \geq a^2 \Big(1 - P(x_1 \leq a + E(max))^n\Big)$ for all $a > 0$.
Comment: Could it be the variance of one variable?
Comment: @herbsteinberg I was thinking it could the variance of the minimum RV and because they are equal, then it's $\sigma_x$ but not sure about this. I'm also looking in https://www.mit.edu/~dbertsim/papers/MomentProblems/orderstatistics.pdf
Comment: @Michael this is from extreme value theory? I don't recall it has a generic form for any distribution. As far as I know for Normal dist the the max as $m \to \inf$ is a standard gumbel.
Comment: @E-A It seems a good lead! Thanks!!
Comment: @jvc I think it should be $>$
Answer: Unfortunately, for $m\ge 2$, there is no lower bound in terms of the variances of $X_i$ (except the trivial one).
@Michael explained that the variance may vanish as $m\to\infty$, but this can happen even for fixed $m\ge 2$.  Indeed, let $\mathrm{P}(X_i=1/\sqrt{p(1-p)}) = 1- \mathrm{P}(X_i=0) = p$ so that $\mathrm{Var}(X_i) = 1$. Then,
$$
\mathrm{P}\left(\max_{1\le i\le m} X_i=\frac{1}{\sqrt{p(1-p)}}\right) = 1- \mathrm{P}\left(\max_{1\le i\le m} X_i=0\right)= 1 - p^m,
$$
so
$$
\mathrm{Var}\left(\max_{1\le i\le m} X_i\right) = \frac{p^m(1-p^m)}{p(1-p)}\to 0, p\to 0+.
$$
Under the assumption that the variables are bounded by some $C$, it may be possible to get a lower bound depending on $C$ (and $m$).


Subalgebra condition in Engel's theorem

Question: An equivalent version of Engel's theorem says that

Let $L$ be a subalgebra of $\mathfrak{gl}(V)$, $V$ finite dimensional. If $L$ consists of nilpotent endomorphisms and $V\ne 0$, then there exists a nonzero $v\in V$ for which $L v = 0$.

Why do we need this condition that $\rho:L\hookrightarrow \mathfrak{gl}(V)$? If this representation is not faithful can't we quotient out the kernel $\overline{\rho}:L/\ker\rho\to \mathfrak{gl}(V)$ and conclude that $(L/\ker\rho)\cdot v = 0$ and therefore $L\cdot v = 0$?
Answer: You're completely right, maybe it's a matter of taste.
One benefit of the formulation you quote is that it is very elementary: it doesn't speak about abstract representations of Lie algebras, but only about spaces of nilpotent matrices closed under commutator - pure linear algebra, if you want. However, as far as I remember, for the usual inductive proof one needs to change both ${\mathfrak g}$ and $V$ and consider representations which are not necessarily faithful, so your version of the theorem fits that induction better than the quoted one, and I'd therefore would prefer it, too.
It's similar for Lie's Theorem: Before proving the representation theoretic version, one shows that solvable subalgebras of matrices admit common eigenvectors (over an algebraically closed field) and deduces the other formulations afterwards.

Subalgebra condition in Engel's theorem


Submit New Item Form and Open the same item for editing

Question: We have a powerapps SharePoint List form where there is a button in the New Item Form.
On Click of said button, the item needs to be saved and should redirect to the Edit item form for the same item.
We tried IF(SubmitForm(NewForm),Navigate(EditForm)) in the button click properties.
On clicking the button the item got saved. But instead of opening the Edit form of the saved item, it is opening the Edit Form of whatever item got edited last in the list.
Please help
Answer: Try this:

Connect your Sharepoint list to the Form
Submit Button:

OnSelect: SubmitForm(<FormName>)

Form properties:

OnSuccess: Set(varLastSubmit, <FormName>.LastSubmit)
Item: If(!IsBlank(varLastSubmit),varLastSubmit)

Caveat:

This solution assumes you ALWAYS want to ONLY edit the last submitted record
To get "out of the loop", you'll need to hit the Reset button (NewForm(<FormName>)

  - If you delete the record you're currently working on, this will throw an error "Item not found" and you'll need to hit the Reset button as well


Set jQuery slider value dynamically

Question: How can I set slider value dynamically?
Here is my current code:
<code> $( "#slider-range-max" ).slider({
  range: "max",
  min: 1,
  max:61,

  step: 1,
  slide: function( event, ui ) {

    var val = ui.value;
   if(val > 10){

     ui.value = ui.value + 3;

  //   $(this).slider('option','max',500);

}
</code>
And after that this value change only once time (value bounce from 10 to 13 and to 14,15,16... after) but i need 10,13,16,19,etc.
what am i doing wrond?
When I try ui.value = ui.value*ui.value it works excellent (121, 144, 169, 196, etc.)
Answer: Haven't you forget to close your if statement whith "}" ?
Edit :
Have you tried something like this :
<code>$("#slider").slider('value',50);
</code>
Comment: No, i've just cut part of code.
And when I place ui.value = ui.value * ui.value instead of ui.value = ui.value + 3; it give me (121, 144, 169, 196, etc.) Dunno why ui.value + 3 won't work...
Answer: The way Pak suggested will recall the slider constructor, which will not be smooth.
The correct way, according to jQuery UI Docs , is:
<code>$("#slider").slider('option','value',50);
</code>

Set jQuery slider value dynamically


Singleton class and using inheritance

Question: I have am working on a web application that makes use of helper classes. These classes hold functions to various operation such as form handling.
Sometimes I need these classes at more than one spot in my application, The way I do it now is to make a new Object. I can't pass the variable, this will be too much work.
I was wondering of using singleton classes for this. This way I am sure only one instance is running at a time.
My question however is when I use this pattern, should I make a singleton class for all the objects, this would b a lot of code replication.
Could I instead make a super class of superHelper, which is a singleton class, and then let every helper extend it.
Would this sort of set up work, or is there another alternative?
And if it works, does someone have any suggestions on how to code such a superHelper class.
Thank you guys
Comment: Do your helper classes hold any state, or could their methods be static?
Comment: Some hold stated, and some can be used as static, i don't think this comment helped a lot
Answer:
I can't pass the variable, this will be too much work.

Are you sure though? People tend to overestimate the effort of passing around dependencies. If you do it in the constructor, it's usually fairly simple to do.
That said, you can put shared functionality in the global scope, in different ways in php. The simplest is to use a global function. Eg. a function that doesn't belong to any class. Another option is to use a static class method. These two a very similar; except for their syntax, they essentially have the same properties. A slightly looser coupled solution is to put the functionality as a method on an (abstract) base class, that your concrete class extends from. This shares the functionality between all child classes.
Common for the above-mentioned solutions is that they have a compile time coupling. You can't change the dependency at run time, which makes your application rather rigid. Their main benefit is the low level of complexity they carry.
If you want a looser coupled application, you can try to replace the hard dependency with a variable, to give a level of indirection. The simples is to create an object and make this shared globally throughout the application. There are a number of ways to do this in PHP, such as a singleton or simply a variable in the global scope (You can access this with the global keyword, or through the $GLOBALS array).
While global variables offer a level of indirection, they also tend to introduce a lot of complexity, since they make it very hard to figure out which parts of the application that depends on each other. For this reason, they are often avoided by experienced programmers. This is especially true if the variable has state; The problem is less prevalent if the shared object is stateless.
The only way to avoid the perils of global variables, is to use local variables instead. Eg. To pass the dependencies around. This can be a bit of a hassle, but in my experience it's often not as big a problem as it's made out to be. At least, the benefits often outweigh the problems. That said, there are techniques to easy the pain; Notably dependency injection containers, which are automatic factories that take care of all the wiring for you. They come with their own level of complexity though, but for larger applications they can certainly be a good solution.
Comment: Thank you for the response, i understand the upside and downside for each of point. I will try to just pass the helpers around in local variables.
Answer: Look into the factory pattern and dependency injection.
http://www.potstuck.com/2009/01/08/php-dependency-injection/
Answer: You can't extend a singleton class. Remember in singleton class we make the constructor private so if a constructor is private than how could you extend this class? We all know what we create an object of a class we call its constructor and in child class constructor it implicitly called the parent constructor. So in this scenario a private constructor can't be called in the child class.
Answer: While sometimes necessary, singletons are evil (because they're global state). Try to avoid them if you can help it.
EDIT: If you can't avoid singletons, at least parameterise the reference to that state. In other words, in a class, pass in the singleton to its constructor or those methods that use the singleton.
Simply making references all over your codebase to your singleton will compromise your ability to test classes in isolation.
If your singleton's stateful, your tests will suddenly become stateful, and your tests can start "cascade failing" because their preconditions become corrupted by earlier tests failing.
Comment: I did not downvote. I think all responses are good concerning this, as I am not sure to use the singleton patern in the first place.

Singleton class and using inheritance


Drupal Add Javascript type=text/javascript

Question: I am trying to add javascript to my page and use type="text/javascript" however when I include the following it just encloses it in script tags. How can I fix this? Also, how can I add the type="text/javascript to external files (see the second example)
drupal_add_js("$(document).ready(function() {
    // Infinite Ajax Scroll configuration
    jQuery.ias({
        container : '#itemcontainer',
        item: '.dealstable',
        pagination: '.nav',
        next: '.nav a',
    });
    });",'inline');

Here is the second example:
drupal_add_js('http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js','external');

UPDATE:
As suggested by the comments I tried the following:
$js = "(function($) {
    jQuery.ias({
        container : '#itemcontainer',
        item: '.dealstable',
        pagination: '.nav',
        next: '.nav a',
    });
    };
})
(jQuery)";
drupal_add_js($js, array('type' => 'inline','scope'=>'footer'));

But that resulted in the following HTML:

Comment: text/javascript is the default type, though it appears Drupal core adds that by default anyway in [drupal_get_js](https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_get_js/7) '#attributes' => array(
      'type' => 'text/javascript',
    ),
Answer: you can use
$js = "(function($) {

    };
})
(jQuery)";
drupal_add_js($js, array('type' => 'inline','scope'=>'footer'));

OR
drupal_add_js("(function($) {
$(document).ready(function(){
    $('.mobile-navigation').click(function(){

     });
    });
})
(jQuery)","inline");

OR
drupal_add_js('sites/all/themes/dawn/js/skrollr.js', array('scope'=>'footer'));
drupal_add_js(drupal_get_path('module', 'module name') . '/js/name.js');

Comment: Please format your code as code. Also, a bit of description why it works and code by OP does not would be helpful.
Comment: That didn't seem to work. I have updated my original edit to show the result.


Node.js script hangs on require, but works fine in the REPL

Question: I'm running node.js on Ubuntu 18.04 LTS. I appear to be getting different behaviour using require depending on whether I use it in the REPL or in a script. Specifically, I used npm to download lightstreamer-client-node. Now, I open up a terminal and do the following:
colin@colin-XPS-15-9550:~$ node
> var x = require('lightstreamer-client-node')

This works perfectly.
Now I want to use this package in a script. I create a text file node_test.js containing just the line:
var x = require('lightstreamer-client-node')

and I open up a terminal and run the command:
colin@colin-XPS-15-9550:~$ node /home/colin/node_test.js

This hangs indefinitely on a blinking cursor.
I'm brand new to node.js and JavaScript so perhaps this is expected behaviour. I've done some reading about the require function and can't seem to find an explanation for it. Note that if I replace lightstreamer-client-node with some other node module, e.g. safe-buffer, then everything works fine, whether I use REPL or script.
Comment: what happens if you put a second line ... like `console.log('hello world')` after the require statement?
Comment: Have you tried putting more code in your file? I was able to `require` it, and with the require being the only thing in the file it did hang like you said. However, I put a bunch of random print statements in. They printed fine, but then hung. I then added `process.exit(0);` to the end of the script and it exited normally. Perhaps the hang is expected of that specific package.
Comment: so, it's not the require that is preventing the node process from ending - it's something in that library that does that - possibly for a good reason - who knows, but you can safely write code that uses that library
Comment: @JaromandaX Thanks for responding. I just placed `console.log('message 1')` before the `require` and `console.log('message 2')` after the `require`. Both statements printed, then the blinking cursor.
Comment: @tycrek I just duplicated that on my machine. Thanks for responding. Perhaps it is supposed to happen. LightStreamer is for establishing a bi-directional connection with a server, so I guess it sort of makes sense? I'm brand new to this area of programming, so my question is perhaps a bit naive.
Comment: @JaromandaX Awesome thanks. My question may have been naive.
Comment: It's not a naive question at all
Answer: The process seems to hang because the library lightstreamer-client installs a timer, with the function setInterval, for its internal activities, and nodejs doesn't allow a graceful shutdown when there are active tasks. So the only way to terminate the script is by using the function process.exit.


change of basis and inverse in tensor notation

Question: I'm trying to study tensors from several textbooks. I would like it
if someone could confirm my understanding of a particular easy example.
It is from Itskov, Tensor Algebra and Tensor Analysis for Engineers, 3rd edition.
$\mathbf{e}_i$ is an orthonormal basis, and $\mathbf{g}_i$ is some other basis.
$\mathbf{e}^i$ and $\mathbf{g}^i$ are the respective dual bases.
Itskov expresses the "primal" bases in terms of each other (eq. 1.16):

$\mathbf{e}_i = \alpha_i^j \, \mathbf{g}_j    \quad\text{and}\quad  \mathbf{g}_i = \beta_i^j \,\mathbf{e}_j$

Ok, no problem so far.
Itskov then says ``Let further'' (eq. 1.19):

$\mathbf{g}^i = \alpha^i_{\,j} \, \mathbf{e}^j$

My question:  I believe that this $\alpha^i_{\,j}$ is a different thing than the $\alpha_i^j$ in 1.16;
I think I should regard these as matrix inverses of each other.
However the notation almost suggests that they could be the same numbers, just indexed differently.
One possible little clue, the subscript $j$ in 1.19 is displaced slightly (which I tried to reproduce here).
Answer: Using your notation, suppose $g^{i} = \sum_{j}\beta^{i}_{j}e^{j}$.
Then $$\beta^{i}_{j} = g^{i}(e_{j}) = g^{i}(\sum_{k}\alpha^{k}_{j}g_{k}) = \sum_{k}\alpha^{k}_{j}\cdot g^{i}(g_{k}) = \alpha_{j}^{i}$$
So $\beta^{i}_{j} = \alpha_{j}^{i}$
Comment: 1) I'm guessing the first step $B_j^i = g^i(e_j)$ is obtained by multiplying on the right with $e_j$.  The rest I follow.
Comment: $\beta_{i}^{j} = g^{i}(e_{j}) $ is obtained by applying the linear functional $g^{i}$ to the vector $e_{j}$
Comment: Initially I felt that the $a_i^j$ is like a matrix, and thus the two equations are analogous to matrix vector equations $e = A g$ and $g = A e$, with $A$ being the matrix corresponding to $a_i^j$.  This makes no sense, so it seemed that $a_i^j$ must have different meaning in the two equations.  However I now think the resolution is that $a_i^j$ is indeed the same in both (thanks to WLOG's answer), but the difference is absorbed in $g_i$ versus  $g^i$.


Find the derivative of the function $(1 + 5x)e^{-5x}$

Question: We have to find the derivative of the function $y=(1+5x)e^{-5x}$. The answer is $-25xe^{-5x}$. If you could explain/show how to do this, that would be very helpful. Thanks.
Comment: It is a combination of the product rule, and the composition rule: $(fog)'(x)=f'(g(x))g'(x)$.
Answer: Hint:
Use the Product Rule: $$y=f(x)g(x), \space y' = f(x)g'(x) + g(x)f'(x)$$
Where $$f(x) = 1+5x, \space g(x) = e^{-5x}$$
$$\implies y' = (1+5x) \cdot (e^{-5x})' + e^{-5x} \cdot (1+5x)'$$
For the differential of $g(x) = e^{-5x}$, use Chain Rule:
$$((f\circ g)x)' = f'(g(x))\cdot g'(x)$$
When differentiating the exponential function $e^x$, you have to differentiate '$e^x$' as well as the function in the power. So the differential of $e^x$ is actually $e^x \cdot(x)'$ but since the differential of $x$ is $1$, $\frac{dy}{dx} e^x = e^x$. For $e^{-5x}$ however, the function in the power $-5x$, has to be differentiated as well. Therefore, using the Chain Rule, $f'(g(x)) = (e^{-5x})'$ which is just ($e^{-5x}$) and $g'(x) = (-5x)'$ which is just $-5$.
$$\therefore (e^{-5x})' = (e^{-5x})' \cdot (-5x)' = e^{-5x} \cdot -5 = -5e^{-5x}$$
Comment: @SujaanKunalan Thanks :)
Comment: can you please explain this further? Thank you.
Comment: @kpatel20 I explained in the answer..Is that any better?
Comment: the answer I have is actually -25e^−5x. Is your answer just simplified? Thank you and sorry for the repeated questions.
Comment: Well that's just part of the answer..I left the product rule part (the first part of the answer) for you to do...The Chain Rule part was simply to explain finding the derivative of $e^{-5x}$. Plug $-5e^{-5x}$ into the $y'$ equation, calculate the other necessary derivative and simplify and you will get $-25e^{-5x}$. And its not a problem.
Answer: product rule d(uv)/dx = u'v+uv'
<code>y' = 5*e^(-5x)+-5*e^(-5x)*(1+5x)
</code>
Answer: First,let $y=(1+5x)e^{-5x}$. notice that $(lny)'=\frac{1}{y}*y'$.
$$ln[(1+5x)e^{-5x}]=ln(1+5x)+ln(e^{-5x})=ln(1+5x)-5x$$
Then we get$$\{ln[(1+5x)e^{-5x}]\}'=\frac{5}{1+5x}-5=\frac{1}{(1+5x)e^{-5x}}*y'$$
$y'$ is easy to get.


Why jsHint says "'setInterval' is not defined"

Question: When I check my *.js with jshint, it's show an error on this part:
function updateStatistic(interval) {
    return setInterval(function () {
        exports.getStatistics();
    }, interval);
}

The message is: 'setInterval' is not defined. But why?
Answer: Alternatively, you could just have JSHint assume a browser:
/*jshint browser: true */

(Reference)
Answer: You have to tell jshint which object and/or functions are considered global in the jshint tag comment at the top of your code.  jsHint doesn't assume any, since they vary depending on the precise environment in which the code is run.
The approach I use is to tell jshint that the window object itself is global (and a few others) with the following, and an ES5 strict-mode directive thrown in too:
/*global $ document window localStorage */
"use strict";

Silencing the warning about setInterval then requires prefixing that function call with window. - I like having to explicitly tag the global functions I'm using so I don't consider this a disadvantage.
Answer: if you don't want to adjust your settings in jshint, there is nothing wrong with simply referencing it through the window object, like so:
function updateStatistic(interval) {
   return window.setInterval(function () {
       exports.getStatistics();
   }, interval);
}

That will also remove the jshint warning, as it is defined within that context.


Why China don't have their cricket team?

Question: as we can see there are limited teams which are playing cricket, and these teams have big names in the world, but why china don't have their cricket team for international?
Answer: Your question is based on a false premise: China does have a cricket team which is affiliated with the ICC and has competed in various tournaments.


apache2: mpm configuration

Question: After several nagios messages like "CRITICAL - load average: 135.12, 92.20, 44.09" and oom-killer, I checked the configuration again and again, with different settings, but no success.
The only work-around which seems to help on the ubuntu box, is this cleaner cronjob:
[ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete
Reading the oom-killer info, tells me about apache2 to be the bad (parent) process. There is only few traffic on this vserver and hardly any peaks.

lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                1
free -m
Mem:          2003        835       1168          0         18        381
-/+ buffers/cache:        435       1568
Swap:         1019        129        890

apache2.conf mpm
<IfModule mpm_prefork_module>
    StartServers          2
    MinSpareServers       2
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   10000
</IfModule>
<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    KeepAliveTimeout     15
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          100
    MaxRequestsPerChild 10000
</IfModule>
<IfModule mpm_event_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          100
    MaxRequestsPerChild 10000
</IfModule>

Isn't there something like a mysql_tuner.sh for apache or a useful example for a similar vps?
THX
Answer: You are over allocating on memory - OOM means "Out of memory" - the high load averages will be a result of the machine swapping.
You don't need a tuning script to know what appropriate settings to use. Launch Apache, then look at the RAM usage of a single thread. Typically, for a PHP app, expect around 30MB. Then, you can start to figure out how many threads you can actually run.
You'll probably find you are over allocating memory at an app level (PHP max memory or MySQL) rather than the number of Apache threads itself; it is just that, that is the app tipping the usage over the edge.
For the time being, be very conservative, then work your way up. So lower the settings to something like this:
StartServers          1
MinSpareServers       1
MaxSpareServers       10
MaxClients            15
MaxRequestsPerChild   1500

Then lower all your MySQL memory settings, or at the very least, the number of connections (to around ~15); and lower all your PHP max. memory settings.
Memory Usage Script
Here's a little script I wrote for memory usage, but bear in mind, it isn't going to properly factor in shared libs etc.
Just create a new file,
Eg. /root/memory_usage.sh
Then run with the application name,
Eg. /root/memory_usage.sh apache2 or /root/memory_usage.sh mysqld
#!/bin/bash

grandtotal=0

if [ $# -lt 1 ];then
  echo "$0: invalid option"
  echo "You are missing required arguments"
  echo "1 Application name or 'all', 2 2nd application name (optional)"
  exit 0
fi

if [[ "$1" == "all" ]]; then
  tot=0;for i in `ps -e -orss=`;do tot=$(( $tot + $i )); done;
  echo "Total " $(( $tot /4096 )) "MB"
  exit
fi

for app in $@; do
  echo -n $app
  ps u -p $(pidof $app) | awk 'NR > 1 {nm += $5} END {print " Total:  " nm/1024 " MB"}'
  apptotal=`ps -e -orss=,args= | grep "$app" | awk 'NR > 0 {nm += $1} END {print nm}'`
  echo "$app Total: " $(( $apptotal / 4096 )) "MB"
  grandtotal=$(( $apptotal + $grandtotal ))
done

if [ $# -gt 1 ];then
  echo "Grand total: " $(( $grandtotal / 4096 )) "MB"
fi

Comment: Well, PHP isn't multi-threaded, so I would hope you are using prefork ... run `apache2 -V` to verify
Comment: Thanks, I would like to try your tip. But dunno which one i have to set to the numbers for testing: mpm_prefork_module vs. mpm_worker_module vs. mpm_event_module
Comment: thanks again for the fast reply. your memory check script is telling about 3GB for apache2 only - although that's not in use! http://nopaste.info/78e944cb9d.html
Comment: Bear in mind what I wrote in my comment earlier, it will show shared memory/libs in the VSZ/RSS calculation. You are allocating a massive amount of RAM to MySQL - so do as I said. Lower number of threads on Apache, connections on MySQL (to a MAX of 15) and lower PHP max memory to a sensible value (~16MB)

apache2: mpm configuration


Final do ASP.NET WebForms?

Question: Gostaria de saber se existe uma certa tendência em o ASP.NET WebForms se  "aposentar", ficando apenas o ASP.NET MVC, pois de acordo com este artigo a resposta seria sim. O autor do artigo (Ramon Durães) pelo menos ao meu ver é um grande conhecedor da tecnologia .NET.
A dúvida foi gerada diante da possibilidade de utilização de ASP.NET WebForms  em um novo projeto, digamos de tamanho médio.
Artigo:
Aposentadoria do ASP.NET WebForms
Answer: Olá, Anderson.
A tendência realmente é essa, porém isso não quer dizer que o suporte aos Web Forms será removido do Visual Studio, pelo menos não ainda. Inclusive o Web Forms teve atualizações na nova versão do ASP.NET (Web Forms 4.6), mas o foco dos esforços será sim o MVC. O Web Forms não irá acompanhar todas as novidades da plataforma ASP.NET e logo se tornará obsoleto.
Claro que para projetos pequenos e rápidos, com pouca manutenção, eu não vejo problemas em usar Web Forms (apesar de que eu hoje já não faria mais isso), porém considerando o cenário atual da web e do mercado, não é mais viável investir em Web Forms para novos projetos grandes (na verdade, projetos pequenos podem crescer também, não é mesmo?).
A menos que você tenha um bom motivo para usar Web Forms em seu novo projeto, lhe aconselho partir para o MVC, que é uma plataforma atual, está em constante atualização e nos fornece diversos recursos para desenvolver os mais variados tipos de aplicação. O MVC também permite investir mais em front-end, garantindo uma interface final mais agradável para o cliente e mais flexível e gerenciável para o programador.
Bem, em resumo é isso. Abraço.
Answer: Cara, afirmar assim que será o fim, não acho que deveria, até porque a escolha de qual plataforma seguir, vai depender exclusivamente do Arquiteto e/ou GerProj. Agora, quanto a tendência, acho que o MVC veio forte e tarde, pois linguagem como Java, já "embutia" o MVC em quase tudo, há bastante tempo. Gosto do MVC. Agora dizer que a MicroSoft vai obrigar as pessoas a optarem sempre para o MVC, não acho que ela faria isso. Acho que a MS permitirá por muito tempo ainda, que os arquitetos e gerproj, escolha qual caminho a seguir e ela continuará a fornecer esses dois caminhos, assim acho.

Final do ASP.NET WebForms?


Compiling Qt 5.2.1 for win32-msvc fails due to Linker Errors

Question: I'm trying to compile Qt 5.2.1 on a 64 Bit Win7 machine (I want 32 bit binaries).
I configured
configure -debug-and-release -opensource -platform win32-msvc2012 -opengl desktop -nomake examples -nomake tests

and I did set the compiler path by running
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\vcvars32.bat

It compiles for a while but fails when linking.
This is the error output:
link /NOLOGO /DYNAMICBASE /NXCOMPAT /DEBUG /DLL /OUT:..\..\..\..\plugins\platforms\qwindowsd.dll @C:\Users\steffenh\AppData\Local\Temp\nm9509.tmp
   Creating library ..\..\..\..\plugins\platforms\qwindowsd.lib and object ..\..\..\..\plugins\platforms\qwindowsd.exp
dlldata.obj : error LNK2001: unresolved external symbol _Accessible2_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleAction_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleApplication_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleComponent_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleEditableText_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleHyperlink_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleHypertext_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleImage_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleRelation_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleTable_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleTable2_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleTableCell_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleText_ProxyFileInfo
dlldata.obj : error LNK2001: unresolved external symbol _AccessibleValue_ProxyFileInfo
..\..\..\..\plugins\platforms\qwindowsd.dll : fatal error LNK1120: 14 unresolved externals
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\BIN\link.EXE"' : return code '0x460'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: 'cd' : return code '0x2'
Stop.
NMAKE : fatal error U1077: 'cd' : return code '0x2'
Stop.
NMAKE : fatal error U1077: 'cd' : return code '0x2'
Stop.
NMAKE : fatal error U1077: 'cd' : return code '0x2'
Stop.
NMAKE : fatal error U1077: 'cd' : return code '0x2'
Stop.

is there anyone who can help me?
best,
S.H

UPDATE
It seems that Qt tries to link against Microsoft Active Accessibility, whose main file is "oleacc.dll", located in the system path.
How can I check if this is for 32 bit or for 64 bit?
Answer: The linking worked when I added the VERBOSE linker flag via
"QMAKE_LFLAGS += /VERBOSE" to "mkspecs/qconfig.pri"
(This shouldn't change anything, but it worked).
Qt Bug Description is here: https://bugreports.qt-project.org/si/jira.issueviews:issue-html/QTBUG-37910/QTBUG-37910.html
Comment: I think that link is now: https://bugreports.qt.io/browse/QTBUG-37910  But yeah, that didn't work for me.


How to recreate /etc/cron.daily/apt?

Question: On my Debian 6.0.8 system the /etc/cron.daily/apt file is missing. Therefore, unattended upgrades do not work.
How can I recreate/fix /etc/cron.daily/apt?
Comment: It will not help with this problem but to prevent future issues may I suggest etckeeper. All you would have to do is use git to revert the change: https://joeyh.name/code/etckeeper/
Answer: first find which package contains the missing file:
$ dpkg --search /etc/cron.daily/apt
apt: /etc/cron.daily/apt

which is that case is the package "apt", and then re-install it:
$ sudo apt-get -o Dpkg::Options::="--force-confmiss" --reinstall install apt

edit: added the option to force the miss conf
Comment: This won't work as the missing file is in /etc and is considered a config file. As such it won't be installed again when doing --reinstall; unless you se  -o DPkg::options::=--force-confmiss
Comment: Correct, in that case we need to use the `-o Dpkg::Options::="--force-confmiss"`, so for that example it's `$ sudo apt-get -o Dpkg::Options::="--force-confmiss" --reinstall install apt`
Comment: This was very helpful as my virtual hosting provider decided it would be a good idea to remove this file, so even though I thought I had enabled automatic security updates, nothing was actually updated.
Comment: Same thing here with OpenVZ `ubuntu-12.04-x86_64.tar.gz` template.
Answer: You should extract the apt deb package in a temp location and then copy the missing file to where it should be.
For instance if your apt cache still contains the deb package apt you can do:
cd /tmp
dpkg -x /var/cache/apt/archives/apt_0.9.7.9+deb7u1_amd64.deb .
cp /tmp/etc/cron.daily/apt /etc/cron.daily/

If you don't have the deb file in your cache anymore, just download it and apply the same procedure.

How to recreate /etc/cron.daily/apt?


Chef: Preinstall packages or install everything from scratch (fast/inflexible vs slow/flexible )

Question: I'm curious is it a good strategy to prebuild binaries (install packages) and use chef for config management only. Theoretically it should speed up init process when we need new machines (traffic spike), especially if we use clouds like AWS where we can create our own AMI (images), at the same time it could be not flexible in terms of how other cookbooks work..
I'm looking forward to your thoughts on the question along with best practices, experiences and ideas!
Answer: Both ends of the spectrum have their pros and cons, as does the area in between.
A. Use a standard, public AMI with dynamic system configuration at boot
(+) Does not require learning how to build AMIs.
(+) Does not require learning how to manage a stable of historical AMIs.
(+) Easy to change and test the system configuration by editing the config and running a new instance.
(+) Easy to manage across regions, accounts by sharing config file(s).
(+) Easy to run variations of the config by tweaking the startup config rules.
(-) Initial startup of a system can be slow, or very slow, depending on how much work your startup configuration process needs to accomplish.
(-) Requires understanding how to automate startup config, especially if used with Auto Scaling or Spot instances.
B. Pre-build custom AMIS
(+) Initial startup is fast as no config steps need to be taken.
(+) Works well with Auto Scaling and Spot instances.
(-) Requires learning how to build and manage AMIs effectively.
(-) Requires building a new AMI every time the desired config changes.
(-) Requires building a new AMI every time OS security patches are released.
(-) Long edit/build/test loop when changing config
(-) Multiple AMIs required for different regions, different accounts (unless shared), different variations of configs, different instance architectures.
C. Something In Between
You can get some of the benefits (and some of the drawbacks) of both strategies by doing something in the middle: Create a base custom AMI that has most of what you need for your instances, then run a dynamic configuration at run time that updates and completes the configuration, applying any specific variations needed.
This speeds up the boot time, possibly by a lot, but also gives some flexibility and not having to rebuild AMIs as often.
Recommendations

Start by creating automated scripts (or Chef recipes) that will take a public AMI and configure it to your desired system.
Use the automated config with public AMIs (approach A above) for as long as that works for you.
When and where you run into startup performance issues, use the automated config to create custom AMIs (approach B above).  Automate this process as much as possible so that you can run it as often as needed.
If you have multiple system variations on top of the same basic base, build a custom base AMI and use approach C above to run the different system flavors.


Meta tag para geolocalização

Question: Estava procurando se existem meta tags para geolocalização, para ajudarem os motores de busca saber que as informações do meu site se referem a uma cidade específica.
Achei esse site que gera as seguintes tags para um endereço que digitei:
<meta name="geo.region" content="US-VA" />
<meta name="geo.placename" content="Fairfax" />
<meta name="geo.position" content="38.844573;-77.286766" />
<meta name="ICBM" content="38.844573, -77.286766" />

Procurei no www.w3.org e no www.w3schools.com algo relacionado a essas tags e não achei.
Essas tags geo. existem efetivamente? Estão em desenvolvimento? Os motores de busca interpretam elas?
Comment: http://searchengineland.com/should-you-geotag-pages-for-local-seo-22531
Answer: Vou responder até onde eu sei sobre sua pergunta, haha
O Google que detém 45% das pesquisas da internet, não reconhece esse meta tag.
As que ele reconhece estão aqui: https://support.google.com/webmasters/answer/79812?hl=pt-BR
Já vi gente usando estas tags(apesar de não saber muito sobre) e se, elas realmente forem úteis para o seu projeto, use-as!
Answer: Aparentemente com base nas respostas dadas e links providos, essas metatags não consideradas por todos os motores, principalmente pelo Google, conforme resposta do Giancarlo Soldera Graziano, e há pouco material disponível sobre isso.
O motivo para qual eu queria essas tags está na pergunta original:

....para ajudarem os motores de busca saber que as informações do meu site se referem a uma cidade específica.

Tentando achar a resposta, me deparei com outro conceito: dados estruturados. Sei que não perguntei sobre isso, mas é porque eu não sabia que isso existia, e na verdade era bem isso que eu estava procurando, mas não sabia.
Usando dados estruturados, eu consigo indicar para o Google(principal buscador) informações valiosas sobre meu site, inclusive a latitude e longitude que foi perguntada.
Esse site gera o script de dados estruturados. Ele irá te entregar um script do tipo application/ld+json que você coloca no head da sua página. Segue exemplo que gerei nesse site:

Há outros sites que geram isso, como:
http://microdatagenerator.com/generator.html
http://microdatagenerator.org/
Answer: Pelo que pesquisei a tag existe, a questão é que não é um padrão oficial.
Na wikipédia explica um pouco sobre o padrão: https://en.wikipedia.org/wiki/Geotagging#HTML_pages
Por via das duvidas se o seu projeto for se beneficiar dessa informação é interessante utilizar mesmo que nem todos os buscadores o utilizem ainda, pois assim quando utilizarem seu projeto já estará funcionando com ela.

Meta tag para geolocalização


Modifying an existing task to add a new dependency

Question: Is it possible to modify a task and add a prerequisite to it? For instance, I have an external build.xml that I'm importing. It includes a debug task. I want to add the dependency -prebuild-copy to that task.
I would just create a wrapper task but the debug target gets called for any libraries that my project includes and I need to ensure that -prebuild-copy is run for all of them. I could copy and modify the other build file, but it's the one that ships with android and I don't want to have to try to update my custom version every time the SDK gets updated.
Comment: Is it a debug task or target you want to modify. From the description it's unclear.
Comment: Sorry. I'm an ant neophyte. It's a target.
Answer: ANT has two task for importing common build logic:

import
include

The following example uses the more modern include.
Example
|-- build-common.xml
`-- build.xml

Project is run as follows
$ ant debug
Buildfile: /home/mark/tmp/build.xml

-prebuild-copy:
     [echo] PREBUILD TARGET

common.debug:
     [echo] I AM A DEBUG TARGET

debug:
     [echo] MY DEBUG TASK

build-common.xml
<project name="build-common">

    <target name="debug">
        <echo message="I AM A DEBUG TARGET"/>
    </target>

</project>

build.xml
<project name="demo" default="debug">

    <include file="build-common.xml" as="common"/>

    <target name="-prebuild-copy">
        <echo message="PREBUILD TARGET"/>
    </target>

    <target name="debug" depends="-prebuild-copy, common.debug">
        <echo message="MY DEBUG TASK"/>
    </target>

</project>


Dagger 2 androidx fragment incompatible types

Question: I'm using Dagger 2.21 and when I try to do
<code>@Module
internal abstract class FragmentModule {
    @ContributesAndroidInjector
    internal abstract fun loginFragment() : LoginFragment
}
</code>
and
<code>@Singleton
@Component(modules = [AndroidSupportInjectionModule::class, AppModule::class, ActivityModule::class, ViewModelBuilder::class, ViewModelModule::class, RepositoriesModule::class, ApiModule::class, FragmentModule::class])
interface AppComponent : AndroidInjector<PhotocoApplication> {
    @Component.Builder
    abstract class Builder : AndroidInjector.Builder<PhotocoApplication>()
}
</code>
I get this error:

/app/build/generated/source/kapt/debug/com/photoco/app/injection/module/FragmentModule_LoginFragment$app_debug.java:18: error: incompatible types: Class LoginFragment cannot be converted to Class extends Fragment

I have been searching and saw that using 2.21 and setting this gets it to work but no luck yet

android.useAndroidX=true ; android.enableJetifier=true

LoginFragment extends:

dagger.android.support.DaggerFragment()

With all this setup can't get it to build, am I missing something here? I can make it work with Activities using DaggerActivity but not with Fragments.
PhotocoApplication extends dagger.android.support.DaggerApplication
Thanks!
Answer: Fixed this issue by updating all dagger dependencies to 2.21, was missing android-support (was still using 2.16).
<code>implementation 'com.google.dagger:dagger:2.21'
implementation 'com.google.dagger:dagger-android:2.21'
implementation 'com.google.dagger:dagger-android-support:2.21'
kapt "com.google.dagger:dagger-compiler:2.21"
kapt "com.google.dagger:dagger-android-processor:2.21"
</code>
Comment: This solved my issue. Weird that Android Studio IDE didn't hint me to update the dependencies with a lint. Thanks for posting this answer!
Answer: I just had the same problem but with two non-Android classes: EventBus and a wrapper class around Android resources.
I tried the solution proposed by Emanuel Amiguinho even it had nothing to do with android-support and it got fixed. So I tried to remove the added dependency and retry, and magically built successfully again.
So I guess in my case it was some caching issue.


recent forum topics on sidebar of home page, recent articles and forum topics on article pages, recent articles on forum page

Question: I'm having a little trouble finding information to help me figure out what I'm trying to do. Please forgive me, as I am new to drupal's api. I have 3 particular scenarios where I would like a little helpful nudge in the right direction.
1 - I really enjoy having the most recent articles being shown on the front page by default. I would like to know how to have recent forum topics, separate from the recent articles, on the sidebar. Just text would be sufficient. Please tell me this is possible. I've searched for hours looking for some kind of information or maybe a module that accomplishes this.
2 - On the Forum, I would like the exact opposite. I would like the recent articles to be on the sidebar. Just the titles would be sufficient here as well.
3 - On the Article Pages, I would like both recent forum topics and articles on the sidebar.
I'm using the core Forum module, as well as Advanced Forum module. -Edit
Are there global variables I can use to achieve this? This, I'm sure, would help others as well with average time on site, and bounce rate.
--Edit--
As Dooshta mentioned, this can be accomplished with Views. It's so very easy to use!
Also, I noticed that there were disabled blocks already there for what I was looking for. I've enabled Recent Content for Article Topics, Active Forum Topics, and New Forum Topics. Once I'm done styling them on my local Drupal Installation, I'll post a link to my live site  to show an example for this Question!
--Edit--
I attempted using the provided blocks, however, I had a problem with a Configure Block link showing up on both provided forum blocks for all roles except admin. After a little research, I seen that it has been a problem for a long time and there's no simple fix. So I decided to use Views instead.
As I mentioned before, Views is absolutely simple to use. I created an Active Forum Topic Block, New Forum Topic Block, and a New Article Block for use on the sidebar. I couldn't configure the Active Forum Topic Block to display the topics in order with last topic commented on first until after creating it, but it wasn't difficult to figure out at all. the page is informative and organized.
If you would like to see how I used Views on my site, go to Strong Local Business. The New Articles don't display on the front page as intended, however you can see them on the sidebar when viewing an article, as designed.
Thanks again, Dooshta!
I hope this question helps others who may want to achieve the same results.
Answer: Sounds like something that would be easiest to accomplish with the Views module (seeing as you're using the Advanced Forum module you should already have it installed). It allows you to create blocks with the necessary content and then you can just adjust the block settings to get them displayed where you want.