Finding extremum of quadratic function divided by $x$

Question: How can we find the extremum value for the function:
$$f(x) = \frac{-(3x-4)^2}{2x}$$
I plugged this into GeoGeBra and found two extremums, $24$ and $0$, but how can we find it without using a calculator?
I've thought about calculating the extremum of the numerator first, then dividing it by the respective $x$ value, but it obviously don't work in this case.
How can we solve it?
Comment: It's not defined at $x=0$.  You can see you have a vertical asymptote there,  with one side going to $-\infty$ and the other to $\infty$, so there are no global extremes.  Local extremes you can find with calculus, taking the derivative and setting to 0
Comment: For $x>0$, $\dfrac{(3x-4)^2}{2x}\ge0$, so $f(x)\le0$; for $x<0$, $(3x+4)^2\ge0$, so $(3x-4)^2\ge -48x$, so $f(x)\ge24$
Comment: *When* does that method work?
Answer: $f(x)=\displaystyle-\frac{(3x-4)^2}{2x}$
$\displaystyle\frac{d}{dx}f(x)=-\frac{d}{dx}\frac{(3x-4)^2}{2x}$
$\displaystyle\frac{d}{dx}f(x)=-\frac{2x\frac{d}{dx}(3x-4)^2-(3x-4)^2\frac{d}{dx}2x}{4x^2}$
$\displaystyle\frac{d}{dx}f(x)=\frac{2(3x-4)^2-12x(3x-4)}{4x^2}$
$\displaystyle\frac{d}{dx}f(x)=-\frac{(3x-4)(6x+8)}{4x^2}$
For maximum and minimum values of $f(x)$, we have
$\displaystyle\frac{d}{dx}f(x)=0$
$\displaystyle-\frac{(3x-4)(6x+8)}{4x^2}=0$
$x=\frac{4}{3}$ or $ -\frac{4}{3}$
Clearly $x=\frac{4}{3}$ gives$f(x)=0$ and $x=-\frac{4}{3}$ gives $f(x)=24$ which is as you found graphically.
Answer: Here is a solution without calculus.
For $x>0$, $\dfrac{(3x-4)^2}{2x}\ge0$, so $f(x)\le0$,
with $f(x)=0$ when $3x-4=0$.
For $x<0$, $(3x+4)^2\ge0$, so $(3x-4)^2\ge-48x$, so $f(x)\ge24$,
with $f(x)=24$ when $3x+4=0$.
Comment: I don't quite understand the "$(3x-4)^2\geq-48x$" part: how did you find it?
Comment: $(3x+4)^2-(3x-4)^2=((3x+4)+(3x-4))(3x+4)-(3x-4))=(6x)(-8)=-48x$


Markov chain from Poisson process

Question: Let $K_t$ be a Poisson process with rate $1$ and $X_n=K_n-n$ $,  \  \  \        n\in \mathbb{N}$
Then we know that $X_n$ is a recurrent Markov chain. I am asked to determine whether the chain is null or positive recurrent.
I tried to compute the mean return time to zero, but, using the law of total probability, I got huge sums...
If $T=\min(n \geq 1 : X_n=0 |X_0 = 0) $ then I get:
$$ \mathbb{P}(T=k) = \sum_{t_1\not = 1}\sum _{t2\not = 2} \cdots \sum_{t_{k-1}\not = k-1} \mathbb{P}(K_1 = t_1)\mathbb{P}(K_2 = t_2)\cdots \mathbb{P}(K_{k-1}=t_{k-1})\mathbb{P}(N_k=k) $$
It does not look right....
How can I go on?
thank you very much
Comment: Possible duplicate of (second part of) [this question](https://math.stackexchange.com/questions/362190/question-about-markov-chain-derived-from-a-poisson-process) (although that part of the question is left unanswered in the accepted answer).
Answer: Recall (from the proof of recurrence) that
$$
\mathrm{P} (X_n = 0\mid X_0=0) = \mathrm{P}(K_n = n) = \frac{n^{n}}{n!}e^{-n} \sim \frac{1}{\sqrt{2\pi n}}, n\to\infty.
$$
Since $X$ is irreducible and aperiodic, if $X$ were positive recurrent, then this probability would converge to the value$^*$ $\pi_0>0$ of invariant distribution at zero. Since it converges to zero, $X$ is null recurrent.

$^*$ in fact, $\pi_0 = \frac{1}{\mathrm{E}[\tau]}$, where $\tau$ is the first time of the return to origin.

Markov chain from Poisson process


Hardy-Littlewood maximal inequality for uncentred intervals.

Question: Suppose $f: \mathbb{R} \rightarrow\ \mathbb{R}$ is Lebesgue-measurable. Define $f^{**}$ as
$$f^{**}(x) = \sup_{t>0}\left\{ \frac{1}{t} \int_{I_t}|f| : I_t \subseteq \mathbb{R}, |I_t| = t , x \in I_t \right\},
$$
where $I_t$ means an interval of length $t$.
Is there a (useful) bound on $\big|\left\{ x \in \mathbb{R}:f^{**}(x)>c\right\}\big|$ similar to the bound for the Hardy-Littlewood maximal function $\big(\;\big|\{ x \in \mathbb{R}:f^{*}(x)>c \}\big| \le \frac{3}{c}\int_{\mathbb{R}} |f|\;$ where $f^{*}(x) =\sup_{t>0}\left\{ \frac{1}{2t} \int^{x+t}_{x-t}|f| : t>0 \right\}\big)$ ?
Answer: Whenever $t > 0$ you have $$\int_{I_t} |f| \le \int_{x-t}^{x+t} |f|$$ for any interval $I_t$ with $x \in I_t$ and $|I_t| = t$, so that $$\frac 1t \int_{I_t} |f| \le  \frac{2}{2t} \int_{x-t}^{x+t} |f|  \le 2 f^*(x).$$ Now take the sup over all $t > 0$ and corresponding intervals $I_t$ to find that $f^{**}(x) \le 2 f^*(x)$. This means that $$\{x : f^{**}(x) > c\} \subset \{x : f^*(x) > c/2\}$$ and thus
$$|\{x : f^{**}(x) > c\}|  \le |\{x : f^*(x) > c/2\}| \le \frac 6c \int |f|.$$


Laravel missing argument 2

Question:
Missing argument 2 for
  Illuminate\Database\Eloquent\Model::setAttribute(), called in
  /vagrant/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
  on line 2335 and defined

The above I get trying to upload a CSV file.
Controller:
 public function postUpload ()
{
    if ( Input::hasFile('file') )
    {
        DB::transaction(function()
        {
            // Clear out what we have written
            DB::table('wc_program')->delete();

            $csv = new CsvFile(Input::file('file')->getRealPath());

            // Get the csv headers and move to the next line (the start of actual data)
            $columns = $csv->getHeader();
            $csv->next();

            // Loop through the rows creating / saving a record for each
            while( $csv->valid() )
            {
                $row = $csv->current();
                $pc = new Programmes();

                for( $i=0; $i<count($columns); $i++ )
                {
                    $pc->$columns[$i] = $row[$i];
                }

                $pc->save();
                $csv->next();
            }
        });

    return Redirect::to('admin/programmes')->with('flash_success', 'Upload completed & new data inserted.');
    }

Then I have a model thats just really basic and nothing major like so:
 class Programmes extends Eloquent {

 protected $guarded = array('id');
//public static $rules = array();

 protected $table = 'wc_program_1';

 public $timestamps = false;
 }

And routes setup like:
Route::get('admin/programmes/excelUpload','ProgrammesController@excelUpload');
Route::post('admin/programmes/doUpload', ['as' => 'admin.programmes.doUpload', 'uses' => 'ProgrammesController@postUpload']);

Answer: The code snippet Illuminate\Database\Eloquent\Model::setAttribute() expects two arguments, key and its value. It seems that your value is missing while being assigned to the column.
I suggest you to debug your code near at
$pc->$columns[$i] = $row[$i];

Please update your question if you find something helpful :)

Laravel missing argument 2


Android SurfaceView black screen on Galaxy S

Question: Hi I am wondering what the problem with the galaxy S is. I am using both a nexus S and a galaxy S phones for testing purposes. My whole app works pretty well on Nexus one. But when it comes to Galaxy S I cant see any video. Just hear audio.
Like I said above this doesn't happen on Nexus S. Is there something about the Galaxy S that messes with the SurfaceView? Sometimes I get a quick flash of the video before the screen goes black. My menu's and such still show up just not the video. Any help would be greatly appreciated. If you have know how to fix this kind of problem please help. I will add relevant code if necessary
I know for a fact that the video is playing because in one of the methods that stats the video player i put a logcat which tells me that video is starting to play.
Is it possible that the surface view is being hidden for some reason on the galaxy S?
Comment: What version of Android are each of the phones running? There might be some compatibility issues with some of your code.
Comment: Galaxy S works on Froyo while Nesus S works with 2.3.3
Answer: I'm not sure if this is relevant to you, but i had a similar issue with image assets not displaying on this phone, turns out i needed to use the layout-xhdpi, even though all other phones would default to the standard image in the 'layout' directory
Comment: The weird thing is I tried rewriting the video player activity as a standalone activity and it worked. But as soon as I transferred the activity to my other project and added all manifest permissions the app kept crashing. As for the xhdpi thing did your image flash in quickly and dissapear?
Answer: I finally figured out what the Problem was. I am changing some settings in for the aspect ratio. This somehow stops the image from showing up. I will update when i have found a solution.
Edit:
I call setAspectRatio on my my Video after it has been prepared and the video has started in the onPreparedListener.
Edit 2:
The best way around this error is to change the aspect Ration after VideSizeChanged listener is called the first time, as that is when the first dimensions of the video are found.


What are the maximal ideals $M$ of $R = \mathbb{F}_{p^n}[X,Y]/(XY - 1)$? What is the degree of $R/M$?

Question: Let $R = \mathbb{F}_{p^n}[X,Y]/(XY - 1)$.

What are the maximal ideals $M$ of $R$?
What does $R/M$ look like? What is it's degree over $\mathbb{F}_p$?

There is a theorem that states that for every $\mathbb{F}_p$-algebra $R$ of finite type and every maximal ideal $M \subset R$, $R/M$ is a finite field of characteristic $p$.
Now I thought that the ring $R$ above is actually a field isomorphic to $\mathbb{F}_{p^n}(X)$. Since it's a field the only maximal ideal is the trivial one and hence $R/M = R / \{0\} \cong R$. But that is not finite which seems to contradict the theorem. Where did I go wrong?
By the way I haven't yet found a proof of the mentioned theorem.
Comment: $R$ is the ring of Laurent polynomials over $\mathbb{F}_{p^n}$. It is not a field since it has many non-invertible elements, such as $1 + X$. You don't need the theorem you cite if you understand the maximal ideals of $\mathbb{F}_{p^n}[X]$ and know some basic things about localization.
Comment: See if you can show that $R$ is naturally isomorphic to $\mathbb{F}_{p^n}[X]_X$, i.e., the polynomial ring with $X$ inverted. Then use the relationship between prime ideals before and after inverting something to relate these to a particular set of the maximal ideals of $\mathbb{F}_{p^n}[X]$.
Comment: Thanks for the help. I realised $R$ is isomorphic to the polynomial ring with $X$ inverted, but mistakenly concluded that it was hence a field.
Answer: Trying to write down an answer to an unanswered question. I'm also trying to clear to myself out some "obvious" things, as the proof, and write them down, so  please feel free to comment about anything in this post.
Putting $\,I:=\langle\,1-xy\,\rangle\,$ , define
$$f:R\longrightarrow \mathbb F_{p^n}[x,x^{-1}]\,\,,\,\,f(g(x,y)+I):=g(x,x^{-1})$$
$\,f\,$ is well defined: $$g(x,y)+I=h(x,y)+I\Longrightarrow g(x,y)-h(x,y)=t(x,y)(xy-1)\Longrightarrow$$
$$ g(x,x^{-1})-h(x,x^{-1})=t(x,x^{-1})(xx^{-1}-1)=0\Longrightarrow g(x,x^{-1})=h(x,x^{-1})$$
$\,f\,$ is clearly a homomorphism of rings, and $\,g(x,x^{-1})=0\stackrel{(**)}\Longleftrightarrow g(x,y)\in I\,$ , from which we get that $\,f\,$ is bijective and thus an isomorphism.
Proof of $\,(**)\,$ above: let
$$g(x,y)=\sum_{k=0}^ma_k(x)y^k\in \mathbb K[x][y]\cong \mathbb K[x,y]\,\,,\,\mathbb K=\,\text{any field}$$and write
$$a_k(x)=\sum_{i=0}^{n_k}a_{ki}x^i\,\,,\,\,n_k\in\mathbb N\,\,,\,a_{ki}\in\mathbb K$$
Suppose $\,g(x,x^{-1})\equiv 0\,\,\,\text{in}\,\,\,\mathbb K[x,x^{-1}]$ . This means
$$g(x,x^{-1})=a_{0,0}+...+a_{0,n_0}x^{n_0}+x^{-1}\left(a_{1,0}+...+a_{1,n_1}x^{n_1}\right)+\ldots +x^{-m}\left(a_{n,0}+\ldots +a_{n,n_m}x^{n_m}\right)$$
The above expression being identically zero means that for any $\,k\in\mathbb N\,$ , we have
$$I\;\;\;\text{coefficient of}\,\,\,x^{-k}=a_{k,0}+a_{k+1,1} +\ldots +a_{j,j-k}+...=0$$
$$II\;\;\;\!\!\text{coefficient of}\,\,\,x^k\,\,=a_{0,k}+a_{1,k+1} +\ldots +a_{k,k+j}+...=0$$
The above sums are for sure finite, as there's only a finite number of powers (negative and positive) of $\,x\,$ with non-zero coefficients (this follows directly from the definition of ring of Laurent polynomials, of course).
Thus, going back to $\,g(x,y)\,$ and taking the sum of monomials with the above coefficients, we get
$$a_{m,0}x^m+a_{m+1,1}x^{m+1}y+\ldots +a_{m+k,k}x^{m+k}y^k=x^m\left(a_{m,0}+a_{m+1,1}xy+...+a_{m+k,k}x^ky^k\right)=$$
$$\stackrel{by\,\,I}=x^m\left(-a_{m+1,1}-a_{m+2,2}-\ldots -a_{m+k,k}+a_{m+1,1}xy+\ldots a_{m+k,k}x^ky^k\right)=$$
$$=-x^m\left[a_{m+1,1}(1-xy)+a_{m+2,2}(1-x^2y^2)+...+a_{m+k,k}(1-x^ky^x)\right]\in I=\langle \,1-xy\,\rangle$$
since $\,1-x^ty^t=(1-xy)\left(1+xy+...+x^{t-1}y^{t-1}\right)\,$ . (The same argument works for the sum of monomials belonging to $\,II\,$ above)


Truncate file at the end with PHP

Question: I have a log file that I would like to truncate after it has been read by PHP. My code currently looks like this:
$fp = fopen($file, "r+");
ftruncate($fp, 125000);
fclose($fp);

However, this truncates the file by keeping the first 1Mb. However, I would like to keep the last 1Mb of the file; logs lines are appended so I would like to keep the most recent entries, rather than the oldest (the post-truncate file would always be the same with this code).
Comment: This is what [`ftruncate()`](http://php.net/manual/en/function.ftruncate.php) does. If you want to keep the tail of the file you have to write your own code that copies the desired part into a new file then replaces the old file with the new one.
Comment: If another process has the log file open for writing, and they didn't use "append" mode, they won't adjust to the truncated position. Log file rotation is usually done by renaming the file and sending a signal to the logger telling them to start a new file.
Answer: You cannot use the ftruncate function to perform this process, since it only accept the final truncation size as argument and the truncation is performed starting from the beginning. Give this a try:
// open the file for reading only
$fp = fopen($file,'r');
// place the pointer at END - 125000
fseek($fp,-125000,SEEK_END);
// read data from (END - 125000) to END
$data = fgets($fp,125000);
// close the file handle
fclose($fp);

// overwrite the file content with data
file_put_contents($file,$data);

Answer: Try this, simple enough and does the trick :)
$logsToKeep = file_get_contents($file, NULL, NULL, -125000, 125000);
file_put_contents($file,$logsToKeep);

edit: if running version prior to v7.1 (anywhere from php5), you can use
$offset=filesize($file)-125000;
if($offset>0){
    $logsToKeep = file_get_contents($file, NULL, NULL, $offset, 125000);
    file_put_contents($file,$logsToKeep);
}

but this does reduce efficiency. the answer being efficiency driven. To quote php doc , "file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance." So a clean call to a negative offset remains the best way to get the last N bytes of a file.
Comment: Negative offset isn't available until PHP 7.1.0.

Truncate file at the end with PHP


Como acessar propriedades de um objeto dentro de outro objeto no ReactJs

Question: Estou consumindo via axios o seguinte JSON: https://randomuser.me/api/?results=5
Quando tento acessar pessoa.name.title recebo o seguinte erro:

Só consigo acessar a propriedade title quando digito dessa forma {pessoa.name && pessoa.name.title,
Alguém sabe me explicar porquê?
import React, {Component} from 'react';
import {Card, Col, Button} from 'react-bootstrap';
import api from "../../services/api"

class CardPeople extends Component {
    constructor(props){
        super(props)
        this.state = {
            pessoas: [
                {
                }
            ]
        }
    }
    async componentDidMount(){
        const people_api = await api.get("https://randomuser.me/api/?results=5");
        this.setState({
            pessoas: people_api.data.results
        })
    }
    render() {
        return (
            <>
             {this.state.pessoas.map((pessoa, index) =>
            <Col key={pessoa.gender}>

 {pessoa.name && pessoa.name.title}

            </Col>
            )}
            </>
        )
    }
}

Answer: Verificando seu código acabei descobrindo que foi iniciado o array de pessoas com um objeto vazio, observe:
this.state = {
    pessoas: [
        { // <-- aqui o problema
        } // <-- aqui o problema
    ]
}

mas, no caso como não tem itens no array (os itens que vão ser carregados após o componente estar totalmente carregado), só precisa informar para o script que é um array sem item (com tamanho 0), exemplo:
this.state = {
    pessoas: [] //correto
}

ou seja, como foi iniciado o array com um objeto sem chaves e valores, causa no inicio do carregamento desse componente a exceção como demonstrada na sua pergunta por falta de informação que somente está disponível a partir da requisição.

Eu acabei simulando um exemplo e no meu caso funcionou perfeitamente, exemplo:

class Source extends React.Component {
  constructor() {
    super();
    this.state = {
      results: []
    };
    this.getResults =
      this.getResults.bind(this);
  }

  componentDidMount(){
     this.getResults();
  }

  getResults() {
    fetch('https://randomuser.me/api/?results=5')
      .then(r => r.json())
      .then(r => {
        this.setState({results: r.results});
      });
  }

  render() {
    return (

          {this.state.results.map((p,i) =>
{p.name.title}
)}

    );
  }
}
ReactDOM.render( <Source/> , document.getElementById('root'));

Carregando ...

O exemplo acima foi realmente para demonstrar o funcionamento, só difere que foi utilizado um API própria do javacript para buscar informações nessa url mas, o problema na verdade é como foi explicado só fazer alteração removendo o objeto vazio do array que o seu código vai funcionar.
Comment: Foi justamente isso, funcionou perfeitamente, muito obrigado.


upload speed control from IIS?

Question: If I am using IIS 7.0 + Server 2008/Vista Enterprise, any ways from IIS 7.0 side to control the upload speed? For example, max upload speed at 1M bytes/second?
Any configuration based easy solution is great! And any programming based solution is also appreciated. :-)
thanks in advance,
George
Answer: I'm unaware of any controls within IIS to handle this.  A customer ISAPI handler would probably be able to do so, but that would be a question for Stack Overflow.
Comment: No, I don't sorry.  Check SourceForge and CodePlex and see what you can find.
Comment: I don't know of any commercial products either.  I know that one company I worked for did this sort of this for one of our web clusters.  You might want to check over on stack overflow and see if anyone has any code that can help out.
Comment: Thanks, do you know whether there are any open source implementation for such ISAPI control available? I may need to have some customization.
Comment: For non-open source ones as you suggested, what products do you mean? Could you recommend some please? :-)
Comment: What is the commercial product you are working on? Do you recommend me to use it? :-)
Comment: This wasn't a product for sale.  It was part of our system.

upload speed control from IIS?


Good book that contains stochastic integration, martingales and Lévy-processes?

Question: Does anyone know about any good and easy interoductory books which contins information about martingales, sotchastic integration and Lévy-processes?
I have tried reading: http://www.cambridge.org/us/academic/subjects/statistics-probability/probability-theory-and-stochastic-processes/levy-processes-and-stochastic-calculus-2nd-edition and it is very hard, I am not really able to get much out of it. Do you know about any lower level texts you can reccomend please?, which contains stochastic calculus and the theory about Lévy processes?
I would like it to introduce stochastic calculus from scratch, where the only prerequisites are real analysis and measure theory.
Answer: Since Lévy processes are used a lot in finance, there are several books on this topic (that is, Lévy processes and their applications in finance). For example "Stochastic Calculus for Finance II" by S. Shreve introduces stochastic integration and contains some material on Lévy processes. However, if you are less interested in applications, but more in the theory behind it, then this might not be your first choice.
For an introduction to Lévy processes I recommend "Stochastic Processes" by Barndorff-Nielsen & Sato. On $\approx$ 60 pages they present the most important results on Lévy processes and the book is quite readable, I would say.
There are plenty of books on stochastic integration. If you are new to stochastic integration, it might be a good idea to start with stochastic integration with respect to Brownian motion and then have a look at the general theory afterwards. For example, in "Brownian Motion - An Introduction to Stochastic Processes" by Schilling & Partzsch, stochastic integration (with respect to Brownian motion) is introduced (and proved) in such a way that it can be generalized to stochastic integration with respect to martingales without difficulties.
Comment: May I know how Levy processes are used in finance? In what aspect of finance?
Answer: It depends a little bit on your interests, but as you might know, stochastic processes and Itô-calculus is excessively used in quantitative finance. I can recommend some books which really explain the basics of stochastic integration and stochastic differential equations. However, these books have a (strong) focus towards financial applications.

'Elementary Stochastic calculus with finance in view' by Thomas Mikosch, is a good book. It starts from scratch and really explains the basics of stochastic integration and stochastic differential equations. Only the last chapter is related to financial applications.

If you want more 'difficult' books then I would suggest:

Steven Shreve: 'Stochastic calculus for finance'
Michael Steele: 'Stochastic Calculus and Financial Applications'

If you are really not interested in any financial applications at all, then I would recommend 'Introduction to Stochastic Integration' by K. L. Chung and  R.J. Williams.


How to show a date in the correct timezone?

Question: I have a Datetime Range field (field_date) in a content type. Once I create my content type I set the Start Date as:
2017-02-27 19:30:01

Now I want to get the value and show the date in other format, so try to use the following code:
// Loading the node.
$node = Node::load(2100);
// Getting the start date value.
$date = $node->field_date->value;
// Printing to see what is the output.
dpm($node->field_date->value);
$date = strtotime($date);
// Printing my timezone.
dpm(drupal_get_user_timezone());
// Applying my custom format.
$date = \Drupal::service('date.formatter')->format($date, 'custom', 'Y-m-d H:i:s', drupal_get_user_timezone());
// Printing to see the output.
dpm($date);

This is my output:
// It's fine.
2017-02-28T00:30:01
// Its fine.
America/New_York
// This is not what I waiting for. I'm waiting here: 2017-02-27 19:30:01
2017-02-28 00:30:01

So, how to show a date in the correct timezone?
Answer: I suspect the problem has to do with some of the nuances of strtotime().
strtotime() can take just about any string, and convert it into a Unix timestamp.  The problem is that when the string doesn't contain an explicit timezone, it will use what is set by date_default_timezone_get().  That should be set from the current user, though (it is set by the account proxy).  However, the string that you are pulling out of $node->field_date->value is implicitly in UTC.  In other words, I think the string is being parsed by strtotime() is being interpreted as in 'America/New_York' and not 'UTC'.
The good news is that you can simplify your situation a lot.  The field item for a date range consists of four parts

'value' is the start date as a string in UTC
'start_date' is a DrupalDateTime object representing 'value'
'end_value' is the end date as a string in UTC
'end_date' is a DrupalDateTime object representing 'end_value'

For a plain date time field they are

'value' is the date as a string in UTC
'date' is a DrupalDateTime object representing 'value'

So, you can work with the DrupalDateTime() object directly.  In addition, that date.formatter service should pull in the proper timezone in use by the user viewing the page by default (in addition to using the user's active language).
I suspect something like this will work
$node = Node::load(2100);
$start_date = $node->field_date->start_date;
$formatted = \Drupal::service('date.formatter')->format(
  $start_date->getTimestamp(), 'custom', 'Y-m-d H:i:s P'
);

Note I added the 'P' format placeholder in there so you can see what what timezone the system thinks is in use.
Make sure you have the proper timezone set up on admin/config/regional/settings, and that your user timezone is what you are expecting.  Also ensure that you have the proper timezone set in your php.ini (it's the date.timezone setting); weird things happen when this isn't set (And off the top of my head, I don't recall if that causes a warning in the installer or on the status report when not set.  I remember the issue, but not whether it got committed).
Comment: @Pzanno I'm the Drupal 8 core datetime.module co-maintainer, and also a lot of other core date/time related stuff comes my way :) The properties are magic methods.  If you look at `DateTimeItem::propertyDefinitions()`, you will see what is exposed.  Then look at `DateTimeComputed::getValue()` to see how that works.  All Item classes can be examined that way, but only a handful use computed values.  I wish there was a better way to expose this to the API.
Comment: Props to this response as this is the most informative piece of Drupal documentation I've EVER found.
Comment: @mpdonadio Thanks for the help! I did not know about the `date` feature to access the DrupalDateTime. Out of curiosity how did you figure this out? I was able to figure out that my field was of the type `DateTimeItem` but within there it doesn't seem obvious that there is a `date` (or `value`) public member for that class.
Comment: In my case, I had to do `$node->field_date->date`, instead of `$node->field_date->start_date`.
Comment: @mpdonadio thanks for the explanation! I missed the fact that they were even defined in `DateTimeItem::propertyDefinitions()`. I figured there was some magic methods happening, but wanted to understand how these were created so I could better understand how to access other fields as well. Like you said it would be nice if the API was exposed, but this helps. Thanks again.
Comment: Thank you. I was using $node->field_date->value instead of $node->field_date->date
Answer: Based in Handling timezone conversion with PHP DateTime I modified my code to this:
$node = Node::load(2100);
$userTimezone = new DateTimeZone(date_default_timezone_get());
$gmtTimezone = new DateTimeZone('GMT');
$myDateTime = new DateTime($node->field_date->value, $gmtTimezone);
$offset = $userTimezone->getOffset($myDateTime);
$myInterval = DateInterval::createFromDateString((string)$offset . 'seconds');
$myDateTime->add($myInterval);
$result = $myDateTime->format('Y-m-d H:i:s');
dpm($result);

And now my output date it's fine:
2017-02-27 19:30:01

This works. But I'm sure that there is a way to do this using the Drupal API.
Comment: I removed my previous comment.  DrupalDateTime doesn't adjust for Drupal user's timezone.
Comment: In my case I just used this before any date function call: `date_default_timezone_set(drupal_get_user_timezone());`
Comment: Thanks for this.  It really helped me with https://drupal.stackexchange.com/q/256490/2089.
Comment: @colan a pleasure help you, if you think that my answer is useful I think that you can check the other answer too.
Answer: I usually solve it this way.:
node = Node::load(1);
$date_original= new DrupalDateTime( $node->field_date->value , 'UTC' );
$result = \Drupal::service('date.formatter')->format( $date_original->getTimestamp(), 'custom', 'Y-m-d H:i:s'  );
dpm( $result );

Answer: This worked for me:
// Take the timestamp.
$timestamp = $form_state->getValue($form_field)->getTimestamp();
// Convert to UTC - the way its saved in database.
$date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
// Add on the current entity.
$this->entity->{$db_field}->value = $date->format("Y-m-d\TH:i:s");

Comment: It works for me as well
`
$dDate = DrupalDateTime::createFromTimestamp($form_state->getValue('service_date')->getTimestamp(), 'UTC');

// Use like this.
$dDate->format('Y-m-d\TH:i:s');`
Comment: The best solution. Thanks so much!
Answer: This code is working for me.
// set use timezone
userTimezone = new DateTimeZone(drupal_get_user_timezone());
// set gmt timezone
$gmtTimezone = new DateTimeZone('GMT');
// Take the timestamp.
$start_date = $val['field_start_time_value'];
$startDateTime = new DateTime($start_date, $gmtTimezone);
$offset = $userTimezone->getOffset($startDateTime);
$startInterval = DateInterval::createFromDateString((string)$offset . 'seconds');
$startDateTime->add($startInterval);
$result = $startDateTime->format('Y-m-d H:i:s');

Answer: None of these other answers worked for me. This is what I finally ended up with:
$range_start = DrupalDatetime::createFromTimestamp((int)$start_date); // unix timestamp
$range_start->setTimezone(new \Datetimezone('EST'));
$node->field_date_range->value = format_date(
  $range_start->getTimestamp() , 'custom', 'Y-m-d\TH:i:s', 'EST');

Answer: I use this snippet to work with dates :
<?php
class MyApp extends ControllerBase
{
    public function output()
    {
        $dtime = DateTime::createFromFormat("d/m/Y - H:I:s", "22/12/1999 - 22:55:12", $this->getDateTimeZone());
        $time = $dtime->format('r');
        // My code goes here
    }

    private function getDateTimeZone()
    {
        return new DateTimeZone(drupal_get_user_timezone());
    }
}

You can get more informations about the Datetime object here


Trying to unit test a React component using Jest and Enzyme

Question: I am trying to run a simple jest and enzyme test against a react component and test throws: ReferenceError: React is not defined. I followed all simple tutorials on jest and react testing but all of them resulted in the same exception. I used npm test and result was the same as yarn test, React not defined. I am confused. Any help would be appreciated.
 Checkbox.test.jsx: simple test
import { shallow } from 'enzyme';
import sinon from 'sinon';

import Checkbox from './Checkbox';

describe('<Checkbox />', () => {
  it('should render three <Checkbox /> components', () => {
    const wrapper = shallow(<Checkbox />);
    expect(wrapper.prop('title')).toEqual('Events — Event Radar');
  });
});

Console log
$ yarn test
FAIL src\components\ReusableComponents\Checkbox.test.jsx (5.248s)
  <Checkbox />
    × should render three <Checkbox /> components (4ms)

  ● <Checkbox /> › should render three <Checkbox /> components

    ReferenceError: React is not defined

      at Object.<anonymous> (src/components/ReusableComponents/Checkbox.test.jsx:8:40)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        10.517s
Ran all test suites.
error Command failed with exit code 1.

package.json
{
  "name": "mi-benchmarking-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.17.0",
    "classnames": "^2.2.5",
    "history": "^4.7.2",
    "prop-types": "^15.6.0",
    "react": "^16.0.0",
    "react-bootstrap": "^0.31.5",
    "react-bootstrap-table": "^4.1.1",
    "react-dom": "^16.0.0",
    "react-logger": "^1.1.0",
    "react-pagination-table": "^1.1.0",
    "react-redux": "^5.0.6",
    "react-router": "^3.2.0",
    "react-router-redux": "^4.0.8",
    "react-scripts": "1.0.14",
    "react-simple-paginate": "^1.1.0",
    "react-table": "^6.6.0",
    "redux": "^3.7.2",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "autoprefixer": "^6.3.6",
    "babel-core": "^6.26.0",
    "babel-eslint": "^6.0.4",
    "babel-jest": "^21.2.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-react-require": "^3.0.0",
    "babel-plugin-syntax-object-rest-spread": "^6.13.0",
    "babel-plugin-transform-object-spread-inline": "0.0.2",
    "babel-polyfill": "^6.8.0",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.5.0",
    "clean-webpack-plugin": "^0.1.13",
    "copy-webpack-plugin": "^4.0.0",
    "css-loader": "^0.23.1",
    "enzyme": "^3.1.0",
    "enzyme-adapter-react-16": "^1.0.2",
    "eslint": "^3.19.0",
    "eslint-loader": "^1.5.0",
    "eslint-plugin-babel": "^4.1.2",
    "eslint-plugin-react": "^7.1.0",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.5",
    "html-webpack-plugin": "^2.16.1",
    "jest": "^21.2.1",
    "jest-enzyme": "^4.0.1",
    "json-loader": "^0.5.4",
    "postcss-loader": "^0.9.1",
    "redux-devtools": "^3.4.0",
    "sinon": "^4.0.2",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "2.6.1",
    "webpack-dev-server": "2.5.0",
    "webpack-manifest-plugin": "1.1.0"
  },
  "scripts": {
    "start": "npm run build:dev",
    "build:dev": "webpack-dev-server --inline --history-api-fallback",
    "build:test": "webpack --define process.env.NODE_ENV='test'",
    "build:stage": "webpack --define process.env.NODE_ENV='stage'",
    "build:prod": "webpack --define process.env.NODE_ENV='production'",
    "eject": "react-scripts eject",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage"
  },
  "jest": {
    "setupTestFrameworkScriptFile": "./node_modules/jest-enzyme/lib/index.js"
  }
}

Answer: Import React in your test and the error should disappear:
import React from 'react';

I tried removing this import in one of my tests and I got the same error you mentioned.
I hope this helps.


Upgrading Drupal 8 to a newer version from the command line using Drush?

Question: Currently I have stable Drupal 8.1 release and I would like to uprgrade my site to 8.2 dev. How can I do this via the command line with Drush if that is even possible?

If not using drush, can I just download 8.2 and extract it into 8.1 directory?
Comment: I believe one method is replacing the core directory and running composer update, to get any package updates / new composer additions. Could be wrong on that last part.
Answer: To do it via the command line you can simply run the command drush up drupal
To do it manually, it's a bit more tedious as you need to be really careful about what you want to keep, templates.. modules... themes. Basically you need to replace all core files at the root level and note that the files that reside at the root level e.g. .htaccess.. robots.txt need to be compared and merged with the latest.
I hope this helps.
Comment: Note that `drush up drupal` will not take you from Drupal 8.1.8 to any Drupal 8.2.x release, because Drupal 8.2.x has no stable releases yet. Specify the version number per my answer to switch from a stable to a newer dev or beta release.
Comment: From Drupal 8.1.x to 8.2.0-rc1 you can do `drush up drupal-8.2.0-rc1`
Answer: Try drush pm-update drupal-8.2.0-beta2 for the beta2 release, or drush pm-update drupal-8.2.x for the dev release.


Valiha maintenance

Question: I recently got my hands on a valiha (an string instrument from Madagascar) which seems quite old, despite still working. I would have loved to change the strings since they seem a little bit old, but they appear to be nailed in place, so I can't safely remove and change them.
Therefore, I am trying to find a way to keep the strings as clean as possible. Would there be an efficient way to protect and/or clean the strings?
EDIT: As requested, some information about the valiha I have. First of all, a photo.

There are 17 strings, which are definitely nailed in place, I can't change them (good valihas have tuning pegs, not mine). It is a plucked string instrument. Here is another photo; it's a top view of the instrument that shows the nails piercing through it.
Answer: There are lots of products on every guitar store that help you mantain/clean your strings.
Based on a quick search online, i've read they use bicycle brake cords as strings, my guess is that you can use a regular electric guitar cleaning product, and also, in case you can replace them, i guess you can use regular electric guitar strings, just be careful choosing the gauge according to the tuning of the instrument.
this might be all wrong, but it's just my opinion, since i've never had one of these instruments and there's not much/none info online about it, wikipedia has a page about it, but the bottom page links are dead...
I guess you'll pretty much have to teach yourself how to mantain this instrument, unless someone that has experience with one comes around :p
also, try posting some photos of the instrument, first because it would be interesting to see how it looks like, second, i'll try to take a look at it and help you find a way to replace the strings, they must be replaceable...
Also, post some useful info about the instrument, just for curiosity's sake :p
For example:
How many strings does it have?
What's the tuning?
How do you play it? (you pluck, hammer or bow the strings? have you tried something crazy like bowing if its made for plucking and the other way around? :p)
Comment: I'll try to addd some information then. It's true that there are not that much information about valihas on the internet.
Comment: first of all, it's an extremely interesting instrument :p since as you say, you have  no tuning pegs, im assuming you have to move those little wooden pieces if you need to tune, right? well the most reasonable way to accomplish changing strings in this that i see is, you try to carefully remove the nails, which is going to be quite hard since i dont see a plier and your hand fitting the cavity where you could reach the nails, and put ball end strings in it's place, the problem really, is the other end, where i dont know how the strings lock in place (char limit)
Comment: *if it is nails again, maybe try either nailing them yourself again, or just without removing the nails, lock the strings, if you know what i mean (try to remove the nails just enough so the new strings fit the hole and then lock them back in place).If you think this might be too hard to accomplish or you dont want to risk ruining the instrument, try to go with the string cleaner, although it is a lot less risky, the tone wount be as "renewed" as if you actually had new strings, but for a start, i would clean the strings, and then see what happens,props on the cool instrument and happy playing

Valiha maintenance


What is the problem with my approach for calculating an explicit formula for S(n,4) (stirling numbers of the second kind)?

Question: I know and understand the general formula for S(n,4) so I know this approach is not correct. But why can't we count this in the following way instead. First we choose 4 elements from the n to fill each partition (so we guarantee no empty partitions). This can be done in n choose 4 ways. Then for the remaining (n-4) elements we have 4 options as to where to place them. We then divide by 4! as we don't care about the order of the partitions themselves (they all look/are labeled the same). So we end up with:
${n \choose 4} \frac{4^{n-4}}{4!}$
This answer is incorrect and does not line up with the general formula for S(n,k), but I'm wondering why not? Where is the counting issue?
Comment: Those $4$ elements you chose at the beginning have been distinguished. In a real partition you can't tell which elements were chosen "first." So you've overcounted there. Your division by $4!$ is also confusing because you already divided by $4!$ with the binomial coefficient; note that when $n = 4$ the result here is not an integer.
Comment: Ah, I see. This makes a lot of sense now, thank you so much for the help.
Answer: EDIT: Oh, sorry, I somehow missed that Qiaochu Yuan already pointed out the extra division by $4!$. Anyway, I've spelled it out below.
In addition to Qiaochu Yuan's comment, your formula does't even yield integers. If you removed the $4!$, then you would be counting the number of partitions into $4$ pointed subsets, meaning subsets with a specified distinguished element (you can think of it as the "leader" of the set).
To illustrate, say $n=7$. First, choose the $4$ leaders, say $\{1,2,4,5\}$. This can be done in $\binom n4$ ways. Then, for each of the remaining elements, we choose which leader they should join, say $3$ joins $1$, and $6$ and $7$ join $4$, meaning we get the partition $\{1^*,3\},\{2^*\},\{4^*,6,7\},\{5^*\}$. I've marked the leaders with a star. The last step can be done in $4^{n-4}$ ways. We don't divide by $4!$ again, because the groups are distinguishable by their leader.
Comment: Thank you so much! This really cleared things up for me.


What point of equilibrium the particle will be close to after a sufficiently long time?

Question:
A particle is moving on the $x$-axis such that $$\frac {dx} {dt} = (x - 1) (x + 2) (x - 3).$$ Here $x$ denotes the $x$-coordinate of the particle and $t$ denotes time. The particle is so positioned
initially that it does not wander off to infinity. Which point of equilibrium will it be close to after a sufficiently long time?

I have solved the differential equation and found that $$\frac {|x-3|^{\frac {1} {10}} |x + 2|^{\frac {1} {15}}} {|x - 1|^{\frac {1} {6}}} = Ce^t$$ where $C$ is some arbitrary constant to be determined by the given initial condition. But I failed to understand the initial condition here. Could anyone please help me in this regard?
Comment: You only need to inspect the sign of $x'$. Since $x' > 0$ for $x > 3$, if $x(0) > 3$, $x(t) \to \infty$ as $t \to \infty$. Similiarly, if $x(0) < -2$, $x(t) \to -\infty$ as $t \to \infty$. If $-2 < x(0) < 3$, convince yourself $x'$ always has the right sign to move towards the middle fixed point $x = 1$.
Comment: No need to solve the ODE! Just draw the **phase portrait**, and the answer should hopefully become obvious.
Comment: Thinking more about it. If $x(0) > 3$ (or $< -2)$, $x(t)$ dosen't diverge to $\pm \infty$ as $t \to \infty$. It does that in finite time! In any event, this doesn't affect the behavior for $-2 < x(0) < 3$.
Comment: @Hans Lundmark what do you mean by **phase portrait**? Actually I am not familiar with such kind of things. Could you please explain a bit more? Thanks.
Answer: Say initially the particle is at $x_0$ (at $t=0$).

The particle is so positioned initially that it does not wander off to infinity.

This means $x_0 \ne 1$ so that you have a finite value for $C$.
Now as $t\to \infty$ the RHS of solution $\to \infty$ due to the term $e^t$.
Since $x$ is a function of $t$, the only way this could happen if $x(t) \to 1$ as $t\to \infty$. This means the particle will be near $x=1$ after a long time.
Comment: You need also to say that in LHS the numerator and the denominator will have same degree of $x.$ That's why the LHS can go to infinity for sufficiently large $t$ if and only if $x(t) \to 1$ as $t \to \infty.$ But the reasoning is very nice. Thanks a lot.
Comment: I think the numerator (or $x(t) $) can not go to infinity because of the initial condition "The particle is so positioned initially that it does not wander off to infinity", so the only possibility is $x\to 1$.


Can't access a local site site on LAN

Question: I have lighttpd setup on a machine (say ip is 10.107.105.13) with following details.
inet addr : 10.107.105.13
Bcast : 10.107.111.255
Mask : 255.255.240.0

I can access my site on this computer by using firefox http://localhost/index.html.
Now I am trying to access this site from another computer with following details
inet addr : 10.14.42.7
Bcast : 10.14.42.255
Mask : 255.255.255.0

But it says 'access denied'.
nmap 10.107.105.13 gives the following output.
PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
1234/tcp open  hotline
3306/tcp open  mysql
9418/tcp open  git

Following is the output of iptables -L -n -v on 10.107.105.13
 141 11207 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:80
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:80

FORWARD and OUTPUT section empty.
What is wrong with all this?
Answer: Perhaps lighttp is configured to only listen on the localhost IP address (127.0.0.1) while you need it to listen on all of them (typically 0.0.0.0).
Answer: The problem was with proxy authentication step. I had to add 10.0.0.0/8 in no-proxy variables in my browser and everything worked smoothly.
Comment: Now that you have your solution, you should mark this as the answer (the checkmark to the left)
Comment: I have to wait for 2 days to accept my own answer. StackOverflow policy.
Answer: Enable prerouting in you iptables because your both machine's subnet masks are different.

Can't access a local site site on LAN


Find the basis of the Ker(T) and Im(T) for $T: P_3 \to P_3$, $T(ax^3+bx^2+cx+d)=dx^3+cx^2+bx+a$

Question: For the linear application, $T: P_3 \to P_3$, $T(ax^3+bx^2+cx+d)=dx^3+cx^2+bx+a$, find

A matrix representation with respect to a basis of your choice
A basis of Ker(T)
A basis of Im(T)

What I have done so far...
Matrix representation: Taking a closer look at the map and the matrix operations, we can easily see that the matrix representation will be $\ldots$
Corrected Matrix:
$\begin{pmatrix} 0 & 0 & 0 & d \\ 0 & 0 & c & 0 \\ 0 & b & 0 & 0 \\ a & 0 & 0 & 0  \end{pmatrix}  $
Because
$\begin{pmatrix} d & 0 & 0 & 0 \\ 0 & c & 0 & 0 \\ 0 & 0 & b & 0 \\ 0 & 0 & 0 & a  \end{pmatrix} \begin{pmatrix} x^3 \\ x^2 \\ x \\ 1 \end{pmatrix} =T(ax^3+bx^2+cx+d)$
Basis of Ker(T): You have to find the set of all $ax^3+bx^2+cx+d \in P_3$ such that $$T(ax^3+bx^2+cx+d)=(0,0,0,0)^T$$
We consider
$\begin{pmatrix} d & 0 & 0 & 0 \\ 0 & c & 0 & 0 \\ 0 & 0 & b & 0 \\ 0 & 0 & 0 & a  \end{pmatrix} \begin{pmatrix} x^3 \\ x^2 \\ x \\ 1 \end{pmatrix} =\begin{pmatrix} 0 \\ 0 \\ 0 \\ 0 \end{pmatrix}$
Which will result in the following equations:
\begin{cases}
      dx^3=0 \\
      cx^2=0 \\
      bx=0 \\
      a=0 \\
      \end{cases}
Is this correct? I do not know how to proceed. I know we have to find $ax^3+bx^2+cx+d=0$ in $P_3$ such that T(ax^3+bx^2+cx+d)=0.
Basis of Im(T): If we just want to have a set of vectors which span the image, then it would be enough to take the column-vectors. But we want to have linear-independent vectors, which span our image.
What we have to do now: Consider $T^{T}$ matrix of T and apply the Gaussian-elimination-algorithm on it. The columns which you will obtain then form a basis of the image.
Need help
So the basis of the Im(T) is the vector columns of the matrix.
Comment: your matrix representation is not quite correct. The coefficients $a,b,c,d$ change with each polynomial. You are on the right track. The matrix should be sort of the flip of the identity matrix.
Comment: Hence is my matrix correct now?
Comment: Not quite, your matrix shouldn't have $a,b,c,d$ in it. These are arbitrary and vary with each element of the vector space.
Answer: You can try this way: choose basis $\displaystyle \{1,x,x^2,x^3\}$ of $P_3$. Then check:
$$T[x^3]=1$$
$$T[x^2]=x$$
$$T[x]=x^2$$
$$T[1]=x^3$$
So first element of basis is transofmed to fourth  by $T$, second to third, third to second, fourth to first. So the matrix representation is:
$$T=\begin{bmatrix}0 && 0 && 0 && 1 \\ 0 && 0 && 1 && 0 \\ 0 && 1 && 0 && 0 \\ 1 && 0 && 0 && 0\end{bmatrix}$$.
Now you can check that $\det T \neq 0$, so Ker(T)=$\{0\}$, so basis of Ker(T) is $\{0\}$, Im(T)=$P_3$, so basis Im(T) is $P_3$, for example, $\displaystyle \{1,x,x^2,x^3\}$.
Comment: How is the Ker(T) empty if you just stated that $Ker(T)=\{0\}$?
Comment: The Kernel of a linear map is never empty since $0$ is always in it. But because $det T\not=0$ the map is injective and so $0$ is the only element of the kernel.
Comment: Ok, I corrected the mistake.


Permutations in a necklace with repeated beads

Question: A string of beads is made up of 5 oranges and 5 black beads. If they are randomly arranged around the necklace, how many possible combinations are there?
My understanding:
Permutations in closed loop without repeated beads would be $\frac{9!}{2!}$. To find the permutations with
the repeated colors, I divided by $5!5!$ to get $\frac{9!}{2!5!5!}=12.5$.
The answer given is 63. Does anyone know where I went wrong?
Answer: A count of arrangements cannot be anything but an integer. To get the correct count of necklaces use Burnside's lemma with group $C_{10}$:

$\binom{10}5=252$ necklaces invariant under identity
$0$ necklaces invariant under $1/10,3/10,7/10,9/10$ of a turn
$2$ necklaces invariant under $1/5,2/5,3/5,4/5$ of a turn (alternate the colours)
$0$ necklaces invariant under $1/2$ of a turn (this would imply that opposite beads are the same colour, hence there are an even number of beads of any colour, which is not the case)

Hence there are $\frac{252+4\cdot2}{10}=26$ possible necklaces; $63$ is also wrong.


What does the following do_action mean in wordpress?

Question: I wanted my Google Analytics plugin to appear in the author role . I gave the manage_option capability to the author and the plugins do appear. However, I fail to understand why the google analytics does not appear..
While debuggin i came across the
<code>do_action('admin_menu', '');
</code>
in the wp_admin/includes/menu.php file and according to me this populates the additional plugins the admin activates.. However, I fail to understand where the function admin_menu is and why the google analytics plugin cannot appear ..
I would appreciate some help
Answer: do_action executes a hook, somewhere in your code. If the hook isn't created, it can't be fired...


Exibir  ao dar hover em um  com transition

Question: Gostaria de verificar se há possibilidade de exibir uma span ao passar o mouse sobre uma tag  com transition. O HTML está da seguinte forma:
Meu Texto

Até o momento fiz em CSS:
#id-a span {
    opacity: 0;
    -webkit-transition: all 1.25s ease-out;
    -moz-transition: all 1.25s ease-out;
    transition: all 1.25s ease-out;
}

#id-a {
    -webkit-transition: all 1.25s ease-out;
    -moz-transition: all 1.25s ease-out;
    transition: all 1.25s ease-out;
}

#id-a span:hover {
    opacity: 1;
}

Acontece que o texto "Meu Texto" está sendo exibido com a transition, porém, ele só será exibido ao dar o hover no próprio span do "Meu Texto". Gostaria que ele fosse exibido ao dar o hover no ícone que está dentro de .
Answer: Pelo que eu entendi vc quer que ao acionar um hover de algum elemento exibir outro componente (o span no caso)
Você pode fazer o seguinte primeiramente oculte seu span assim:
span {
display: none;
}

e utiliza um hover que afeta outro elemento dessa forma:
a:hover + span{
display: block; // coloque um valor para que o span apareça novamente
transition: 500ms;
backgroud-color: red;

}
e assim o seu input começa invisível e quando a pagina carrega e quando for acionado o hover no elemento A o span irá aparecer com as propriedades que vc inseriu, mas eu indico utiliza elementos DOM para esse tipo de solução, qualquer duvida estou a disposição.
dica: Utilize classes nos seus elementos para acessar no arquivo css.
Comment: Obrigada Matheus!
Answer: Pelo que entendi, você quer dar o hover no icon e fazer o texto do span aparecer. Para isso, basta você fazer uma pequena modificação no seu CSS:

#id-a span {
  opacity: 0;
  -webkit-transition: all 1.25s ease-out;
  -moz-transition: all 1.25s ease-out;
  transition: all 1.25s ease-out;
}

#id-a {
  -webkit-transition: all 1.25s ease-out;
  -moz-transition: all 1.25s ease-out;
  transition: all 1.25s ease-out;
}

#id-a i:hover ~ span /* aqui é a linha que mudou */  {
  opacity: 1;
}

O seletor ~ seleciona o próximo irmão.
Referência.


erlang substr - no function clause

Question: Learning erlang and just a bit confused with what I'm trying to do in the following code:
start() ->
   Lst = string:tokens("Hello,How,Are,You!Today",",!"),
   Result = [string:substr(Lst, ".!", len(Lst))],
Result.

I get the following error: exception error: no function clause matching string:substr(["Hello","How","Are","You","Today"],".!",5)
Comment: Exactly what are you trying to do? `lists:substr` is intended to work on a string, a list of characters, but you are calling it in a list of strings.
Answer: string:substr/3 takes integers in both its second and third argument:
10> [string:substr(Lst, 1, length(Lst))].
[["Hello","How","Are","You","Today"]]
11> [string:substr(Lst, 3, length(Lst))].
[["Are","You","Today"]]

You're passing the string ".!" as the second argument, which is why you're getting a function clause error.

erlang substr - no function clause


Probability of "manmade global warming is a problem with solutions that are cost-effective"

Question: I came across this post from a climate change skeptic, which made the following point (emphasis mine):

However, if Pope Francis is right that history will judge us, we need to decide what, if any, action is called for by asking four questions: Is the earth warming? Is that an overall bad thing? Is human activity the primary cause? And would forced standards be cost-effective?
Regrettably, none of those questions can be answered with absolute confidence because our knowledge is limited by data, finite in number and dependent on processes that, in some cases, are not fully known and, in others, not even identified. As already discussed, answering the first question and most basic with any degree of confidence is unlikely.
Yet even if each of those questions could be answered in the affirmative with 80 percent probability, their cumulative probability would be 41 percent, indicating the proposition that "manmade global warming is a problem with solutions that are cost-effective" is, at best, problematic.

I get the calculation ($0.8^4=0.4096 \approx 41\%$). However, I feel there is something wrong here. The above calculation seems to assume the answers are entirely independent. But they are clearly not. For example, if the Earth is not warming, then this is clearly not a bad thing, nor there is a cause to nothing, so humans cannot be such cause to nothing. Therefore, the first question kind of makes the other three redundant.
Similarly, if human activity is the cause of global warming, a cost-effective solution is more likely to exist that if global warming is not due to human actions. Thus, there last question is not independent of the other either.
How would one go to properly address this problem then? Do we need complete information of the joint distribution of the answers to the four questions?
Comment: This is not an answer to your question, but in practice be aware that the more specific we are, the lower the probability. So for example, saying that the next person we meet will have two legs and each leg will have five toes is less probable than saying the person will have two legs, full stop. So while the first claim seems somehow better (more complete), it is the second one that is more probable.
Comment: As you say, the arithmetic here is just $0.8^4 \approx 0.41$. That's not a cumulative probability, but a joint probability based on an assumption of independence. Whether it's worth even reading this stuff is the bigger issue!
Comment: Or with the theory of evolution: the more specific we make it, the more complete, intuitive and acceptable it might seem; but the less probable it is. So I should trust more firmly a claim that a species A developed into whatever (general) and then into species C than the more coherent claim that A developed into B which developed into C (where B is something in between A and C by its appearance).
Comment: @NickCox haha good point. I was curious about what is the argument of climate change skeptics.
Comment: For what it's worth I'd parse those as conditional probabilities, so $\Pr(A,B,C,D) = \Pr(D|C,B,A) \Pr(C|B,A) \Pr(B|A) \Pr(A)$
Comment: @Scortchi That's a good point here, but are you implying that the original thinkers were that subtle? (I declare a bias to trust consensus climate science here, and critically,  including a bias of participating in a small way to environmental science literature.)
Comment: @NickCox: IMO they may well have been thinking along the lines of:-"If the Earth's warming, is that a bad thing? And then if it is a bad thing [..]". But a charitable interpretation of the calculation does nothing to diminish the pointlessness of plucking the probabilities out of thin air to start with. Ill-defined probabilities at that.
Comment: @Scortchi We agree, naturally.
Answer: I usually parse such arguments as involving conditional probabilities
$\Pr(A,B,C,D) = \Pr(D|C,B,A) \Pr(C|B,A) \Pr(B|A) \Pr(A)$
which is formally correct without any assumptions of independence. (Rather like the Drake equation.)
Formal correctness doesn't make up for vagueness in the definitions of the events†, or for our being expected to nod along with numbers pulled out of thin air:—"80%'s quite a good chance, he's being fair there, isn't he?".‡ A cynical reader might suppose that an intial description of the outcome as a conjunction of affirmative answers to three questions (each with a generous-sounding 80% probability) didn't yield a low enough joint probability to make the point.
† Which isn't the only reason these "yes/no" questions would surely better be posed as "how much" questions.
‡ Moreover, as @gung points out, we're entitled to some explanation of the concept of probability being used here, presumably one quantifying degree of belief rather than long-run frequency.
Comment: @gung: I was also assuming epistemic rather than frequentist probabilities - something like a Bayesian perspective. Of course it behoves someone quantifying probability to be clear what they mean by it - I'll edit this point in.
Comment: This is a charitable interpretation of the statement, but I'm still not sure that it is coherent. Eg, the probability that the earth is warming is either $0$, or $1$, no other values are possible.


How do I pass a local variable to remote PowerShell Script

Question: Let me brief out what all methods I tried.
Here is the Start_TestTalk.ps1 script
$RN = $env:RName
$TestV = "Local_Variable"
Write-Host $TestV
Write-Host $RName
Write-Host $RN
Write-Host $env:RName
I've declared the below variables
$Name="myname"
$CPU= 100
First Method:
PS C:\Users\Administrator> Invoke-Command -Session $s -Scriptblock{ & "C:\Users\Administrator\Desktop\Start_TestTalk.ps1
" -RName $args[0] -RCPU $args[1]}-argumentlist $Name,$CPU
Local_Variable
Second Method
PS C:\Users\Administrator> Invoke-Command -Session $s -Scriptblock{ & "C:\Users\Administrator\Desktop\Start_TestTalk.ps1
" -RName $using:Name -RCPU $using:CPU}
Local_Variable
Third Method
PS C:\Users\Administrator> Invoke-Command -Session $s -Scriptblock{ Param($Name, $CPU) & "C:\Users\Administrator\Desktop
\Start_TestTalk.ps1" -RName $Name -RCPU $CPU}-argumentlist $Name ,$CPU
Local_Variable
All the above three methods just prints the 'Local_Variable' which is local to the remote machine and doesn't print the variable that I pass from my local machine(here $Name).
Comment: What is the contents of `Test.ps1`?
Comment: @MathiasR.Jessen: Thanks, there's nothing much as of now for testing purposes, I'm just trying to print the variable I pass from source machine. Here is the simple code

$RN = $env:RName
$TestV = "Local_Variable"
Write-Host $TestV
Write-Host $RName
Write-Host $RN
Write-Host $env:RName
Comment: The start_testtalk.ps1 doesn't use parameters....
Comment: @MartinBrandl: Sorry, I didn't get what you meant by 'start_testtalk.ps1 doesn't use parameters'.
Comment: You are passing parameters to Start-TestTalk.ps1 but the script is missing the parameter section e. g. `param($Name, $CPU)`
Answer: You can use the :using variable prefix:
Invoke-Command -Session $s -Scriptblock{ & "C:\Users\Administrator\Desktop\Test.ps1" -RName $using:Name -RCPU $using:CPU}

Comment: Thank you, It's still the same even with 'using' variable prefix
PS > Invoke-Command -Session $s -Scriptblock{ & "C:\Users\Administrator\Desktop\Test.ps1
" -RName $using:Name -RCPU $using:CPU}
Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
    + CategoryInfo          : InvalidData: (:) [Get-Process], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetProcessCommand
Comment: Then you probably use PowerShell 2.0? Try this: `Invoke-Command -Session $s -Scriptblock{ Param($Name, $CPU) & "C:\Users\Administrator\Desktop\Test.ps1" -RName $Name -RCPU $CPU}-argumentlist $Name ,$CPU`
Comment: I'm using the Powershell version 4 on both the local and remote machines, I tried the method you suggested as well but still the same. I've also updated the question with more specific details to avoid confusion. Thanks.
Answer: I figured out the way on how this feature works with the help of a Senior Architect here in our company. The variables sent from the local(source machine) are not actually made local on the remote machine and these just get dumped as values on the remote machine and not as variables(you can't use variables). A simple example on how the above script which I had mentioned works
Start_TestTalk.ps1 script

    $RN = $args[0]
    $CPU= $args[1]
    Write-Host $RN
    Write-Host $CPU

Now use the same old Invoke Command with slight changes removing the variables earlier used to hold the values from local machine
Invoking the remote script using argument list
I've declared the below variables
    $Name="myname"
    $CPU= 100
    PS C:\Users\Administrator\ Invoke-Command -Session $s -Scriptblock{ &
    "C:\Users\Administrator\Desktop\Start_TestTalk.ps1" $args[0] $args[1] }-
    argumentlist $Name,$CPU
   myname
   100
Now you see that you get the required output on the remote machine, so it conveys that the values are directly getting dumped and not with the variables and hence I was earlier not able to use those variables on the remote machine.


Can I use DenyHosts for a SMTP service

Question: I would like to block some hosts that are brute forcing my SMTP server.
I'm currently using DenyHosts for SSHD and was wondering if I can add the SMTP service too.
It could be possible based on this http://email@example.com/msg00833.html
Currently in my auth.log I get:
<code>Jan  3 17:58:40 servername saslauthd[10729]: pam_unix(smtp:auth): check pass; user unknown
Jan  3 17:58:40 servername saslauthd[10729]: pam_unix(smtp:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=
Jan  3 17:58:42 servername saslauthd[10729]: do_auth         : auth failure: [user=zzz] [service=smtp] [realm=] [mech=pam] [reason=PAM auth error]
</code>
But, from the logs I'm not getting the attacker's host. (I'm using Postfix)
Maybe there is a more "standardized" way of doing this with DenyHosts or is there an alternative?
Comment: Switch to dovecot for SASL instead, and trawl the dovecot logs with denyhosts. saslauthd is a pain in the b-hind.
Answer: You can also use Fail2ban instead Denyhosts. Here's a good explanation of how to do it for SMTP: http://theether.net/kb/100141

Can I use DenyHosts for a SMTP service


Need to Group/Sort and then do operation in the same column

Question: 1- For Each Part No, and also for each order Number ( need some grouping) , I need the data to be sorted in ascending order using the column On Time Start
2- Then I need to calculate the delta between two cells from the same column ( see picture bellow : B-A) , then create a new column called Span.plus.Queue
The reason I need to sort by ascending order is because the delta calculation must always be positive
structure(list(Order = c("100016572", "100016572", "100016572",
"100049101", "100049101", "100049101", "100049101", "100049101",
"100049101", "100049101"), Op = c(9997, 9997, 9997, 8391, 8392,
8393, 8394, 8395, 8396, 8397), `Op Desc` = c("PP&C Movement / Go To Stock",
"PP&C Movement / Go To Stock", "PP&C Movement / Go To Stock",
"ASSEMBLY REWORK IAW 200365779", "MACHINE SHOP IAW 200365779",
"ASSEMBLY REWORK IAW 200365779", "PP&C REWORK IAW 200365779",
"INSPECT IAW 200365779", "ASSEMBLY REWORK IAW 200365779", "PP&C REWORK IAW 200365779"
), `Part No` = c("2352841G1-516", "2352841G1-516", "2352841G1-516",
"2352841G1", "2352841G1", "2352841G1", "2352841G1", "2352841G1",
"2352841G1", "2352841G1"), WBS = c("G-CUST-01", "G-CUST-01",
"G-CUST-01", "G-6M76-01", "G-6M76-01", "G-6M76-01", "G-6M76-01",
"G-6M76-01", "G-6M76-01", "G-6M76-01"), `Work Cntr` = c("26801702",
"26801702", "26801702", "CHRP0000", "CHRP0000", "CHRP0000", "CHRP0000",
"CHRI0000", "CHRP0000", "CHRP0000"), `On Time Start` = structure(c(1557852668.803,
1557852668.803, 1557852668.803, 1579215738.477, 1579279874.08,
1579598294.2, 1579625528.097, 1579690071.267, 1583883648.167,
1584029686.74), tzone = "UTC", class = c("POSIXct", "POSIXt")),
    `On Time Comp` = structure(c(1585156034.313, 1585156034.313,
    1585156034.313, 1579216621.723, 1579285486.47, 1579605490.21,
    1579626040.097, 1583876924.857, 1584012522.213, 1584029801.71
    ), tzone = "UTC", class = c("POSIXct", "POSIXt")), Span_CDay = structure(c(316.011174884259,
    316.011174884259, 316.011174884259, 0.0102227546302257, 0.0649582175938068,
    0.0832871527776674, 0.00592592592592593, 48.4589535879647,
    1.49159775462967, 0.00133067129662743), class = "difftime", units = "days")), row.names = c(NA,
-10L), groups = structure(list(Order = c("100016572", "100049101"
), .rows = structure(list(1:3, 4:10), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))

Comment: Don't add `rstudio` tag for questions related to only R. `rstudio` tag is reserved for questions related to the RStudio IDE.
Comment: What is RStudio IDE/
Answer: Try :
library(dplyr)

result <- df %>%
            arrange(Order, `On Time Start`) %>%
            group_by(Order) %>%
            mutate(Span.plus.Queue = as.numeric(difftime(lead(`On Time Start`),
                             `On Time Start`, units = 'days')))

Comment: is making the calculation but the results are not in the right cells,  needs to be shifted up by one cell. See the picture.
Comment: The code ran, but the results need to be shifted up by one up. In the picture you can see it.  That is the only part i am missing
Comment: @JavierPrieto Can you check my updated answer.
Answer: I hope you get what you want with this. Here, mydf is your data frame.
attach(mydf)
#Sort with ascending order
mydf[order(Order,`On Time Start`),]

#Add the new column for the delta and assigned NAs as initial values
mydf$Span.plus.Queue = NA_real_

#Compute the delta in days, and store the result in the new column
k = 1:nrow(mydf)
mydf$Span.plus.Queue[k]= ifelse(Order[k]== Order[k+1], difftime(`On Time Start`[k+1],`On Time Start`[k], unit = "days"), NA)
mydf

#  Order       Op `Op Desc`               `Part No`    WBS     `Work Cntr` `On Time Start`     `On Time Comp`      Span_CDay      Span.plus.Queue
   <chr>    <dbl> <chr>                   <chr>        <chr>   <chr>       <dttm>              <dttm>              <drtn>                   <dbl>
# 1 1000165~  9997 PP&C Movement / Go To ~ 2352841G1-5~ G-CUST~ 26801702    2019-05-14 16:51:08 2020-03-25 17:07:14 3.160112e+02 ~           0
# 2 1000165~  9997 PP&C Movement / Go To ~ 2352841G1-5~ G-CUST~ 26801702    2019-05-14 16:51:08 2020-03-25 17:07:14 3.160112e+02 ~           0
# 3 1000165~  9997 PP&C Movement / Go To ~ 2352841G1-5~ G-CUST~ 26801702    2019-05-14 16:51:08 2020-03-25 17:07:14 3.160112e+02 ~          NA
# 4 1000491~  8391 ASSEMBLY REWORK IAW 20~ 2352841G1    G-6M76~ CHRP0000    2020-01-16 23:02:18 2020-01-16 23:17:01 1.022275e-02 ~           0.742
# 5 1000491~  8392 MACHINE SHOP IAW 20036~ 2352841G1    G-6M76~ CHRP0000    2020-01-17 16:51:14 2020-01-17 18:24:46 6.495822e-02 ~           3.69
# 6 1000491~  8393 ASSEMBLY REWORK IAW 20~ 2352841G1    G-6M76~ CHRP0000    2020-01-21 09:18:14 2020-01-21 11:18:10 8.328715e-02 ~           0.315
# 7 1000491~  8394 PP&C REWORK IAW 200365~ 2352841G1    G-6M76~ CHRP0000    2020-01-21 16:52:08 2020-01-21 17:00:40 5.925926e-03 ~           0.747
# 8 1000491~  8395 INSPECT IAW 200365779   2352841G1    G-6M76~ CHRI0000    2020-01-22 10:47:51 2020-03-10 21:48:44 4.845895e+01 ~          48.5
# 9 1000491~  8396 ASSEMBLY REWORK IAW 20~ 2352841G1    G-6M76~ CHRP0000    2020-03-10 23:40:48 2020-03-12 11:28:42 1.491598e+00 ~           1.69
# 10 1000491~  8397 PP&C REWORK IAW 200365~ 2352841G1    G-6M76~ CHRP0000    2020-03-12 16:14:46 2020-03-12 16:16:41 1.330671e-03 ~          NA


How to swap the QListWidgetItem in QListWidget by mouse event?

Question: I would like to implement the images icon list that connect to the corresponding image. Now, I want to swap the images icon list to change their index in the list.
How can I swap the icon smoothly?
GIF Bellow:
What I want

What I have now (with ListWiget)

import sys
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import *

class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.layout = QHBoxLayout(self)
        self.label = QLabel()
        self.listwidget = QListWidget()
        self.initGUI()

    def initGUI(self):
        self.listwidget.setViewMode(QListView.IconMode)
        qPixmap = QPixmap('images/002.jpg')
        self.label.setPixmap(qPixmap)
        image_list_item = QListWidgetItem()
        icon = QIcon()
        icon.addPixmap(qPixmap, QIcon.Normal, QIcon.Off)
        image_list_item.setIcon(icon)
        self.listwidget.addItem(image_list_item)

        w = self.listwidget.sizeHintForColumn(0) + 2 * self.listwidget.frameWidth()
        self.listwidget.setFixedSize(w, 512)

        qPixmap = QPixmap('images/003.jpg')
        image_list_item = QListWidgetItem()
        icon = QIcon()
        icon.addPixmap(qPixmap, QIcon.Normal, QIcon.Off)
        image_list_item.setIcon(icon)
        self.listwidget.addItem(image_list_item)

        self.layout.addWidget(self.listwidget)
        self.layout.addWidget(self.label)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

Answer: You do need to set ViewMode and DragDropMode.
Just add these lines below to the initGUI method:
self.listwidget.setViewMode(QListView.ListMode)
self.listwidget.setDragDropMode(QAbstractItemView.InternalMove)


Task related to well-order and topology 2

Question: I have exam in 3 days.And this task was in the prep task list for exam.I have no idea from which perspective I can solve it... But maybe I think this problem can be solved using ordinals.
Let A be a Well-order and B ⊂ A.It's known that for any x,y ∈ B if x < y, than exists z ∉ B, such as x < z < y...and for any x ∈ B, y ∉ B, if y < x, than exists z ∉ B,such as y < z < x. Proof that any element in B is limit element.
Comment: Do not just repost your question if it gets closed: [Task related to well-order and topology](https://math.stackexchange.com/questions/4128020/task-related-to-well-order-and-topology) Improve the original question instead.
Answer: Let $x \in B$
Assume $x$ has a predecessor $y$. If $y \in B$, then there must be $z\notin B$ with $y<z<x$. This cannot be, since $x$ is the successor of $y$. Likewise, if $y \notin B$, there must be $z\notin B$ such that $y<z<x$. Again, this cannot be.
Therefore, $x$ is a limit element


(temporary) Change in vocal range after straining my voice

Question: I have noticed that when I strain my voice (intense, hmmm, singing as a part of the public in a rock concert for instance), the next day my vocal range extends greatly in the low range (I'm almost gaining an octave sometimes), at the cost of having a harder time to sing precisely high pitched notes: the voice is shaking, but I can still sing as high pitched as usual. I have a number of questions regarding this:

What is the physiological reason behind the change or range ? How are my vocal chords affected ?
Is this a bad idea ? My gut feeling is that it doesn't do good to my voice, but I don't really know in fact.
What can I do to mitigate that, after the fact ? (I get that avoiding to shout too much in the first place is probably a good idea)
Bonus question: is there any way I can get the extension of the vocal range in the low frequencies while keeping my ability to sing in the high frequency range ?

If that has any part to play, I am a tenor.
Comment: Whatever the voice you have is the one you have, and it cannot be physically changed. Get used to the idea to prevent further harm. After that you can learn of mechanics of voice, and figure out _relatively_ harmless ways to change your range, such as breathing glycerol vapor.
Comment: @polkovnikov.ph - I doubt what you say is true when my mother reports that she "wrecked her voice" when younger and my range has actually still been gaining low notes (the G# below the C below Middle C has been becoming increasingly convincing this year) and I am scrambling to keep my high notes even though I already turned 30 (I have notably lost the ability to sing the highest note of Christine's part in "The Phantom of the Opera" (song) since I was young, and I keep checking whether I can still hit the C two octaves above Middle C - so far, I still can).
Comment: An edit to refocus into one question might keep this open. Something like "Can I (ab)use straining my voice to safely increase my range?" might work?
Answer:
Straining your voice means you are causing small damage to your vocal cords. This triggers a healing reaction which causes a higher circulation and thus causes some swelling (similar to for example when you have an infection). This then increases the mass of your vocal cords and thus lower the range of your voice.

Putting some strain on your voice occasionally will heal well and probably not cause lots of problems. It gets dangerous when you strain your voice too hard or if you do it very frequently, eventually even not leaving enough time to heal. This can eventually lead to damage to your vocal cords that either requires operation or even cannot be completely healed at all. This might drastically reduce your usuable vocal range and your vocal stability! For example straining your voice too much can cause those vocal cords nodules, which are something like callusses for your vocal cords.

There are multiple things that cause vocal cord strain. Simply singing high notes will strain your voice. So to some extent you need to be pragmatic with how much you want to use your voice. But such strain can be mitigated a lot by using proper technique. Even in harsh vocals (metal growls &c.) there is a correct way to do it that affects the voice as little as possible and there are "wrong" ways to do it that can cause immense amounts of strain. Similarly shouting can be done with good technique.

Technique will allow you to extend you voice in both directions to some extent. But it cannot make your vocal cords longer/shorter or heavier/lighter. So the amount of range you can gain by this will be less and require more work than this magical "suddenly my voice is a fifth lower". Of course there are the old tricks like breathing gas that is lighter than air (making the voice higher) or heavier than air (making the voice lower).

Bonus answer: While this swelling does make your voice lower it does not mean you should use this as a means. Because this also means that your vocal cords are slightly hurt and should be strained as little as possible so that they can heal properly. Especially trying to sing particularly high notes is not a very good idea in such a situation.
Comment: vocal chords = C-E♭-G, D-F♯-A when sung. vocal cords = those things in your neck that vibrate to make noise.
Comment: Thanks for the explanations and advice, it makes sense !
Comment: @shoover You're right. But then, essentially it is just a different spelling for the same word. Blame the english language for being inconsistent ...
Comment: It may sound the same, but they aren't the same word.  "Cord" has a completely different meaning than "chord."
Comment: @aparente001 "Cord" from french "Corde" from latin "corda", which is an alternative spelling to latin "chorda" from greek "khorde". Originally means a (gut) string. Meanwhile "Chord" from latin "chorda" from greek "khorde". Means as much as a string, just in musical, geometric or anatomical context. So essentially just different spellings of the same word.


How can i copy rows while creating?

Question: Greetings to everyone,
I am checking the questions about copying rows but i couldn't find a solution or i am searching wrong.
I am trying to upload multiple files and store some informations in 2 tables which rows are created at the same time while upload process.
I have 2 tables called "media" and "pmedia" structures are;
CREATE TABLE IF NOT EXISTS `media` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `product_id` int(1) unsigned NOT NULL default '0',
  `media_id` int(1) unsigned NOT NULL default '0',
  `ordering` int(2) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  UNIQUE KEY `i_product_id` (`product_id`,`media_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=267 ;

and
CREATE TABLE IF NOT EXISTS `pmedia` (;
  `media_id` int(11) unsigned NOT NULL auto_increment,
  `file_title` char(126) NOT NULL default '',
  `file_mimetype` char(64) NOT NULL default '',
  PRIMARY KEY  (`media_id`),
  KEY `i_vendor_id` (`vendor_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=274 ;

I am uploading multiple images to "pmedia" which there is no problem with;
$query="INSERT into pmedia (`file_title`,`file_mimetype`) VALUES ('$file_name','$file_type') ; ";

But at the same time i want those uploaded files' Auto Increated column "media_id" also copied to "media" table..
Result should be after upload;

EDIT2 :
Ok guys that was the loop itself. I just made a write mistake. The below code works by the help and inspiration of Ruly and gaRex. Thank you so so much.
EDIT :
Here is the structure, and sorry for missing explanation. (I am not trying to do that in single query.)
How should i implement the loop? In this way it only writes the uploaded data only to pmedia.
<?php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
    $file_name = $_FILES['files']['name'][$key];
    $file_size =$_FILES['files']['size'][$key];
    $file_tmp =$_FILES['files']['tmp_name'][$key];
    $file_type=$_FILES['files']['type'][$key];

    if($file_size > 2097152){
        $errors[]='File size must be less than 2 MB';
    }

        $query="INSERT into pmedia (`file_title`,`file_mimetype`) VALUES ('$file_name','$file_type') ; ";
        $media_id = mysql_insert_id();

        $query2="INSERT into media (`media_id`) VALUES ($media_id) ; ";

    $desired_dir="user_data";
    if(empty($errors)==true){
        if(is_dir($desired_dir)==false){
            mkdir("$desired_dir", 0700);        // Create directory if it does not exist
        }
        if(is_dir("$desired_dir/".$file_name)==false){
            move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
        }else{                                  // rename the file if another one exist
            $new_dir="$desired_dir/".$file_name.time();
             rename($file_tmp,$new_dir) ;
        }
     mysql_query($query);
     mysql_query($query2);

    }else{
            print_r($errors);
    }
}
if(empty($error)){
    echo "Success";

} }
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>
</form>

Answer: There is 2 way to do that:

Run multiple query
After execute:
$query="INSERT into pmedia (`file_title`,`file_mimetype`) VALUES ('$file_name','$file_type') ; ";

Get the id for new record, use mysqli_insert_id
http://www.php.net/manual/en/mysqli.insert-id.php
Then execute:
$query="INSERT into media (`id`,`product_id`, `media_id`, `ordering`) VALUES ($id, $product_id, $media_id, $ordering) ; ";

Use trigger, but for this case I'm sure since I think think you can get the value of id, product_id, ordering from pmedia table

EDIT:
To add several rows, you should have a loop, and in the loop you should do those three steps. The code should be like this:
// Looping {
    $query="INSERT into pmedia (`file_title`,`file_mimetype`) VALUES ('$file_name','$file_type') ; ";

    $media_id = mysqli_insert_id($conn);

    $query="INSERT into media (`id`,`product_id`, `media_id`, `ordering`) VALUES ($id, $product_id, $media_id, $ordering) ; ";
// } Looping

Comment: Greetings Ruly;
Thanks for your help, but as far as i can understand mysqli_insert_id gets only the last record. I'm trying to make multiple uploads. I tried triggering before, i tried every way but no luck with that.
Comment: Correct, it only get the last new id, so if you want to insert several images, then you should loop the query right? And every time you run the query, get the last id, and run the second query. Look at the edited code above
Comment: Thanks for the way Ruly. But i couldn't make it work. Please check the edit.
Answer: Why do you want to insert multiple rows into pmedia in one query?
Most simple and reliable way will be to insert there by one row and only then update media table.
But if you want, you can try these two ways. They both dirty:

Add to pmedia some column with unique value, that can be set outside. Let it be our lovely GUID (see google) CHAR(36). Then in script generate this value and set to each row of pmedia. After you will not need any mysql`s insert ids as you will already have them generated by you. Then you can insert into media table by referring to pmedia in your insert query.
insert into t1 (v1, v2) values ($v1, (select id from t2 where guid = $guid)), ...
Start transaction. Insert into pmedia, get last_insert_id() for last record. Then you can calculate id for first record as you now count of records.

But pls remember -- both ways are dirty and bad.
Comment: Hi gaRex, the reason i want to insert multiple rows is because i am trying to upload multiple images at the same time. "pmedia" is to collect all images for products and categories and "media" is just for products.
2nd way won't work because last_insert_id() gets only 1 row (as far as i know, i am not very good at mysql and php)
For the 1st way; i guess we should delete the GUID after copying rows to media i guess. Or maybe give another GUID for another product while copying.
Comment: Im' still not understand why do you want insert multiple rows in SINGLE query. Why dont' you want to do it in multiple queries?
Comment: After your 2nd "why", i started to think that i'm in a wrong way. :) Please forgive me but let me ask in this way and please lighten me. What is the easiest way to upload multiple images at the same time to a product? And for your previous post i am still trying to figure out how.
Comment: I was posting this questions at around 4am and i misunderstood what you wrote. I didn't want to do the process in "Single" query. I just showed in what position i am in. And i was asking what should be the next step. Sorry for my fault.

How can i copy rows while creating?


WP-API search post and pages in one request

Question: Is it possible to search for wordpress posts AND wordpress pages in ONE request using the WP-API REST API?
?
(By slug)
Answer: The pattern is right in the WP-API Documentation's 'Type' section
GET /posts?type[]=post&type[]=page
Comment: Is this still possible with WP-API v2?
Comment: I haven't used the V2 API so I'm not sure. After a quick review of the docs, it doesn't seem like there is. I'd suggest running the `posts` endpoint and see what you get back


AJAX is running correctly but doesn't display fetched data

Question: My PHP query is running fine(based on the response on firebug) but the result its giving me are [object Object] on my direct page. So I'm guessing that my problem lies on my javascript because on firebug under the response tab its retrieving all my data on my database
Here is my javascript
    function AjaxRetrieve()
            {
              var rid = document.getElementById('trg').value,
            data = {chat: uid, rid: rid, name: user};
 $.ajax({
      url: "includes/getChat.php",
      type: "GET",
      data: data,
  dataType: 'json',
   success: function(result){
     var res = $([]);

        $.each(result[0], function(key, value) {
            res = res.add($('
', {text : value}));
        });

        $("#clog").html(res);
   }
});

        }

The php script as requested is this
        $sql7 = "SELECT   message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";

    $stmt7=$con3->prepare($sql7);
    $stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
    $stmt7->execute();

  $message_query = $stmt7;

$json = array();

if($message_query->rowCount() > 0) {
    while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
        $json[] = $message_array;
    }
    echo json_encode($json);
}

I'm not that familiar yet on JQUERY/AJAX/Javascript so I'm not actually sure if what I'm doing is correct I just based some of my codes on jquery's documentation and some
 suggestions from our fellow members here
Comment: could you post the json data received on successfull ajax call
Comment: please show your json data
Comment: Show your php code and json returned...
Comment: Master @dreamweiver
Here are the response I have cut them short cause its so many
`[[{"message_content":"asdafgga","username":"ab","message_time":"2014-04-03 14:50:03","recipient":"cd"},{"message_content":"hey","username":"ab","message_time":"2014-04-03 14:50:17","recipient":"cd"}]]`
Comment: Master @Madhu I have edited and included my php script as you have requested
Answer: Change your success callback like below, you have an array of objects.
   success: function(result){
        var container = $("#clog");

        $.each(result, function(i, message) {
            $.each(message, function(key, value) {
                container.append($('
').html(key + ':' + value));
            });
        });
   }

Edit:
And you have to change fetchAll to fetch in you while loop.
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
    $json[] = $message_array;
}
echo json_encode($json);

Or just use fetchAll without while loop:
$json = $stmt7->fetch(PDO::FETCH_ASSOC);
echo json_encode($json);

Comment: Hi I used your code and the result was `0:[object Object]
1:[object Object]
2:[object Object]`
Comment: @user256009 See my edit. There is wrong place in your php code too.
Comment: this worked but is there a way for me to display my json result individually? because I need to style the username result and message result from JSON
Answer: The way your constructing the json data is wrong,try this way
$json =array();
$i=0;
if($message_query->rowCount() > 0) {
  while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
     $json[$i]= $message_array;
     $i++;
  }

echo json_encode($json);
}

Happy Coding :)
Comment: Hi this code doesn't seem to work to me I get a message that ` Array to string conversion`
Comment: @user256009: didnt notice that, try now with edited code
Comment: `[object Object]
[object Object]
[object Object]
[object Object]`
this is the output =(


What am I doing wrong in passing a struct around in C?

Question: So I am working on a project in C that requires that I pass pointers to a struct into functions. The project is structured as follows:
struct structName {
    unsigned short thing2;
    char thing1[];
};

void function_1(struct structName *s) {
    strcpy(s->thing1, "Hello");
    printf("Function 1\n%s\n\n", s->thing1); // prints correctly
}

void function_2(struct structName *s) {
    // can read thing2's value correctly
    // thing1 comes out as a series of arbitrary characters
    // I'm guessing it's an address being cast to a string or something?

    printf("Function 2\n%s\n\n", s->thing1); // prints arbitrary characters ('É·/¨')
}

int main() {
    struct structName s;
    function_1(&s);
    printf("Main\n%s\n\n", s.thing1);
    function_2(&s);
    printf("Main 2\n%s\n\n", s.thing1);
}

This code outputs the following:
Function 1
Hello

Main
Hello

Function 2
É·/¨

Main 2
É·/¨

Obviously, the program has more than just what I've written here; this is just a simplified version; so if there's anything I should check that might be causing this let me know. In all honesty I reckon it's probably just a stupid rookie error I'm making somewhere.
[EDIT: Seems like s.thing1 is being mutated in some way in the call to function_2(), since the odd value is replicated in main() - I should point out that in my program the printf()s are located right before the function call and in the first line of the function, so there's no chance that it's being written to by anything I'm doing. I've updated the example code above to show this.]
Thanks in advance!
Comment: `char thing1[];` is not valid. A flexible array member **must** be the last member of a `struct`.
Comment: Unless it's imperative to have the string stored within the struct itself, it would be more common to just have a pointer as a member of your struct, and allocate memory separately for the string.  Flexible array members require a lot of care on the part of the programmer and may not be a good choice for someone getting started with the language.
Comment: This is not valid C code. It doesn't compile.
Comment: Sorry, it is the last member in my code - will swap it now @user3386109
Comment: @NateEldredge Thank you for the advice; I'm currently using chqrlie's method but if I run into problems I'll give separate strings a try!
Comment: Did some further work and ended up being better off using a pointer to the string - thanks again!
Answer: The structure contains a flexible member at its end, if you declare a static object with this type, the length of this member will be zero, so strcpy(s->thing1, "Hello"); will have undefined behavior.
You are supposed to allocate instances of this type of structure with enough extra space to handle whatever data you wish to store into the flexible array.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct pstring {
    size_t length;
    char data[];
} pstring;

pstring *allocate_pstring(const char *s) {
    size_t length = strlen(s);
    pstring *p = malloc(sizeof(*p) + length + 1);
    if (p != NULL) {
        p->length = length;
        strcpy(p->data, s);
    }
    return p;
}

void free_pstring(pstring *p) {
    free(p);
}

int main() {
    pstring *p = allocate_pstring("Hello");
    printf("Main\n%.*s\n\n", (int)p->length, p->data);
    free_pstring(p);
    return 0;
}

Comment: @barnstorm3r: look at the example in the updated answer.
Comment: Just got it implemented; works perfectly, thanks a lot!
Comment: Okay - if I did need to have dynamic size for this, what would be the best alternative? This value is derived from user input and can be of any length.
Comment: Will do; thank you! I'm new to C so was unconsciously a bit wary of using `malloc()` since it was somewhat foreign to me, but I'll give it a look now. Thanks again!


Is it possible to make the Book Outline a mandatory field when creating a new book page?

Question: I would like to make sure that certain content types always have a parent book/page.
Is there a way to do this, by JavaScript, by modifying the book module or whatever?
Answer: EDIT: On review, I see this question is D7 specific. There may be subtle things wrong with my code snippet. It should be fundamentally the same.
If something should never happen, I prefer to make it never-an-option.
If you want to make all book pages default to being new books:
<code>/**
 * Implementation of hook_form_FORM_ID_alter() for node_form.
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  if (book_type_is_allowed($form['#node']->type)) {
    // Remove the "none" option.
    unset($form['book']['bid']['#options'][0]);
  }
}
</code>
Once that's done, you can leave it be or set <code>$form['book']['bid']['#default_value']</code> explicitly to be a new book, or a specified book bid of your choice. It will probably naturally fall into creating new books, as that is the first option in the selector after you remove none.
Comment: The reason why I can't use this its because children will be creating pages and I can't trust them to always choose the right book unless it's right in front of their eyes and even then it's probably not going to work 100%
Comment: Choosing the right book is a related question, but I'd call them completely different issues. The accepted answer achieves basically the same thing by warning them off from the option you don't like, instead of preempting the problem by removing the option.
Answer: Yes, it is possible to do it, without to modify book.module. (Modifying Drupal files is never a good idea.)
You can create a custom module that contains code similar to the following:
<code>/**
 * Implements hook_BASE_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['book']['bid'])) {
    $form['book']['bid']['#element_validate'][] = 'mymodule_book_validate';
  }
}

/**
 * Form validation handler for book_form_node_form_alter().
 */
function mymodule_book_validate($element, $form_state) {
  // Check other conditions you need to check.
  if ($element['#value'] == 0) {
    form_error($element, t('You must select a book.'));
  }
}
</code>
The code I wrote allows you to check other conditions before to report the error; for example, you could allow users with the permission to administer books to not assign a book to the book page. You could also verify other conditions like the node title, the permissions assigned to the user who is creating the book page, the presence of keywords in the text used as body of the node, etc.
Comment: @Spre3: I forgot to add `[]`. `$form['book']['bid']['#element_validate']` is an array; that is the reason why you get that error when you replace its value with a string. I fixed my answer. I apologize for not having noticed before the code I wrote was not correct.
Comment: Hey, I tried creating a new module called booktest and, when I save a book page without a parent I get the error: "Warning: Invalid argument supplied for foreach() in _form_validate() (line 1336 of /Applications/MAMP/htdocs/drupal-7.0test/includes/form.inc)." Any idea what it could be?
Comment: @Spre3: Usually that means the code changed a value that Drupal is expecting to be an array with a value of a different datatype.
Comment: the error is coming from the line:  "$form['book']['bid']['#element_validate'] = 'booktest_book_validate';"
is this line meant to assign the validation function to that element of the form? I dont understand it.
Comment: Fantastic, that worked! Also had to change if ($element['#value'] == t('none')) to if ($element['#value'] == "0") and it's now working, thanks a lot!


Rails: Passing a variable from one controller to another for two forms

Question: I have two models: one for patient and one for referral request. I've created two forms - one that allows a user to create a new patient and another that allows a user to create a referral request. A patient can have many referral requests, and and a referral request will belong to the user who created it as well as the patient it is created for.
I am having trouble figuring out how to link these forms together in a way that creates the association between the patient and the referral request being created for them by the user. I think I have to put something in the new or create actions of the referral requests controller, but I can't get anything I've tried to work.
Any help appreciated for a rookie!
Patients Controller:
class PatientsController < ApplicationController

def new
    @patient = current_user.patients.build
end

def create
    @patient = current_user.patients.build(patient_params)
    if @patient.save
        flash[:success] = "Patient Created!"
        redirect_to '/referral_requests/new'
    else
        Rails.logger.info(@patient.errors.inspect)
        render 'patients/new'
end
end

private

def patient_params
    params.require(:patient).permit(:age, :user_id, insurance_ids: [], gender_ids: [], concern_ids: [], race_ids: [])

end
end

Referal Requests Controller:
class ReferralRequestsController < ApplicationController
    before_action :logged_in_user, only: [:show, :index, :new, :create, :edit, :update, :destroy]

    def index
        if logged_in?
        @referral_request = current_user.referral_requests.build
        @feed_items = current_user.feed.paginate(page: params[:page])
    else
        @feed_items =[]

    end
end

    def create
        @referral_request = current_user.referral_requests.build(referral_request_params)
        if @referral_request.save
            flash[:success] = "Referral Request Created!"
            render 'referral_requests/index'
         else
    Rails.logger.info(@referral_request.errors.inspect)
      @feed_items = []
      render 'static_pages/home'

    end
  end

    def destroy
    end

    def new
    @referral_request = current_user.referral_requests.build if logged_in?
    end

private

def referral_request_params
    params.require(:referral_request).permit(:content, concern_ids: [],
     insurance_ids: [], race_ids: [], language_ids: [], gender_ids: [])

end
end

Answer: you need to pass in the patient_id in your redirect in the create action of PatientsController.
redirect_to '/referral_requests/new'
should become
redirect_to new_referral_request_path(patient_id: @patient.id)
then in ReferralRequestsController you can associate the newly built referral_request with the patient
def new
  @patient = Patient.find(params[:patient_id])
  @referral_request = current_user.referral_requests.build(patient: @patient) if logged_in?
end

Then in your referral_requests/new.html.erb form you can add a hidden_field_tag
form_for(@referral_request) do |f|
  f.hidden_field :patient_id
  .....
end

which will then add patient_id to into the form params and pickup the patient_id that got associated in the new action of the controller
You will need to add :patient_id into your referral_request_params method as well


ckedittor automcalliy convert <

Question: When I copy a link and put into CKeditor (drupal)

After I switch back plain text it changed to be like this:

<iframe width="420" height="315" src="//www.youtube.com/embed/q4Rgh5JNWf4" frameborder="0" allowfullscreen></iframe>

How can I solve this?
Answer: First put your text format to Plain Text mode and then paste your  code on the editor, now you switch back to "Full HTML" or "Filtered HTML" mode (for which your text editor is set to display).
Hope this is what you are looking for. Hope this helps. :)
Comment: Also check that your input format allows iframes.
Answer: Click 'Source' on CkEditor menu and paste the HTML code in source of the CK Editor and make sure to put  Text Format in Full HTML mode.

ckedittor automcalliy convert <