Prepared Statement Syntax Error

Question: There are 3 tables in a sales database: orders(order_id, user_id, item_id, quantity, date), users(user_id, name, discount_percent) and items(item_id, name, type, price). I'm trying to generate a report for the monthly profit by user grouped by days that must look this (snippet):
|-------user--------|----------day_1--------|---------day_2---------|---------day_3---------| etc. |

|-user_name_1-|-sum_of_expenses-|-sum_of_expenses-|-sum_of_expenses-| etc. |

|-user_name_2-|-sum_of_expenses-|-sum_of_expenses-|-sum_of_expenses-| etc. |

I used the following prepared statement to achieve this:
SELECT
    GROUP_CONCAT(DISTINCT CONCAT('SUM(IF(DATE(orders.date) = \'',
                DATE(orders.date),
                '\', orders.quantity * items.price * (1 - users.discount_percent / 100), 0)) AS ',
                DATE(orders.date))
        ORDER BY DATE(orders.date))
INTO @sql FROM
    orders;
SET @sql = CONCAT('SELECT users.name, ', @sql, ' FROM
    users
        INNER JOIN
    orders ON users.user_id = orders.user_id
        INNER JOIN
    items ON orders.item_id = items.item_id
GROUP BY users.name
ORDER BY users.user_id');

PREPARE statement FROM @sql;
EXECUTE statement;
DEALLOCATE PREPARE statement;

For some reason it gives me a warning:
1 row(s) affected, 1 warning(s): 1260 Row 8 was cut by GROUP_CONCAT()

And then an error:
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2015-01-01,SUM(IF(DATE(orders.date) = '2015-01-02', orders.quantity * items.pric' at line 1

I think this has something to do with the format of the date or the quotes, but everything I type in order to fix it fails.
Also I'm trying to figure out how to implement this complex statement via php's mysqli prepare() method.
Comment: I don't think that `SELECT ... INTO` a variable will work directly on MySQL.  But why are you overwriting `@sql` right after assigning something to it?
Answer: For the first warning, MySql group_concat function is limited by default to 1024.
You can increase the limit before your query by using:
SET @@group_concat_max_len = 32000;

Answer: Any time you have a syntax error in SQL, it's much easier to find the problem by looking at the final SQL that was generated—not the code used to generate the SQL.
In this case, I think you'll find that the column alias you're defining lacks quotes:
SUM(IF(DATE(orders.date) = '2015-01-01',
       orders.quantity * items.price * (1 - users.discount_percent / 100),
       0)
) AS 2015-01-01

That's not a legal column alias. You must put quotes around it.
I recommend you use the QUOTE() function as you create your prepared SQL statement:
SELECT
GROUP_CONCAT(DISTINCT CONCAT('SUM(IF(DATE(orders.date) = ',
            QUOTE(DATE(orders.date)),
            ', orders.quantity * items.price * (1 - users.discount_percent / 100), 0)) AS ',
            QUOTE(DATE(orders.date)))
    ORDER BY DATE(orders.date))
INTO @sql FROM
orders;

Prepared Statement Syntax Error


Problema ao verificar dado em tabela SQL

Question: Tenho o banco de dados ragnarok com a tabela login que tem o userid (usuario) e a user_pass (senha) da pessoa.
Estou tentando fazer com que o sistema entre nessa tabela e verifique se o campo digitado no formulario confere com o que está na database, porém, o php está retornando sempre como se eu tivesse diigtado o campo incorreto, sendo que eu estou digitando corretamente...
Código php:
$query = "SELECT 'user_pass' FROM `login` WHERE userid = '".$_SESSION["userid"]."'  ";
    $resultado = mysqli_query($conexao, $query) or die(mysqli_error($conexao));
    $campo = mysqli_fetch_array($resultado);
    if($campo)
    {
            echo "
Senha atual errada!
";
    }

Não sei mais o que fazer..
Comment: Tente assim: `$user = $_SESSION["userid"]; $query = "SELECT user_pass FROM login WHERE userid = '$user'";`, lembrando que quando você usar aspas, para adicionar uma variável a string não é necessário quebrar ela; e complementar com o resto da verificação de senha, etc... é com você...
Comment: Você quer fazer um sistema de login? Essa query está buscando pelo id do usuário e não login/senha.
Comment: RESOLVIDO! utilizei o código do @RafaelWithoeft. Estava dando errado pois eu utilizei na query SELECT 'user_pass' ao inves de SELECT user_pass. Muito obrigado a todos que ajudaram! Querem que eu faça uma resposta com o código correto?
Comment: @Guilherme seria interessante e marque-a como certa depois assim outros que acessarem poderão ver como foi resolvido.
Comment: Certo! Farei assim qur chegar em casa @Rafael
Comment: Luis, sistema de recuperacao de senha :x
Answer: Utilizei o código do comentário do @RafaelWithoeft. Estava dando errado pois eu utilizei a query SELECT 'user_pass' ao invés de SELECT user_pass. Muito obrigado a todos que ajudaram!


Object reference not set to an instance of an object

Question: Estou aprendendo a fazer App utilizando o Xamarin 2017, e quando tento fazer a conexão com a base de dados que criei via SQLite, a aplicação apresenta esse erro:

Object reference not set to an instance of an object.

Como eu poderia arrumar isso?
O erro se dá nesse ponto:
public UsuarioDataAccess()
{
    database = DependencyService
            .Get<IDatabaseConnection>()
            .ConexaoDatabase();
    database.CreateTable<Usuario>();

Comment: Ele só da problema quando faço isso.. e é essa a mensagem que aparece quando eu dou o debug
Comment: é a variável `database` aonde dá esse erro?
Comment: Exatamente. Nao sei o que fazer...
Comment: Tem que verificar com um debug porque essa linha `DependencyService            .Get().ConexaoDatabase();` não está retornando uma conexão de banco, já tentou fazer isso ... ???
Comment: Você criou a classe que implementa a interface IDatabaseConnection?
Answer: O objetivo do DependencyService é facilitar a criação de APP que acesse API's específicas de cada plataforma (Android, IOS, Windows Mobile, etc).
Se o estudo que você estiver fazendo não necessitar dessa portabilidade, você poderá instanciar direto o objeto da classe que implementa IDatabaseConnection sem usar DependencyService.
database = (new CLASSE_QUE_IMPLEMENTA_IDatabaseConnection()).ConexaoDatabase();
database.CreateTable<Usuario>();

Agora, se você for usar DependencyService, será necessário implementar 3 coisas em seu projeto:
1) Definir a interface
public interface IDatabaseConnection
{
    MinhaClasseConexao ConexaoDatabase();
}

2) Criar a classe que implemente a interface
public class DatabaseConnectionImplementacao : IDatabaseConnection
{
   // implementar código da classe
}

3) Registrar a classe que implementa a interface;
//registrar a classe usando um atributo do namespace da classe
[assembly: Xamarin.Forms.Dependency (typeof (DatabaseConnectionImplementacao ))]
namespace MeuApp.Android
{
   public class DatabaseConnectionImplementacao : IDatabaseConnection
   {
      // implementar código da classe
   }
}

Veja: Introduction to DependencyService
Pela descrição do seu problema, você deve ter feito o primeiro passo mas não implementou os outros dois.


Do ol.Overlay and ol.layer.Vector have a up-down order?

Question: For openlayers3, is there a up-down order between ol.Overlay and ol.layer?
I draw the overlay and layer on the same map, and I want to the location layer above the hotspot type overlay.
So how to do this?
Answer:
is there a up-down order between ol.Overlay and ol.layer?

No. As it is there's no way to solve this. Between ol.Overlay's you can use DOM z-index to control their order.
Between ol.layer.Vector's you can setZIndex to control their order.

So how to do this?

Don't use ol.Overlay for this. Use a different (not mandatory) ol.layer.Vector to add your markers.


Multiple models generic ListView to template

Question: What is the SIMPLEST method for getting 2 models to be listed in a generic IndexView? My two models are CharacterSeries and CharacterUniverse.
My views.py
    from .models import CharacterSeries, CharacterUniverse

    class IndexView(generic.ListView):
        template_name = 'character/index.html'
        context_object_name = 'character_series_list'

        def get_queryset(self):
            return CharacterSeries.objects.order_by('name')

I need to know the shortest and most elegant code. Looked a lot but don't want to use mixins. I am perhaps not being pointed in the right direction.
Thanks all.
Answer: You can pass the one queryset in as context on the ListView like this,
class IndexView(generic.ListView):
    template_name = 'character/index.html'
    context_object_name = 'character_series_list'
    model = CharacterSeries

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context.update({
            'character_universe_list': CharacterUniverse.objects.order_by('name'),
            'more_context': Model.objects.all(),
        })
        return context

    def get_queryset(self):
        return CharacterSeries.objects.order_by('name')

Comment: It's just personal preference, I just prefer using context.update, instead of context['value'], both methods does exactly the same.
Comment: If you want to pass in another list of you can just add to the context. in that case I would say use the context.update method as the code will at least look cleaner. I'll update my answer to show you what I'm trying to explain.
Comment: I will look at your answer; I just posted an answer to my own before reading this. Thanks. Will discuss.
Comment: My method worked without the ``context.update`` part.. Can you please explain? Thanks.
Comment: quick question for the future. How about 3 models? Can we just use the ``get_context_data`` over and over for more models?
Comment: Fantastic info; will just keep adding to the context.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/81952/discussion-between-klandshome-and-pieter-hamman).
Comment: I want to do pagination on both models. Can that be accommodated?
Comment: @sureshvv - Did you arrive at a solution? I was also trying something like this.
Answer: https://docs.djangoproject.com/en/1.8/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.get_context_data
Sounds like a mixin is the only (right)? way. I added a get_context_data method and now it works.
Quick question how about adding more than 2 models..?
below works with the 2 models now:
class IndexView(generic.ListView):
    template_name = 'character/index.html'
    context_object_name = 'character_series_list'

    def get_queryset(self):
        return CharacterSeries.objects.order_by('name')

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['character_universe_list'] = CharacterUniverse.objects.order_by('name')
        return context


Using string interpolation in React.js regex function

Question: I am having some issues using string interpolation in a regex, however I have also tried to log it to the console and I can see that I am doing it incorrectly.
I am trying to loop through an array of weather types to see if my API request returned a type of weather which requires me to add a class to one of my elements in the UI.
I iniitally thought the issue was using array[x] in the regex, but I have assigned this to a variable p and am still getting the same result.
let weatherTypes = ['rain', 'clouds', 'snow', 'clear', 'thunderstorm'];

for (var x= 0; x <= weatherTypes.length; x++) {
    let p = weatherTypes[x];
    console.log(p)
    var searchPattern = `/${p}/i`;
    var result = this.state.description.match(searchPattern);

    console.log(`splash--weather-${p}`);

    if(result !== null) {
        var element = document.getElementById("splashContact");
        element.classList.add(`splash--weather-${weatherTypes[0]}` );
    }
}

The logic to add the class works when I abstract it out of the for loop so I know that part is working fine.
Can somebody please point me in the right direction?
edit Have now used backticks instead of quotation marks
Comment: You should use the back ticks instead of the quotation marks. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
And BTW, why are you manually manipulating the DOM, if it's allegedly a React project?
Comment: @mbojko hey perfect thank you - would I have to enclose the search pattern in back ticks? And any suggestions on how to add a class without manipulating the DOM - incredibly new to React :)
Answer: searchPattern is a string so you just need to use the RegExp constructor before using it.
var searchPattern = `${p}/i`;
var searchPatternRegex = RegExp(`${searchPattern}`);


Largest possible solution for equation

Question: I have the following equation
$$x^2=n^2+2016n, n>0$$
The questions wants to find the largest possible integer value for n. I have tried solving using difference of squares but it doesn't lead anywhere (substituting into '2016')
$$x^2-n^2 = 2016n$$
$$(x-n)(x+n)=2016n$$
Alternatively, I have tried isolating x but that doesn't work either
$$x^2 + 1008^2=n^2+2016n+1008^2$$
$$x^2 + 1016064=(n+1008)^2$$
$$x= \sqrt{(n+1008)^2-1016064}$$
And since that's derived from the initial, subbing it back into the initial doesn't help. Is there any other way/continuation to the problem or to construct another equation (thus solving with simultaneous eq.)? Thank you for your help!
Answer: $x= \sqrt{(n+1008)^2-1016064}$ works wonders, you just have to think a bit about what it says.
It says that you can take the square number $(n+1008)^2$, subtract the number $1016064$, then you get a new perfect square.
The distance between square numbers increase as the numbers themselves increase, and they increase quite predictably. The distance between consecutive squares actually follow the odd numbers.
So, back to your problem, we want $n$, and by extension, $(n+1008)^2$ to be as large as possible. The limitation is that there has to be another square number $1016064$ below it, and it has to be as "adjacent" as possible. Now, it can't be the previous square, because then the difference would be odd. But it can be the one before that, namely $(n+1008 - 2)^2 = (n+1006)^2$. So, we want
$$
(n+1008)^2 - 1016064 = (n+1006)^2\\
n^2 + 2016n = n^2 + 2012n + 1012036\\
4n = 1012036\\
n = 253009
$$

Largest possible solution for equation


C# Statement Tokens

Question: Somewhere I've read:

Statements are formed from tokens. These tokens can be keywords, identifiers (variables), operators, and the statement terminator which is the semicolon (;).

I was wondering, are these the only "tokens" from which C# statements are formed? Are there any other that are not mentioned?
Comment: yes. proton electron and neutrons. xD
Comment: https://msdn.microsoft.com/en-us/library/ms173143.aspx
Comment: Literals seem to be missing, and I wonder if `()` is an operator. This quote seems to be informal, just take it with a grain of salt.
Answer: It is the way a compiler writer would talk about statements. the tokens are generated by the lexer (aka lexical analyzer), the parser interprets them to parse valid statements. Not specific to the C# language, just about any language works that way.  Literals are missing from your list, comments and end-of-file can be tokens.
Specific to the C# compiler, its source is readily available today, there is no keyword token but each keyword is a token by itself.  Like TID_FOR for the "for" keyword and TID_BYTE for the "byte" keyword, etcetera. There are four kinds of literal tokens: number, string, string with @ and character.  Four kind of comments: single line, multiline, /// single and /// multiline.
The C# lexer does not classify operators, just the characters that build them up.  Necessary because, say, '[' and ']' can mean different things (indexing operator vs attribute declaration).  The parser figures out which interpretation is the correct one based on the parser state.
C# has contextual keywords, like "yield".  Classified as a regular identifier by the lexer, the parser recognizes it when it sees it followed by "return".  Contextual keywords are good because they avoid breaking a program that accidentally uses "yield" as a variable name.  It was the way they could add "async" and "await" to version 5 without breaking existing programs.

C# Statement Tokens


div above another div, but should scroll beneath the later one

Question: there is a div (namely div_fixed) which is  fixed in position. Another div namely other_content is beneath the div_fixed. The other_content div has a padding-top property  so that when the page is scrolled only the other_content is scrolled beneath the fixed div.
The fiddle is here
HTML :

FIXED

    content goes here

    content goes here

    content goes here

CSS:
     div { color: #fff }
        .div_fixed { position: fixed;
    width: 100%;
    height: 100px;

    }

.other_content {
background: #f00;
height: 5000px;
color: #fff;
padding-top: 100px;

margin:0 auto;

}

But I want the non-fixed div to stay upon the fixed div and want the non-fixed div to disappear just beneath its upper edge i.e. position of the non-fixed div's upper edge will remain fixed but it's content will start disappearing on page scroll just the way it happened when it was staying beneath the fixed div.
So i had a little edit in the html ( just 2 breaks) before the non-fixed div :

FIXED

            content goes here

            content goes here

            content goes here

The addition in css is:
  .fixed_div{

    z-index:-1;
    }

    .other_content{

    width:60%;
    z-index:99099900;

    }

But the upper edge of the non-fixed div does not stay at the position I want.
How to achieve that ?
EDIT :
suppose I add a background image  for the non-fixed div. Is it possible that part of  background image of the fixed  div over which the other div will scroll will have a z-index higher than that of the non-fixed div ? Will the problem be solved in that way ?
EDIT2
Let use suppose that fixed_div is the header, other_content is the content body of a webpage. Let us add a footer div with id footer. No scroll should be present in other_content. other_content should scroll when the page is scrolled.
Comment: not based on this question,I want to achieve the effect shown in your fiddle ,for some reason I can't seem to achieve it,can u help me?
Comment: it seems i forgot to set background color for the fixed element fixed it
Answer: I think this is what you're looking for. You'll want to position the fixed div in a fixed fashion, but the second div doesn't need special positioning. Just give it a margin-top:100px where 100px is the height of the fixed div.
The trick is to use z-index and to add position:relative; to the content div
Working Demo: http://jsfiddle.net/KyP8L/3/
.div_fixed{
    height:100px;
    width:100%;
    position:fixed;
    top:0;
    left:0;
    background:#ff0;
    z-index:500;
}
.other_content {
    width:60%;
    background:#0ff;
    margin-top:100px;
    z-index:600;
    position:relative;
}

Comment: what change did it make ? width of the `other_content` div should be 60%. In that case the non-fixed div does not seem to stay on the fixed one ?
Comment: `other_content` should stay above `fixed_div`. jsfiddle does not show that.
Comment: When you say above, you mean closer to the user on the z-axis? Here you go: http://jsfiddle.net/KyP8L/3/  - the trick is to use `z-index` and to add `position:relative;` to the content div.
Comment: now this is 'above'. But the `other_content` should be staying on the `fixed_div` and the upper edge should be a bit down to that of the `fixed_div`  .
Comment: You'll need to explain what you want a bit better, or show me an example or illustration.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/22114/discussion-between-istiaque-ahmed-and-dutchie432)
Comment: the jsfiddle solution if taken in pc browser as a normal web page, it does not work..
Answer: One option would be to wrap the content div in another container with a fixed position.
For example:
HTML:

FIXED

        content goes here

        content goes here

        content goes here

CSS:
.fixed_container {
    position: fixed;
    overflow: auto;
    top:30px;
    width: 100%;
    height: 5000px;
    z-index:10; }

.other_content { position: absolute; }

Demo: http://jsfiddle.net/xmKMs/
Comment: what about the disappearance of the upper edge of the `other_content` in the expected way ?
Comment: why `padding-top:100px` for the `other_content` ?
Comment: That's just what you had in your original example.  That could be removed if necessary.
Comment: try reducing the height and increasing the amount of content: http://jsfiddle.net/xmKMs/
Comment: the scroll bar in for the scrolling div is not wanted. When the web page is scrolled the scrolling div should also scroll... Looking for the solution


Prevent enabling module if private streamwrapper not set

Question: I need to create a subdirectory in the private files folder. I can check if the folder is available with variable_get('file_private_path', FALSE) in hook_install or hook_enable.
But how can I prevent my module from getting enabled? And preferably, I want hook_uninstall to run in case this happens so that the user can first setup the private files directory and then try again.
I played with module_disable and drupal_uninstall_modules, but (understandably) those don't seem to work if they target the module they are called from. I'm using Drupal 7.
Answer: The hook_requirements(), what do you need.
Implement it your own modules .install phase. Here is an example from one of my module: http://drupalcode.org/project/jquery_localscroll.git/blob/refs/heads/7.x-1.x:/jquery_localscroll.install#l20
Comment: Excellent, and thank you for including some of your own code.


What tests for dependent variables for Likert scale outcomes?

Question: My dependent variable is Likert data (strongly agree, agree, neutral, disagree, strongly disagree).
My independent variables include age and 3 categorical variables (one has 3 levels, two are binomial).
I want to see which independent variables are associated differences in agreement with X, Y, and Z statements. Would I first run a Pearson's chi-square for test of independence for each statement for each independent variable? Or should I do an ordinal logistic regression? I would also like to say something like older people are more likely to strongly disagree/disagree with this statement.
I don't mind turning age into a categorical variable and I don't mind condensing my Likert data into strongly/agree vs. neutral vs. strongly disagree/disagree.
I'm obviously a non-statistician and am drawing from minimal experience during college years ago! I would appreciate any help I could get.
Answer: You can run ordinal regression models (e.g., ordinal logistic or probit regression) to examine the relationships between the covariates and your outcome. Standard ordinal regression models work by assuming there is an underlying, unobserved continuous variable (in your case, agreement) that has been discretized into several bins at various thresholds. These methods model the relationship between this underlying variable and the predictors you've specified. The coefficients can be interpreted as the effect of the predictors on the underlying outcome, just like in standard regression, though there are some additional interpretational complexities with this practice.
With two predictors, you can run univariable and multivariable regression models. Univariable regression models answer the question of to what degree the predictor is associated with the outcome. Multivariable regression models answer the question of to what degree each predictor is associated with the outcome over and above the other predictor(s).
See Bürkner and Vuorre (2019) for a nice introduction and tutorial of ordinal regression for psychology researchers.


Bound power series with kind of random coefficients by it's finite versions?

Question: Let*s define a power series:
$$
\begin{align}
p_n(x) = \sum\limits_{k=1}^n a_k x^k, \quad a_k \in \mathbb{N}
\end{align}
$$
Is it possible to give a certain bound $-1 \le x_b  \le x < 0 $ such that
$$
\begin{align}
p_n(x) &> p_{\infty}(x), \quad \text{if n is even} \\
p_n(x) &< p_{\infty}(x), \quad \text{if n is odd}
\end{align}
$$
although $a_n$ is kind of a random distributed sequence only bound between $a_n = n$ and $a_n = n^2$?
Edit: I would be happy also about a rough bound. F.e. let's say the best $x_b$ for a given $a_n$ sequence would be $-0.6$ but I would be able to say that $-0.25$ is a certain bound such that the conditions above are true.
Edit 2: With kind of randomly distributed I mean that I don't know the sequence. The values can jump up and down. I only know that this sequence is bounded. So, the "jumps" are bounded, too.
Clarification of the question: Is there any way to give a fixed $x_b$ only by the bounds such that the condition is true?
Comment: The question doesn't make much sense to me. You call $p_n$ a power series, but really it's a polynomial; did you intentionally leave off the constant term? It's not clear what $x_b$ means. Perhaps you want partial sums of a power series to alternately be upper and lower bounds on the limit, for all inputs in a certain subinterval of $[-1, 0]$? I have no idea what "although $a_n$ is kind of a random distribution sequence only bound between $a_n=n$ and $a_n=n^2$?" is trying to say. The question seems too vague to be answerable.
Comment: Thanks, indeed. I edited.
Answer: I assume that $p_n(x) = \sum_{k=1}^n a_k x^k$.
As I understood the question, there exists a feasible sequence $(a_n)$ without the bound $x_b$, because the gap between the bounds for $a_n$ is too big. Namely, let $a_n=n$ when $n$ is odd and $a_n=n^2$, when $n$ is even. Given $-1<x<0$, pick an even $n$ such that $\tfrac 1n <-x$. It is easy to check that for each positive odd $k$ we have
$$ a_{n+k}+xa_{n+k+1}=(n+k)+x(n+k+1)^2<0.$$
Then
$$p_\infty(x)-p_n(x)= \sum_{k=n+1}^\infty a_k x^k=x^{n+1}((a_{n+1}+a_{n+2}x)+ x^2(a_{n+3}+a_{n+4}x)+\dots)>0.$$
Comment: So, as I understand, your $x_b$, which depends on $n$. would be like $-\frac{1}{n}$. So there isn't any because $x$ would be go to zero as $n$ goes to infinity. There could be no other fixed $x_b$ as zero?
Comment: @thinkingeye It is more correct to say that for any $-1\le x_b p_{\infty}(x)$ is violated, so there exists no $x_b$ required in the question, as I understood it.


How to prove that $ {\displaystyle \sup_{x \in \mathbb R^n, \, r > 0} r^{-\lambda} \int_{B(x,r)} |f_\alpha(y)|^p \, dy < \infty}$?

Question: Let $1 \leqslant p < \infty$ and $0 < \lambda < n$. Consider the function $f_\alpha \colon \mathbb R^n \to \mathbb R$ defined by
$$ f_\alpha(x) := \|x\|^{\frac{\lambda - n + \alpha}{p}} \chi_{B(0,1)}(x) + \| x \|^{\frac{\lambda - n}{p}} \chi_{\mathbb R^n \setminus B(0,1)}(x), \quad \forall x \in \mathbb R^n, $$
where $\alpha > 0$ is an arbitrarily fixed constant. My goal is to show that $f_\alpha$ satisfies the following property:
$$ \sup_{x \in \mathbb R^n, \, r > 0} r^{-\lambda} \int_{B(x,r)} |f_\alpha(y)|^p \, dy < \infty. $$
My attempt. I wasn't able to make any usefull progress but I believe I should start by analysing different cases. For context, yesterday I posted a question about this same function but proving another (similar) property (see here) and there I had to consider the cases $(i) \| x \| < 2r$ and $(ii) \| x \| \geqslant 2r$ to reach the result. Here we have two varying parameters so I believe the splitting is so easy to figure out.
Thanks for any help in advance.
Comment: It is not hard to see that: $$|f_\alpha(y)|^p=\|y\|^{\lambda-n+\alpha} \chi_{(0,1)}(\|y\|)+y^{\lambda-n}\chi_{[1,\infty)}(\|y\|).$$ $f$ is already non-negative, and since the two sets are disjoint, the power  can be applied to each set  seperately. This would not be true of the sets were not disjoint, but here they are.
Comment: If you are aware of these facts, tell us first in the question, rather than waiting for me to waste my time duplicating the effort.
Comment: $f_\alpha(x)$ only depends on $\|x\|,$ and the only problem with estimates is near $0$ when $\lambda-n+\alpha<0,$ my intuition tells me.
Comment: @ThomasAndrews Thanks for your observations. All that you wrote is correct and I am aware of these facts. Do you have any idea for the initial split?
Comment: @ThomasAndrews Sorry, I didn't mean to be rude in my last comment. I appreciate every bit of help I get on MSE. Next time I will add more details to the post to be clear of what I am already aware of.
Answer: Remark: I expect the ideas below work, although I did not check thoroughly the calculations, in particular, whether they are rigorous.
For any $x\in\mathbb R^n$, $r>0$, and $y\in B(x,r)$, we have $|f_\alpha(y)|^p\le \|y\|^{\lambda-n}$.
So it suffices to show that
$$I=r^{-\lambda}\int_{B(x,r)} \|y\|^{\lambda-n} dy<\infty$$
To bound $I$ we consider two cases which you suggested.
Let $V_n$ be the volume of $B(0,1)$.
Suppose that $\|x\|\ge 2r$. Then $\|y\|\ge r$ for each $y\in B(x,r)$, so
$$I\le r^{-\lambda}\int_{B(x,r)} r^{\lambda-n} dy\le
r^{-\lambda}\cdot r^{\lambda-n}\cdot r^nV_n =V_n.$$
Suppose now that $\|x\|\le 2r$. Then $B(x,r)\subset B(0,3r)$, so
$$I\le r^{-\lambda}\int_{B(0,3r)} \|y\|^{\lambda-n} dy=
r^{-\lambda}\int_0^{3r} t^{\lambda-n} V_n nt^{n-1} dt=$$
$$nV_n r^{-\lambda}\int_0^{3r} t^{\lambda-1} dt=
nV_n r^{-\lambda}\frac {t^{\lambda}}{\lambda} {\Huge|}_0^{3r}=
nV_n r^{-\lambda}\frac {(3r)^\lambda}{\lambda} =
\frac {nV_n3^\lambda}{\lambda}.$$
Comment: Very good. Thanks.


How can I read config schema from a config entity?

Question: I need to read the schema definition from a config entity, which is located in config/schema. For example the schema from a node type defined in node.schema.yml:
<code>node.type.*:
  type: config_entity
  label: 'Content type'
  mapping:
    name:
      type: label
      label: 'Name'
    type:
      type: string
      label: 'Machine-readable name'
    description:
      type: text
      label: 'Description'
    help:
      type: text
      label: 'Explanation or submission guidelines'
    new_revision:
      type: boolean
      label: 'Whether a new revision should be created by default'
    preview_mode:
      type: integer
      label: 'Preview before submitting'
    display_submitted:
      type: boolean
      label: 'Display setting for author and date Submitted by post information'
</code>
How can I do this?
Answer: Found, it can be done by using config.typed service:
<code>$typed_config_manager = \Drupal::service('config.typed');
$node_type_definition = $typed_config_manager->getDefinition('node.type.*');
</code>


Traduzir textos do inputs do WooCommerce

Question: Instalei o WooCommerce em meu tema, porém, quando clico em Login, Sign up, tudo isso está em inglês. Como traduzir esses pequenos textos? Só consegui traduzir a loja, o painel e algumas outras coisas.
Answer: Conforme a documentação do plugin em Translating WooCommerce (Localization), estes são os passos:

definir a linguagem do site no wp-config.php
define('WPLANG', 'pt_BR');

a seguinte notificação deveria aparecer no dashboard

se não aparecer a notificação, é necessário forçar o download da tradução, indo à

WooCommerce > System Status > Tools > Force Translation Upgrade

Uma vez feito isso, o plugin é traduzido na administração e no tema (nas partes que são mostradas por ele):
Comment: Na verdade `WPLANG` foi depreciado na última versão do WordPress. O que precisa fazer mesmo é baixar os pacotes de tradução ou baixar o WordPress traduzido em http://br.wordpress.org/, depois de feito isso é possível alterar o idioma em "Configuraçoes > Geral" na opção "Idioma do site". Feito isso é só seguir do passo 2 em diante.
Comment: Obrigado, já foi !
Answer: Não consegui Forçar a atualização, conforme citado em inúmeros posts na web. Minha versão de WooCommerce é a 2.5.2, com o WP 4.4.2.
A maneira que encontrei foi baixar os arquivos de tradução do WC manualmente, e colocá-los na pasta de tradução de plugins. Estando setado o WP como pt_BR, tudo correu como esperado.
Para baixar os arquivos de tradução (.PO e .MO) em português brasileiro, basta ir ahttps://github.com/woothemes/woocommerce-language-packs/blob/master/packages/pt_BR.zip
Depois, extraia o conteúdo em wp-content/languages/plugins e o WooCommerce fica traduzido.


Script to echo out range of dates

Question: I've been trying to get a script to print out a range of dates from a start date then the day after up to the present day.
Example:
Backup-2011-06-14
Backup-2011-06-15
Backup-2011-06-16

Had a idea below but doesn't even slightly work, any ideas?
start=$(date +%F --date="2011-06-14")
echo "$start"
current=$(date +%F)
echo "$current"
end=$(date +%F)

while [ "$start" != "$current" ]; do
    echo backup-$(( $(date --date="$start" +%F) + $(date +%s --date='1 day') ))
done

Comment: Possible duplicate: http://stackoverflow.com/questions/4351282/how-to-generate-a-sequence-of-dates-given-starting-and-ending-dates-using-awk-of/4351948#4351948
Answer: Date math in bash is difficult.  But the date command does support simple addition or subtraction from today's date.  So a different approach is necessary in your case.  First, determine the number of days for which you want to output these dates, then output the dates as they relate to today's date.
#!/bin/bash
days=$(( ($(date +%s)-$(date +%s --date="2011-06-14"))/86400 ))

while [ $days -gt 0 ]; do
    echo backup-$(date --date="-$days days" +%F)
    days=$(($days-1))
done

Comment: thats great... works a charm - No I need to try to work out how to add it to my merge backup script :-(

Script to echo out range of dates


How to add position to my stock portfolio, currently getting an error about incompatible types cannot be converted to int or String

Question: I'm having trouble adding the stock to the portfolio. I have tried without new Stock, with just stock instead of stock.tickersymbol  and it still doesn't work. What would I need to change to add the stock and quantity to the positions?
The error I am getting is
error: incompatible types: Stock cannot be converted to String
error: incompatible types: Stock cannot be converted to int
      positions.add(new Stock(stock.tickerSymbol), quantity);
  positions.add(new Stock(stock), quantity);

I am trying to get this line working.
positions.add(new Stock(stock.tickerSymbol), quantity);
public boolean buy(Stock stock, int quantity, double price) {
    double total = price * quantity;

    if (cash >= total) {
        cash -= total;
        positions.add(new Stock(stock.tickerSymbol), quantity);
        return true;
    }

    return false;
}

The following is my minimum viable code
import java.io.*;
import java.util.*;
import java.util.stream.*;
import org.junit.*;
import org.junit.runner.*;
import static org.junit.Assert.*;

class Stock {

  public String tickerSymbol;

  public Stock(String tickerSymbol) {
    this.tickerSymbol = tickerSymbol;
  }

}

class Position {

  public Stock stock;
  public int quantity;

  public Position(Stock stock, int quantity) {
    this.stock = stock;
    this.quantity = quantity;
  }

}

class Portfolio {

  public double cash;
  public List<Position> positions;

  public Portfolio(double cash, List<Position> positions) {
    this.cash = cash;
    this.positions = new ArrayList<>(positions);
  }

  /*
  If the buy is viable (sufficient cash), executes it and returns true,
  else returns false
  */
  public boolean buy(Stock stock, int quantity, double price) {

    double total = price * quantity;

    if (cash >= total)
    {
      cash -=total;
      positions.add(new Stock(stock.tickerSymbol), quantity);
      return true;

    }
    return false;

  }

}

Comment: You need to post a [mcve] **and** a the exact error messages that you're getting. The code that you have posted doesn't compile and probably doesn't focus on exactly where the error occurs.
Comment: @lag where did you get this question from? I was asked this in an interview recently and I thought the interviewer made up the question. But apparently he just lifted it from somewhere!
Answer: The buy method needs to be part of the Portfolio class if it is going to access the positions variable (I'm going to go ahead and assume it is...). Then you need to define a new Position to add to the positions list, as that is a List of the object Position, not Stock:
positions.add(new Position(stock, quantity));


Is this matrix product diagonalizable?

Question: Let $\boldsymbol{A} \in \mathbb{R}^{n \times m}$ and $\boldsymbol{B} \in \mathbb{R}^{n \times n}$ with $m < n$. If $\boldsymbol{A}$ has full column rank and $\boldsymbol{B}$ is diagonalizable, will $\boldsymbol{A}'\boldsymbol{B}\boldsymbol{A}$ be diagonalizable?
Comment: What is $A^\prime$ here?
Comment: The transpose of $\boldsymbol{A}$.
Answer: No, diagonalisability is not preserved by matrix congruence. E.g. when $m=n=2$,
$$
\underbrace{\pmatrix{1&1\\ 0&-1}}_{A^T}\underbrace{\pmatrix{3&-1\\ -2&1}}_B\underbrace{\pmatrix{1&0\\ 1&-1}}_A=\pmatrix{1&0\\ 1&1}.
$$
$B$ is diagonalisable over $\mathbb R$ because its characteristic polynomial $x^2-4x+1$ has two distinct real roots. This counterexample extends to other dimensions $2\le m<n$ by considering
$$
\pmatrix{A^T&0&0\\ 0&I_{m-2}&0}\pmatrix{B\\ &0\\ &&0}\pmatrix{A&0\\ 0&I_{m-2}\\ 0&0}=\pmatrix{A^TBA&0\\ 0&0}.
$$

Is this matrix product diagonalizable?


Align TextField and Text in ReactNative?

Question: I'm trying to align my component TextInput that uses a TextField from @ubaids/react-native-material-textfield and a Text but i couldn't. The result i have is in the image below :

I added alignItems: 'center' in the container but i didn't work. My code is:

<View style={styles.container}>
            <View style={styles.input}>
              <TextInput
                containerStyle={{ height: 20, marginVertical: 10 }}
                label=""
                value=""
                keyboardType="phone-pad"
              />
            </View>
            <View style={styles.label}>
              <Text style={[styles.text, { textTransform: 'uppercase' }]}>Text</Text>
            </View>
</View>
container: {
    flexDirection: 'row',
    alignItems: 'center'
  },
 input: {
    flex: 0.2
  },
label: {
    paddingTop: 20,
    paddingHorizontal: 10
  },
Comment: why you add `styles.label` to the container view and the `Text` component at same time?
Comment: it was just a mistake i changed it.
Answer: Already answered but I'd like to add a bit more on the topic and different ways to do it depending on your use case.
You can add adjustsFontSizeToFit={true} (currently undocumented) to Text Component to auto adjust the size inside a parent node.

 <Text adjustsFontSizeToFit={true} numberOfLines={1}>Hiiiz</Text>

You can also add the following in your Text Component:

<Text style={{textAlignVertical: "center",textAlign: "center",}}>Hiiiz</Text>
Answer: You should try and add justifyContent to your container's Styling:
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
}
And also, you don't need the view above the Text with the styles.label.
This way, both your TextInput and your Text components will be aligned on both axis
Answer: You have to set display css property to inline-block for both input and label style:
  text: {
    fontWeight: "bold",
    fontSize: "1.5rem",
    marginVertical: "1em",
  },
  container: {
    flexDirection: "row",
    alignItems: "center"
  },
  input: {
    flex: 0.2,
    display: 'inline-block'
  },
  label: {
   // paddingTop: 20,
    paddingHorizontal: 10,
    display: 'inline-block'
  }

As you can see I commented paddingTop: 20 in label (but if you need, you can add it again but you have to add it to input also).
Here a codesandbox.


How to use MUI v5 makeStyles without ThemeProvider?

Question: I have a styles.tsx file because I rather not put the styling in my components:
//styles.tsx

import {grey, purple} from '@mui/material/colors';
import {styled, Theme} from '@mui/material/styles';
import {createStyles, makeStyles} from '@mui/styles';

export const drawerStyles = makeStyles((theme: Theme) =>
  createStyles({
    logo: {
      'fontSize': '2em',
      'fontFamily': 'Oleo Script Swash Caps',
      'background': 'transparent',
      'border': 'none',
      'marginLeft': theme.spacing(1),
      'width': '41px',
      'overflow': 'hidden',
      'transition': 'all 0.1s ease-out',
      'cursor': 'pointer',
      '&:hover': {
        color: purple[700],
      },
    },
    slide: {
      paddingLeft: '8px',
      width: '100%',
    },
  }),
);

In another component I import the drawerStyles:
// drawerContainer.tsx

import {drawerStyles} from 'Src/styles';

export const DrawerContainer = () => {
  const classes = drawerStyles();

  return (
    <Box className={`${classes.logo}>

some text

    </Box>
  )

The code compiles but the browser is returning an error:

MUI: The styles argument provided is invalid. You are providing a function without a theme in the context. One of the parent elements needs to use a ThemeProvider.

On my index.tsx I use ThemeProvider:
// index.tsx

import {ThemeProvider, StyledEngineProvider} from '@mui/material/styles';
import {theme} from 'Src/theme';

  const Root = () => {
    return (
      <ApolloProvider client={client}>

      </ApolloProvider>
    );
  };

  render(<Root />, document.getElementById('root'));

I think the issue is because styles.tsx isn't inside the index.tsx scope. So it doesn't have the themeprovider context when the browser loads the file.
Should I just move all the styling in the component? Or is there another way?
// edit //
Created the styling with the styled api:
// styles.tsx

export const Logo = styled(Box)(({theme}) => ({
  'fontSize': '2em',
  'fontFamily': 'Oleo Script Swash Caps',
  'background': 'transparent',
  'border': 'none',
  'marginLeft': theme.spacing(1),
  'width': '41px',
  'overflow': 'hidden',
  'transition': 'all 0.1s ease-out',
  'cursor': 'pointer',
  '&:hover': {
    color: purple[700],
  },
}));

// DrawerContainer.tsx

  <Link data-cy='btn_home' to='/'>
    <Logo component='button'>Movieseat</Logo>
  </Link>

I kind of dislike this syntax, it's not clear what type of object Logo is.
Answer: See this answer for more detail. In short, makesStyles/withStyles is not the first class APIs in MUI v5 anymore and is scheduled to be removed in v6. If you use the old API, you have to add a theme yourself.
In v4 you can import makeStyles from @material-ui/core/styles without having to supply a custom theme. You can do the same in v5 but only with the new styled API that is being used by all of the MUI components internally.
Comment: @PeterBoomsma looks good to me. `styled`/`sx` prop is the 2 recommended APIs to use in v5. If you want to add the prop type when using typescript. See [this](https://stackoverflow.com/a/69677803/9449426) answer I just wrote an hour ago. Read [this](https://mui.com/system/basics/#main-content) docs section to know more about them.
Comment: The Styled api makes a new component with the added styling, right? I've updated my question with how I've coded it now, could you take a look?
Comment: @PeterBoomsma What's your question with `styled()`, do you still have the same error?
Comment: No error. Everything is working as expected. Just wondering if this approach with the `styled()` components makes sense.


errors creating a custom web component with coffeescript

Question: I am trying to create a custom HTML5 web component in a Rails application, but I am getting errors instantiating the Javascript object.
Version info:
Rails 220.127.116.11
ruby 2.5.8
coffee-rails 4.1.1
I've reproduced the issue in a minimal Rails app, available at https://github.com/fredwillmore/coffee_test
Here's the coffeescript file that creates the component:
class ThingDoer extends HTMLElement
  # constructor: ->
  #   super()

customElements.define("thing-doer", ThingDoer);

This is what the coffeescript transpiles to:
ThingDoer = (function(superClass) {
    extend(ThingDoer, superClass);

    function ThingDoer() {
      return ThingDoer.__super__.constructor.apply(this, arguments);
    }

    return ThingDoer;

  })(HTMLElement);

customElements.define("thing-doer", ThingDoer);

Errors:
with no constructor defined, I get the following error:

Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

same with  a constructor that just calls "super":

Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

I tried a constructor that just calls new HTMLElement:

Uncaught TypeError: Illegal constructor

What am I missing?
Answer: The compiled script isn't suitable as the class has been compiled to an ES5-style class which is not compatible with Custom Elements API.
Instead, you can write a little bit of raw JavaScript to generate a real class, then augment more methods to it using the CoffeeScript's Prototypal Inheritance syntax:
ThingDoer = `class ThingDoer extends HTMLElement { constructor() { super(); this.initialize(); } }`

ThingDoer::initialize = ->
  @innerHTML = 'meow'

customElements.define "thing-doer", ThingDoer

If the above code works in development but not when precompiling assets for production, the reason for that may be that your JS compresser doesn't support ES6 syntax. You can fix your asset pipeline by using a more modern compressor such as terser-ruby or don't transpile it (define the class in eval instead).
ThingDoer = eval '(class ThingDoer extends HTMLElement { constructor() { super(); this.initialize(); } })'

ThingDoer::initialize = ->
  @innerHTML = 'meow'

customElements.define "thing-doer", ThingDoer


An Elliptic Curve has 3 real roots if and only if $\frac{\omega_2}{\omega_1}$ is purely imaginary

Question: Define $\Lambda=\{n\omega_1+m\omega_2 \mid n,m\in \mathbb{Z}\}$ for $\omega_1, \omega_2\in \mathbb{C}$ and $\wp(z)$ is the corresponding Weierstrass elliptic function.
I want to show that $e_1=\wp(\frac{\omega_1}{2}), e_2 = \wp(\frac{\omega_1 + \omega_2}{2}), e_3=\wp(\frac{\omega_2}{2})$ are real if and only if $\omega_1$ is real and $\omega_2$ is purely imaginary.
WLOG, I assumed $\omega_1=1$ and $\omega_2 = i\tau$ for some $\tau\in\mathbb{R}$. Then I deduce that for every $z\in\mathbb{C}$, $\wp(\overline{z})=\overline{\wp(z)}$. By, evaluatin $\wp$ at the half-ratios, I proved that $e_1, e_2, e_3 \in \mathbb{R}$. Is my idea correct?
For proving the other direction I wanted to use the following identities:
$$\omega_1 = \int_{\infty}^{e_1}{\frac{1}{\sqrt{(y-e_1)(y-e_2)(y-e_3)}}dy}$$ and $$\omega_2 = \int_{e_1}^{e_2}{\frac{1}{\sqrt{(y-e_1)(y-e_2)(y-e_3)}}dy}$$
but I cannot drive the result from them since I do not know which of $e_i$s is bigger.
Any help is appreciated.
Answer: The lattice $\Lambda$ is determined by its elliptic curve (ie. differential equation of $\wp_\Lambda$) $$y^2 = 4x^3-g_2(\Lambda)x-g_3(\Lambda) = 4(x-\wp_\Lambda(\omega_1))(x-\wp_\Lambda(\omega_2))(x-\wp_\Lambda(\frac{\omega_1+\omega_2}2))$$
If $\wp_\Lambda(\omega_1),\wp_\Lambda(\omega_2),\wp_\Lambda(\frac{\omega_1+\omega_2}2)$ are real then the elliptic curve of $\overline{\Lambda}$ is the same, so $\Lambda=\overline{\Lambda}$.
(so either $\Lambda=u\Bbb{Z}+iv\Bbb{Z}$ or $\Lambda=u\Bbb{Z}+(\frac{u}2+iv)\Bbb{Z}$ for some $u,v\in \Bbb{R}$)


ListView items repeating

Question: I know this question has been asked before and I have tried those solutions but it didn't help. Items keep repeating after the 9th item. Here is my code.
<code>@Override public View getView(int position, View convertView, ViewGroup parent)
{
    ViewHolder holder;
    if (convertView == null)
    {
        convertView = mInflater.inflate(R.layout.tile_company, null);
        holder = new ViewHolder();
        holder.name = (TextView) convertView.findViewById(R.id.companyname);
        holder.type = (TextView) convertView.findViewById(R.id.companytype);
        holder.logo = (ImageView) convertView.findViewById(R.id.logo);
        holder.category = (ImageView) convertView.findViewById(R.id.category);
        holder.distance = (TextView) convertView.findViewById(R.id.distance);
        holder.time = (TextView) convertView.findViewById(R.id.time);

        convertView.setTag(holder);

        new GetDistanceTime().execute(LocateOutlets.userLatlng, companyList.get(position).getCompanyLatLng(), holder.distance, holder.time);
        holder.name.setText(companyList.get(position).getCompanyDiscout() + "% Off In Store");
        holder.type.setText(companyList.get(position).getCompanyName());
        imageLoader.displayImage(companyList.get(position).getCompanyLogo(), holder.logo);
        imageLoader.displayImage(getCategoryImage(companyList.get(position).getCompanyType()), holder.category);

    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    return convertView;
}

static class ViewHolder
{
    TextView name;
    TextView type;
    ImageView logo;
    ImageView category;
    TextView distance;
    TextView time;
}
</code>
If I do the set functions outside of the if, all the images keep reloading and weird things happen (for instance, an already loaded image will reload with a different image if I scroll a page up).
What am I doing wrong here?
Comment: Have you double-checked your item data (like `Array` or `ArrayList`)? Coz basically what an adapter does is just to display your item data to the assigned listview.
Answer: You need to move the part of your code that links data to views outside of the if-statement.
ListView items are recycled.  Meaning as you scroll, the listview item that was holding data from row #1 might now be used to show row #10.  This recycled view is sent to getView, and since it is not null it skips the part of your code where you link your data to the view elements.  Unless you write over what is currently there, it will continue showing the data from row #1 (or whatever row it was previously assigned to).
Thus, you want to move the part of your code that links data to views outside of the if-statement.
<code>ViewHolder holder;
if (convertView == null)
{
    convertView = mInflater.inflate(R.layout.tile_company, null);
    holder = new ViewHolder();
    holder.name = (TextView) convertView.findViewById(R.id.companyname);
    holder.type = (TextView) convertView.findViewById(R.id.companytype);
    holder.logo = (ImageView) convertView.findViewById(R.id.logo);
    holder.category = (ImageView) convertView.findViewById(R.id.category);
    holder.distance = (TextView) convertView.findViewById(R.id.distance);
    holder.time = (TextView) convertView.findViewById(R.id.time);

    convertView.setTag(holder);

}
else
{
    holder = (ViewHolder) convertView.getTag();
}

    //I moved this block out of your if-statement

    new GetDistanceTime().execute(LocateOutlets.userLatlng, companyList.get(position).getCompanyLatLng(), holder.distance, holder.time);
    holder.name.setText(companyList.get(position).getCompanyDiscout() + "% Off In Store");
    holder.type.setText(companyList.get(position).getCompanyName());
    imageLoader.displayImage(companyList.get(position).getCompanyLogo(), holder.logo);
    imageLoader.displayImage(getCategoryImage(companyList.get(position).getCompanyType()), holder.category);
</code>
Comment: The problem comes when I use the Universal Image Loader. If I use it outside the if, if keeps reloading the wrong images into my imageviews when I scroll up or down the list.
Comment: Is your image loader asynchronous? Try scrolling super slowly (waiting for each image to fully load before showing the next row) and see if the correct image loads.  Let me know results.

ListView items repeating


Confusion between Bytes, Hex and string in Python 3

Question: I have a log file that contains hex strings. I have to convert it back to a legible sentence. However, I am noticing some erratic behavior during string processing.
For example, the shortest line in log file is
82099fd4e8643133b854c842231e33fe99601adfbb32fe19070dc7b665c27f4510eccdd20c8c68b9ffe6fb941554cb675f92fdfd043a7855f8e5ec1f4b1869595f2ee3e89269d3035c77b3e7d520dc786fecc6074c23565a5de9837627e676676bdbfdeda5d5b52895b2ccdaaa373b5cc8ca7e927d885db6d69fed2175df66b23d21b93b5bdbb619bbde75b39acd42d76778259a4a3653473e74fcd0ec0182401ac5367967c1d8de79cb98fab4bf73b561202042dd94853c0e1375fbd147377de48c7050f660af2f55c572ac53384e3c270c95a20767326f58011139217cef33ae4dd5d94835a1717ad60d478b335d4d78901f51467c0d9e73032f95df834f0105012ae3a9e2b82be5981e340e24b71282b002c512d126c1c6edc868cd13cac190a923cd58e6ec08e48426d1f79969833e4499650e1846c93983efc1364ace994ebf2e12fe41aa0e23214b1f04176ec331967395fd4f3ef374f34dc5ed310748398d87528e3eb0ccde6113151d4cd8634dc755e571a7383a1abdbda4bc9a360c75b444628b5fea075a3ab5ac9d169c565645ed3a14997c3d6e1e62516161986a251ae4c2c3d74c248748d956ffdbaa4dcc6bbd11d2f85f00fdf28cbb0b4bb2143030d0d3b5d0d351756c538785d544c775bbe504089616d32c1903aab5f93e986c2a59dfec2d8e5a380563d3f24be2891835cd5bc6bf73c4803644ee9d5d109c2648e76fab6903a6b8bde98de29c5845b550b7cda83668f1706f5c5388010e200d1954230c4cdf18c824356cfb8c01a1f98493cdd4321195adf0d2cf37951a191429b8b9e5062d5c17fc6d356af5fd34fcfb874a9df39bed83dced182becd09ed1d8be2e853d3b1f1397eeeddcf3bbb91dce6c1bb7b7ddbe7e98bd383efbf0e19254cbf489ae8b6596c0e474376cd8f555b3b8c16e491e86b4195f40f6426967c450dbc9a01dbf2d7d05437017002822cc562096d19455266bfe0c7981818e5e8590555af3ef2e4f39fc70023805095443f5be673be68ed99cd823d82e2b831117377b09ea4375aefb6dac75d2c468264e3d22aa1071aaac220ce1052424e85fc2b52d1b22763b7e5b4a9992f5c67c1d5ead25535cab570ab5c1c9752c39d0a76bd0ffd0bb9bc7e0652edf7014d4da9864619b4d1ed10c2f3c5a3b863e2c8e06a947c831d1f328c8244f1f853c4f2f44ee49eb2ee4251eaebc1a4ef0f0a418fff041f33e9c5d58e904f198bd0e23ab7264a19f3ff1d14b8ee0020f591efb7673bd1ec13d37637c105b442fc2af82b48902b0b22be9086d0cdf3148500c62f72a06994980863f2f0e49c1d6e3a65595c61aa6dbb8d55ce330c617d8a1f3df219347ebec4e2ed4809520208b3af588071e42fdf721c1766bf1461fdad89f00b5dda5d6f538d8e517542bd949b1d6324f625d030b5973f6d0fcfc89242bc1735975c2025e3c40a2102887ad45994734e39b81353e2ea63ae2cae7ecf39a2b6c862762a90dcc8b9bca897874928cb9f7d32cb30c9cd43b2462c636fa26a9e5aa147361584f15f619964b7f8a887c0083e5956dc810d3894c2d228e28d5351210425b2cdbaaf64a702cb6e120130c540e5d29b2cf7fffc0ae7c252d1d09189b52ba82012193527cdf03f8417039dea5028100d5a5ad637ad0e88e91043aa321486e1e7a7a8a78c8ceec015d4c4046f6c75e2d3d53b1b2aec8a4fab6df9654bc93e718d61bdc307a7e7b6feea27b0d03a460f8bf2538d838e48178d649b1e4c76dbbc0c6d63aa35a9827d7fd109a763eadb217a5ec6362e5bfb5a35048b11bed20c3da738bb5385895667014babf04842b983f1272d9d675fa407b2cbb6224f2cad2a3bdfb51c0de8809d69b63e48315c0f31e51cd2a555ac9781b5e40d787a1ea297a78b3d7cc0ad0d907b28940c3c9819d156b869507c1cf3c982e17

I use the following snippet to convert it to bytes object
binascii.unhexlify(line[:-1])

The [:-1] to remove the endline character at the end.
I get a bytes object back as follows
b'\x82\t\x9f\xd4\xe8d13\xb8T\xc8B#\x1e3\xfe\x99`\x1a\xdf\xbb2\xfe\x19\x07\r\xc7\xb6e\xc2\x7fE\x10\xec\xcd\xd2\x0c\x8ch\xb9\xff\xe6\xfb\x94\x15T\xcbg_\x92\xfd\xfd\x04:xU\xf8\xe5\xec\x1fK\x18iY_.\xe3\xe8\x92i\xd3\x03\\w\xb3\xe7\xd5 \xdcxo\xec\xc6\x07L#VZ]\xe9\x83v\'\xe6vgk\xdb\xfd\xed\xa5\xd5\xb5(\x95\xb2\xcc\xda\xaa7;\\\xc8\xca~\x92}\x88]\xb6\xd6\x9f\xed!u\xdff\xb2=!\xb9;[\xdb\xb6\x19\xbb\xdeu\xb3\x9a\xcdB\xd7gx%\x9aJ6SG>t\xfc\xd0\xec\x01\x82@\x1a\xc56yg\xc1\xd8\xdey\xcb\x98\xfa\xb4\xbfs\xb5a  B\xdd\x94\x85<\x0e\x13u\xfb\xd1G7}\xe4\x8cpP\xf6`\xaf/U\xc5r\xacS8N<\'\x0c\x95\xa2\x07g2oX\x01\x119!|\xef3\xaeM\xd5\xd9H5\xa1qz\xd6\rG\x8b3]Mx\x90\x1fQF|\r\x9es\x03/\x95\xdf\x83O\x01\x05\x01*\xe3\xa9\xe2\xb8+\xe5\x98\x1e4\x0e$\xb7\x12\x82\xb0\x02\xc5\x12\xd1&\xc1\xc6\xed\xc8h\xcd\x13\xca\xc1\x90\xa9#\xcdX\xe6\xec\x08\xe4\x84&\xd1\xf7\x99i\x83>D\x99e\x0e\x18F\xc99\x83\xef\xc16J\xce\x99N\xbf.\x12\xfeA\xaa\x0e#!K\x1f\x04\x17n\xc31\x96s\x95\xfdO>\xf3t\xf3M\xc5\xed1\x07H9\x8d\x87R\x8e>\xb0\xcc\xdea\x13\x15\x1dL\xd8cM\xc7U\xe5q\xa78:\x1a\xbd\xbd\xa4\xbc\x9a6\x0cu\xb4Db\x8b_\xea\x07Z:\xb5\xac\x9d\x16\x9cVVE\xed:\x14\x99|=n\x1ebQaa\x98j%\x1a\xe4\xc2\xc3\xd7L$\x87H\xd9V\xff\xdb\xaaM\xcck\xbd\x11\xd2\xf8_\x00\xfd\xf2\x8c\xbb\x0bK\xb2\x1400\xd0\xd3\xb5\xd0\xd3QulS\x87\x85\xd5D\xc7u\xbb\xe5\x04\x08\x96\x16\xd3,\x19\x03\xaa\xb5\xf9>\x98l*Y\xdf\xec-\x8eZ8\x05c\xd3\xf2K\xe2\x89\x185\xcd[\xc6\xbfs\xc4\x806D\xee\x9d]\x10\x9c&H\xe7o\xabi\x03\xa6\xb8\xbd\xe9\x8d\xe2\x9cXE\xb5P\xb7\xcd\xa86h\xf1po\\S\x88\x01\x0e \r\x19T#\x0cL\xdf\x18\xc8$5l\xfb\x8c\x01\xa1\xf9\x84\x93\xcd\xd42\x11\x95\xad\xf0\xd2\xcf7\x95\x1a\x19\x14)\xb8\xb9\xe5\x06-\\\x17\xfcm5j\xf5\xfd4\xfc\xfb\x87J\x9d\xf3\x9b\xed\x83\xdc\xed\x18+\xec\xd0\x9e\xd1\xd8\xbe.\x85=;\x1f\x13\x97\xee\xed\xdc\xf3\xbb\xb9\x1d\xcel\x1b\xb7\xb7\xdd\xbe~\x98\xbd8>\xfb\xf0\xe1\x92T\xcb\xf4\x89\xae\x8be\x96\xc0\xe4t7l\xd8\xf5U\xb3\xb8\xc1nI\x1e\x86\xb4\x19_@\xf6Big\xc4P\xdb\xc9\xa0\x1d\xbf-}\x05Cp\x17\x00("\xccV \x96\xd1\x94U&k\xfe\x0cy\x81\x81\x8e^\x85\x90UZ\xf3\xef.O9\xfcp\x028\x05\tTC\xf5\xbeg;\xe6\x8e\xd9\x9c\xd8#\xd8.+\x83\x11\x177{\t\xeaCu\xae\xfbm\xacu\xd2\xc4h&N="\xaa\x10q\xaa\xac"\x0c\xe1\x05$$\xe8_\xc2\xb5-\x1b"v;~[J\x99\x92\xf5\xc6|\x1d^\xad%S\\\xabW\n\xb5\xc1\xc9u,9\xd0\xa7k\xd0\xff\xd0\xbb\x9b\xc7\xe0e.\xdfp\x14\xd4\xda\x98da\x9bM\x1e\xd1\x0c/<Z;\x86>,\x8e\x06\xa9G\xc81\xd1\xf3(\xc8$O\x1f\x85<O/D\xeeI\xeb.\xe4%\x1e\xae\xbc\x1aN\xf0\xf0\xa4\x18\xff\xf0A\xf3>\x9c]X\xe9\x04\xf1\x98\xbd\x0e#\xabrd\xa1\x9f?\xf1\xd1K\x8e\xe0\x02\x0fY\x1e\xfbvs\xbd\x1e\xc1=7c|\x10[D/\xc2\xaf\x82\xb4\x89\x02\xb0\xb2+\xe9\x08m\x0c\xdf1HP\x0cb\xf7*\x06\x99I\x80\x86?/\x0eI\xc1\xd6\xe3\xa6U\x95\xc6\x1a\xa6\xdb\xb8\xd5\\\xe30\xc6\x17\xd8\xa1\xf3\xdf!\x93G\xeb\xecN.\xd4\x80\x95  \x8b:\xf5\x88\x07\x1eB\xfd\xf7!\xc1vk\xf1F\x1f\xda\xd8\x9f\x00\xb5\xdd\xa5\xd6\xf58\xd8\xe5\x17T+\xd9I\xb1\xd62Ob]\x03\x0bYs\xf6\xd0\xfc\xfc\x89$+\xc1sYu\xc2\x02^<@\xa2\x10(\x87\xadE\x99G4\xe3\x9b\x815>.\xa6:\xe2\xca\xe7\xec\xf3\x9a+l\x86\'b\xa9\r\xcc\x8b\x9b\xca\x89xt\x92\x8c\xb9\xf7\xd3,\xb3\x0c\x9c\xd4;$b\xc66\xfa&\xa9\xe5\xaa\x14saXO\x15\xf6\x19\x96K\x7f\x8a\x88|\x00\x83\xe5\x95m\xc8\x10\xd3\x89L-"\x8e(\xd55\x12\x10B[,\xdb\xaa\xf6Jp,\xb6\xe1 \x13\x0cT\x0e])\xb2\xcf\x7f\xff\xc0\xae|%-\x1d\t\x18\x9bR\xba\x82\x01!\x93R|\xdf\x03\xf8Ap9\xde\xa5\x02\x81\x00\xd5\xa5\xadcz\xd0\xe8\x8e\x91\x04:\xa3!Hn\x1ezz\x8ax\xc8\xce\xec\x01]L@F\xf6\xc7^-=S\xb1\xb2\xae\xc8\xa4\xfa\xb6\xdf\x96T\xbc\x93\xe7\x18\xd6\x1b\xdc0z~{o\xee\xa2{\r\x03\xa4`\xf8\xbf%8\xd88\xe4\x81x\xd6I\xb1\xe4\xc7m\xbb\xc0\xc6\xd6:\xa3Z\x98\'\xd7\xfd\x10\x9av>\xad\xb2\x17\xa5\xeccb\xe5\xbf\xb5\xa3PH\xb1\x1b\xed \xc3\xdas\x8b\xb58X\x95fp\x14\xba\xbf\x04\x84+\x98?\x12r\xd9\xd6u\xfa@{,\xbbb$\xf2\xca\xd2\xa3\xbd\xfbQ\xc0\xde\x88\t\xd6\x9bc\xe4\x83\x15\xc0\xf3\x1eQ\xcd*UZ\xc9x\x1b^@\xd7\x87\xa1\xea)zx\xb3\xd7\xcc\n\xd0\xd9\x07\xb2\x89@\xc3\xc9\x81\x9d\x15k\x86\x95\x07\xc1\xcf<\x98.\x17'

Now, my understanding is that these are hex codes, and there would be a "decoded" version of this.
Now, for some reason, I copied a portion of the string, assigned it to a variable, and printed it normally, it gave a "decoded" version (it was random gibberish, though, but it works)
print('\x98l*Y\xdf\xec-\x8eZ8\x05c\xd3\xf2K\xe2\x89\x185\xcd[\xc6\xbfs\xc4\x806D\xee\x9d]\x10\x9c&H\xe7o\xabi\x03\xa6\xb8\xbd\xe9\x8d\xe2\x9cXE\xb5P\xb7\xcd\xa86h\xf1po\\S\x88\x01\x0e \r\x19T#\x0cL\xdf\x18\xc8$5l\xfb\x8c\x01\xa1\xf9\x84\x93\xcd\xd42\x11\x95\xad\xf0\xd2\xcf7\x95\x1a\x19\x14)\xb8\xb9\xe5\x06-\\\x17\xfcm5j\xf5\xfd4\xfc\xfb\x87J\x9d\xf3\x9b\xed\x83\xdc\xed\x18+\xec\xd0\x9e\xd1\xd8\xbe.\x85=;\x1f\x13\x97\xee\xed\xdc\xf3\xbb\xb9\x1d\xcel\x1b\xb7\xb7\xdd\xbe~\x98\xbd8>\xfb\xf0\xe1\x92T\xcb\xf4\x89\xae\x8be\x96\xc0\xe4t7l\xd8\xf5U\xb3\xb8\xc1nI\x1e\x86\xb4\x19_@\xf6Big\xc4P\xdb\xc9\xa0\x1d\xbf-}\x05Cp\x17\x00("\xccV \x96\xd1\x94U&k\xfe\x0cy\x81\x81\x8e^\x85')

The output of the previous line is as follows
T#                          âXEµP·Í¨6hñpo\S
Z8LßÈ$5lû¡ùÆ¿sÄ6Dî&Hço«i¦¸½é
           ÍÔ2ðÒÏ7�)¸¹å-\üm5jõý4üûJÜí+ìÐ
=;îíÜó»¹Îl·Ý¾~TËô   ®eÀät7lØõU³¸ÁnI´_@öBigÄPÛÉ ¿-}Cp("ÌV ÑU&kþ
                                                                  y^

And the output was encrypted gibberish.
Then I tried doing the whole string through the copy-paste mechanism, and it worked.
However, when I try to run it through the script going line by line by using str(<bytes object here>) and removing the unnecessary parts (the leading b' and the ending '), I am still getting the string with all the \x codes.
for i in range(len(data)):
    binary_string = data[i][:-1]
    binary_string = binascii.unhexlify(binary_string)
    binary_string = str(binary_string)[2:-1]
    print(binary_string)

Where data is the result of file.readlines().
Can someone help me understand what's happening and why a simple copy-paste method works while running it through the loop doesn't work?
Answer: The bytes object you get back with the representation beginning
b'\x82\t\x9f\xd4\xe8d13\xb8T\xc8B#\x1e3\xfe\x99`\x1a\xdf\xbb2\xf... etc

is actually a list of integers in the range 0..255. You will see this if you do
>>> x = b'\x82\t\x9f\xd4\xe8d13\xb8T\xc8B#\x1e3\xfe\x99`\x1a\xdf\xbb2\xf... etc
>>> list(x)
[130, 9, 159, 212, 232, 100, 49, 51, 184, 84, 200, 66, 35, 30, ...etc

The backslashes aren't part of the data: they are the representation of the data when byte values are displayed as a bytestring. For example, the 2nd value as shown in the integer list is 9. In the bytestring display it is shown as \t which is an ascii horizontal tab, for which the byte value is 9 (or ctrl-i if you prefer). Similarly, the 6th to 8th integer values are 100, 49, 51 which are the ascii values for the characters 'd', '1', '3'; and if you look closely you will see them in the bytestring representation as d13 between the bytes \xe8 and \xb8. You see d13 because those bytes can be represented as ascii characters. On either side of that you see \xe8 and \xb8 because those bytes have the values 232 and 184, which can not be represented as ascii characters, and so are displayed as hex escapes.
But if you try to process the bytestring representation as a sequence of characters, which is what happens when you call str() on it, and throw away the enclosing b'...', then it is no longer a sequence of byte values, but rather a bunch of characters that once represented a bytestring. Then you are more or less on your own.
You are probably wondering why Python's default representation of bytestrings is a mixture of hex escapes like \xe8, shortcuts like \t, and printable characters. There are a couple of good reasons for this, one being that bytestrings are often text, and b'Hello World' is friendlier than b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64'.
To confirm this, paste that bytestring at a Python interpreter prompt, like this:
>>> b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64'
b'Hello World'


Except in a regex still returns a match

Question: I am in the process of trying to firm my grasp over regex expression using except and am trying to explain to myself why the following wont work. I am using regex 101 for testing
I have something like this
[^abc]s$

This works when any letter that is next to the end letter s is not an a,b or c.
What i want is the entire string should not have an a , b or c. How can i specify that.
I tried this
([^abc].*)s$
. => any character
* => any no of times
s$ => ending with a s character

so [^abc]. should be any character except abc - Am i Correct ?
Overall the expression should be any no of characters except characters a,b or c occurring any no of times and ending with character s ? I tried this and this still passes the regex  with the following word
ddsbbsdds

since the string has the characters b in it it should have failed the regex test
Answer: What you have here is a (potential) partial match. You specify what should match the end anchor of your test string, but not what the start should be. Also, you are testing just a single character, because a custom character class [...] only tests one.
To test an entire string, from start to end, add a start anchor ^:
^[^abc]s$

This will only match two-character strings, so to allow more occurrences of the custom character class, add either * (zero or more) or + (one or more):
^[^abc]+s$

This will match entire strings, not containing a, b or c, and always end with an s. (See this on regex101.com.)
(Note on your own attempts: [^abc]. fails because [^abc] matches a single character and the next . matches any character. Adding parentheses and * are random attempts to "make it work", as far as I can see.)
Comment: Thank you for answering. Could you tell me why my `([^abc].*)s$` fails. Did i interpret this expression wrong ? I mean even you read it the way it is I would think it should fail as it specifies any characters the preceed s should not be a,b or c
Comment: @JamesFranco: the `.` will match any character, thus violating your rule of "no a,b,c". The only criterium here is that the *first* character is not one of `abc` – and since you did not add a start anchor, that 'first' can actually be *any* character in the string.

Except in a regex still returns a match


Bourbaki-Witt fixed point theorem: two questions

Question: Consider the following theorem:
Let $f\colon E \to E$ have the propery that $f(x)\geq x$, where $(E,\leq)$ is a non-void partially ordered set with the property that every totally ordered subset of $E$ has a least upper bound. Then there is an element $a$ in $E$ such that $a=f(a)$.
My first question is:

does this theorem hold for sets like $[0,1[$? In general, does it hold for generic subsets of $\mathbb{R}$?

This theorem "implies" the Hausdorff maximality theorem, that is
"every partially ordered system contains a maximally ordered subsystem."
Proof. If $E$ has no maximal element, then to every $A \in E$ there corresponds an $f(A)$ containing $A$ properly. Thus the preceding theorem is contradicted by the function $f\colon E \to E. \quad \blacksquare$
My second question is:

in proving this statement it seems that we are not taking into account only the fixed point theorem, but the fact that the function $f$ is not defined "concretely". Are we invoking implicitly the axiom of choice?
Comment: To your second question, I would say that _Bourbaki-Witt theorem can be used to show that AC implies ZL_ is more precise than the statement _Bourbaki-Witt theorem implies ZL_. You're right that the above proof uses AC implicitly; in some places the use of AC is more explicit; see e.g. http://files.nyu.edu/eo1/public/Book-PDF/CHAPTER%205%20(Zorn).pdf and
http://www.artofproblemsolving.com/Wiki/index.php/Zorn%27s_Lemma
Answer: The set $[0,1[$ does not have a least upper bound in itself, so the theorem does not apply to it. It also does not hold: consider the map $$f:[0,1[\to[0,1[:x\mapsto \frac{x+1}2\;.$$ Clearly $f(x)>x$ for each $x\in[0,1[$.
Added: The answer to the second question is yes: the Hausdorff maximality principle [HMP] is equivalent to the axiom of choice [AC}, but the Bourbaki-Witt theorem can be proved in ZF without AC. Since AC is independent of ZF, the HMP cannot possibly follow from the Bourbaki-Witt theorem. What is true is that the Bourbaki-Witt theorem allows an easy proof that AC implies HMP, as may be seen here.
Answer: I looked at the proof appearing in Wikipedia, the proof of the theorem goes like this:
Let $x_0\in E$. Suppose $x_\alpha$ was defined, let $x_{\alpha+1}=f(x_\alpha)$, and if $\beta$ is a limit ordinal and $x_\alpha$ was defined for all $\alpha<\beta$ then $x_\beta=\sup\{x_\alpha\mid\alpha<\beta\}$ (this is well defined because we ensured that $\{x_\alpha\mid\alpha<\beta\}$ is a chain, therefore it has a supremum)
So far there is no use in the axiom of choice. The assumption on $E$ was that every chain has a supremum. In the usual proof of AC from Zorn's Lemma there is no supremum and we need to choose an upper bound at limit stages.
Now, a very good construction related to the axiom of choice is Hartogs number, let us denote $X$'s Hartogs by $\aleph(X)$: the least ordinal which cannot be injected into $X$. Assuming the axiom of choice $\aleph(X)=|X|^+$, but without the axiom of choice this is a good measure on "how much of $X$ can be well ordered".
We return to the above $x_\alpha$'s, if $x_\alpha=x_{\alpha+1}$ then $f(x_\alpha)=x_{\alpha+1}$ and we found the fixed point; otherwise we can contintue and define an injection from $\aleph(E)$ into $E$ which is a contradiction.
The key point, here, is that $f(x)\geq x$ and that $E$ has the property that every chain has a least upper bound. From these two properties the proof becomes constructive. Not everything which is "general" requires the axiom of choice. It is possible to have general, nontrivial theorems which do not require the axiom of choice (e.g. Cantor's theorem; Cantor-Bernstein theorem). Furthermore, the generality is quite restrictive in the form mentioned above with the property of $E$.


What's the probability of 2-head given at least 1 head?

Question:
Problem Two coins are tossed. What's the probability of 2-head given at least 1 head?

I got the answer to be:
$$P = \dfrac{(1/2)(1/2)}{1 - 1/4} = \dfrac{1}{3}$$
but I have a feeling it should be greater than this, could anyone help me out?
Comment: This is correct.  Stipulating at least one head leaves three equally probable cases (HT, TH, and HH), one of which is the 2-head case.
Comment: Also [see this isomorphic question](http://math.stackexchange.com/q/2731/25554)
Comment: Also [here it is again](http://math.stackexchange.com/questions/15055/in-a-family-with-two-children-what-are-the-chances-if-one-of-the-children-is-a)
Comment: Does this answer your question? [If two coins are flipped and one gets head, what is the probability that both get head?](https://math.stackexchange.com/questions/1805277/if-two-coins-are-flipped-and-one-gets-head-what-is-the-probability-that-both-ge)
Answer: If you know that the coins are fair and the tosses are independent, and if the "given at least 1 head" is strictly interpreted (you know that, and just that), your answer is correct. A priori (without the additional "at least 1 head" condition), you had four equiprobable cases. The condition removes one of the four possible cases, but does not say anything more (hence the three remaining cases remain equiprobable). Hence, the probability of the case "2-heads" is 1/3.
If you feel this is incorrect, perhaps you are thinking (wrongly here) along the lines of this related problem. That statement might sound equivalent to this one, but it's not.
Comment: Thanks a lot! In fact I was confident about my answer when drawing out all the same spaces.
Answer: There are 8 possible combinations of 3 coin toss:
HHH THH HTH HHT TTH THT HTT & TTT
but given that 1 H is observed, so TTT was elimated. So 7 left possible combination..but the question is  the probability of at least 2 H. (HHH THH HTH HHT) Therefore the answer is
4/7


Why is there a need to restore the policies when creating an alert policy in Cloud Monitoring API?

Question: There is a concept I don't really understand when looking at the sample code for Cloud Monitoring API (v3).
In all the code examples for creating an alert policy there is code that "restores" the policies first before making a new one. Also the function names for the examples isn't "creating" a policy, it's "restoring". I don't quite understand why this is needed. Is there a reason for why policies need to be "restored"? What does "restored" mean?
https://cloud.google.com/monitoring/alerts/using-alerting-api#api-create-policy
Here is one of the examples (Java)
<code>private static void restoreRevisedPolicies(
String projectId, boolean isSameProject, List<AlertPolicy> policies) throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    for (AlertPolicy policy : policies) {
      if (!isSameProject) {
        policy = client.createAlertPolicy(ProjectName.of(projectId), policy);
      } else {
        try {
          client.updateAlertPolicy(null, policy);
        } catch (Exception e) {
          policy =
              client.createAlertPolicy(
                  ProjectName.of(projectId), policy.toBuilder().clearName().build());
        }
      }
      System.out.println(String.format("Restored %s", policy.getName()));
    }
  }
}
</code>
Answer: Those are valid examples of using the "create" API call, and  the "restore" function is there because the same example code is used also in the "Backup and restore" section, but this makes it no less of a valid example.


What is the IIS equivalent of mod_wsgi's WSGIScriptAlias?

Question: I'm trying to get Django running on IIS 6 using pyisapie and I'm having some trouble. I have pyisapie working on IIS, but it only works if I specify the full url to a specific python script like so:
http://localhost/sample/test.py

I have PyISAPIe.dll set as a wildcard application map for the virtual directory where my application lives.  The part that I don't understand is how do I tell PyISAPIe.dll which python script to execute when I hit my virtual directory from the url?
I want to be able to navigate to
http://localhost/sample/any/thing/that/I/want/right/here

and have test.py be executed. If I try the 2nd url now, I get a 404.
Answer: If you need to specify an existing file.py, then you probably put in the configuration of the Virtual Directory on IIS6 an Application extension with PyISAPIe.dll instead of a Wildcard Application map (lower pane) in the Application Configuration screen.
For me it works now.
Answer: http://www.boutell.com/newfaq/creating/iiscgihowto.html
See above link as well.
Have no experience here but thought that IIS supported CGI therefor why not wsgi?
Comment: I have wsgi working on IIS already, but it only works when I hit a python script from the URL... I don't know how to configure IIS to have a WSGIScriptAlias like mod_wsgi for Apache.


Servlet throws Exception

Question: This is my Servlet code which i am using to query a solr index
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

//Solr Imports
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;

/*
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
*/

public class HelloWorldExample extends HttpServlet {

    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
    {
        PrintWriter out = response.getWriter();
        String inputStr=request.getParameter("input");
        out.println("
" + inputStr + "
");
        //try {
        SolrServer server = new CommonsHttpSolrServer("http://localhost:8080/solr/");
        SolrQuery solrQuery = new SolrQuery();
        //solrQuery.setQuery("fileName:"+input);
        solrQuery.setQuery("Latitude:"+32.55668);
        QueryResponse rsp = server.query(solrQuery);
        //SolrDocumentList x = rsp.getResults();
        System.out.println(rsp);
        }
        catch (SolrServerException e) {
            e.printStackTrace();
        }
    }
}

I am compiling this code using
D:\xampp\tomcat\webapps\examples\WEB-INF\classes>javac -classpath .;D:\JAR\servl
et-api.jar;D:\JAR\1solr-core-1.3.0.jar;D:\JAR\1solr-solrj-1.3.0.jar;D:\JAR\1solr
-common-1.3.0.jar;D:\JAR\apache-solr-solrj-1.4.0.jar HelloWorldExample.java
This code compiles without problem. However when i run this servlwt it gives me an error:

type Exception report
  message
description The server encountered an internal error () that prevented
  it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
  root cause
java.lang.NoClassDefFoundError:
  org/apache/solr/client/solrj/impl/CommonsHttpSolrServer
    HelloWorldExample.doGet(HelloWorldExample.java:35)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Comment: Start reading. http://stackoverflow.com/search?q=%5Bjava%5D+NoClassDefFoundError
Comment: i have been trying to debugging from last 3 hours...  pls suggest
Comment: Add solr jar files in your class path
Comment: @Grrrrr please see D:\xampp\tomcat\webapps\examples\WEB-INF\classes>javac -classpath .;D:\JAR\servl et-api.jar;D:\JAR\1solr-core-1.3.0.jar;D:\JAR\1solr-solrj-1.3.0.jar;D:\JAR\1solr -common-1.3.0.jar;D:\JAR\apache-solr-solrj-1.4.0.jar HelloWorldExample.java
Comment: it has solr files already i do not know hwich one is missing
Comment: If this is your servlet and I am assuming you are using eclipse or NB to develop it then add the libraries from apache-solr-x.x.x\dist to your project lib.
Comment: It gives error while compiling: Note: HelloWorldExample.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Comment: The problem is the **runtime** classpath, not the compile-time classpath.
Answer: When you are compiling you are properly including all dependant libraries into the classpath.
The classpath used for execution is a totally different beast. You need to make sure the Servlet has access to the jars when it is being executed. How to do that depends on the container you are using. Since it is tomcat it should be easy to find out (search the web) how to add thirdparty libraries (pretty sure you can just dump the jar into common/lib directory).
Best would be to have a build process different from manual compiling of the servlet class. For example and IDE or maven - that would produce a war / web-application and deploy it to the servlet container (tomcat in your case). I do really really recommend doing this instead of manual compiling and deploying (once you get IDE-way to work and become more masterful at deployment you could go back to manual deployment)
Maybe search the internet for a tutorial on servlets and tomcat?
Answer: Put the library JAR files where the webapp depends on in its /WEB-INF/lib folder. That folder is by default covered by the webapp's runtime classpath.

Servlet throws Exception


User Login Destination | to his first submission | Webforms

Question: i have a career form built with webforms ; I need the users to go back to their first submission when they come back to the site again .
Login Destinations | can help me with that . but it will send only to a specific URL . where in my case every user have its own submission and i want him to return back to it in Edit mode when he/she logins again .
any clues /
thanks
Answer: You can achieve using hook_user_login() function.
<code>function mymodule_user_login(&$edit, $account)
{
  // Your logic will set $redirection to the desired location.
  // Get the logic and fetch where do you want to redirect.
  // Here i am redirecting to node 34. You can fetch your own webform submission path
  // where do you want to redirect.
  // Fetch the submission of done by the current users. by using http://api.drupalize.me/api/drupal/function/webform_get_submissions/7 function
  $redirection = 'node/34';

// Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.
  if (empty($_GET['destination'])
    && !is_null($redirection)
    && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset'))
  {
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }
}
</code>
Comment: in template.php you can also write, but create a simple module. in the .module file of module write the MODULENAME_user_login() function.
Comment: thanks mohit , but i need each user to go to its own form (edit mode) which he submitted earlier .
Comment: you can find the webform submissions of the logged in users and then you can redirect it to respective page.
Comment: where should i be altering this hook function ? in my template.php ?


Laravel com Site + Cms + Intranet

Question: Estou criando um site que vai contemplar um cms e uma intranet. No CakePhp eu separava essas aplicações com Plugins, isto é, site na raiz do projeto/cake e plugins para os demais. Bem tranquilo, organizado e funcional
Como consigo fazer isso no Laravel? Não gostaria de deixar os controllers e models tudo misturado.
Vale ressaltar que estou iniciando agora no Laravel (5.X)
Answer: Veja essa vendor que permite trabalhar no Laravel com HMVC pingpong que pode ser mais familiar a você. De todo modo, mesmo sem usar essa vendor que citei, vale a sua organização na hora de criar sua aplicação, se não quer misturar tudo, depende de como pensa na infraestrutura e o Laravel não obriga você a misturar tudo, talvez, tão pouco outro framework.
Comment: Obrigado pela resposta William. Vou ver sobre essa vendor. Mas no caso consigo separar por pastas os models e controllers? Minha "organização" que digo é mais relacionado ao espaço físico e não lógico.

Laravel com Site + Cms + Intranet


Is everyone capable of singing?

Question: So here is the exciting analogy I am going to cite: "While singing, our body is like a musical instrument, having distinct body parts playing different roles in creating the sound we produce." Felicia Ricci (youtube artist)
So, if our body really comes equipped ready to sing, why isn't everybody good at singing when they try? Is it just due to lack of practice or knowledge? Is it true that everybody can sing?
Comment: I'd hardly take a "youtube artist" as being an expert in anything.  Your premise that our physiology is designed (in any evolutionary sense) for carrying a tune is unfounded.
Comment: @Carl would you agree with this post
Which tells genetics might be behind it counting for differences in quality of sound one can produce. So theoretically everbody is capable of singing but with limitations or differences
http://www.medicaldaily.com/singing-tips-have-certain-skull-shape-and-other-science-behind-carrying-tune-308372
Answer: In the absence of some physiological defect (which may also preclude the ability to talk) everyone can "sing".  However not everyone will sound the same when they sing, nor will everyone have the same vocal range.  In other words, there is a wide disparity in capability.
Every person is born with different physiology which has a bearing on what they are capable of doing with their bodies.  Not everyone is equipped to be able to run a mile in under four minutes no matter how much they train.  Not everyone can hit a baseball 400 feet or throw a baseball 100 miles per hour.  The same limitations apply to many aspects of singing.
For example some singers have an unusually wide range in terms of the notes they can accurately sing.  While most people are able to increase their range through training and practice, they are usually only able to add a few more notes to either end of their range.  A very small number of people are able to sing notes covering a four octave or more span, before they even start training to expand their range.  The average person will never be able to achieve even a two octave range.
I should point out that not everyone can "carry a tune" so to speak.  I know some people who are tone deaf.  No matter how hard they try, they cannot stay in key when they sing.  According to Wikipedia: Wikipedia Article on Tone Deafness

Tone deafness is the lack of relative pitch, or the inability to distinguish between musical notes that is not due to the lack of musical training or education.

Also - the quality of a persons voice in terms of how others perceive it, varys from person to person.  While everyone can improve their singing with training and practice, some people just naturally have a more resonant or pleasant sounding singing voice.  The way a person sounds when they sing is influenced by things such as the shape of their throat, the length and thickness of their vocal chords, the shape of their mouth, the shape and size of their nasal cavity, and other aspects of the physical characteristics of their vocal tract and resonators.
Having said all of that, I believe that with proper training and intentional practice - most people can dramatically improve their singing ability - including their range, tone and quality of their singing!  A good vocal coach or voice teacher can evaluate a singer's strengths and weaknesses and prescribe specific practice drills and regimens to help them develop and improve their singing voice.
There will always be some physical limitations to how much anyone can improve.  But singing is a way that everyone can express themselves in an enjoyable way that provides personal satisfaction to the singer.  Even if those within earshot don't share in that joy.  I think everyone should be encouraged to sing more often.  It's good for the soul!
Comment: Yes, I think being totally "unable to sing" is quite rare. You might equate it with dyslexia - lots of people have it to a slight extent but most are able to work around it to a degree with hard work.
Comment: @Rockin This question was targetted to my personal pursuit. I wanted to take a decision whether its worth giving time practicing singing.And hey,  Acually i got the answer that exluding the possiblility of illness of any kind I have a high chance that i can try and find out this answer for myself.
Comment: @SanjeevChauhan Absolutely!  Go for it.  The most important thing is for you to have fun and enjoy the process of singing and learning to sing better.  You may discover that other's really enjoy hearing you sing as well.  I did not discover that I could sing well until after the age of 40.  Now I perform professionally and people pay me to sing.  But mostly I do it for the enjoyment of it.
Answer: Well, difficult to answer that questions. Personally, I would say that it is the case. We all have the needed tools and prerequisites to sing properly.
Of course there maybe some diseases or malfunctions which prevent you from singing, but then you would have other concerns than singing =)
I would say, even a person which lacks everything needed for singing, may it be rhythm, finding the right pitch and be able to hold it, even when he isn't capable of doing all that, with enough training and the right instructor everyone can become a good singer. But everyone will need a different amount of time to master his voice.
And I really agree with the statement that when singing, our body is an instrument, the faster one really understands that, the faster he will learn.
As for the question why not everyone is good at singing: Not everyone tries or wants to be a good singer.
That is my quite generic answer to that question. I am sure someone can give more examples and explain why that is the case and which physiological requirements there are.
Answer: So much of the problem in getting people to sing is not with there ability but getting people confident enough to sing in front of people There seems to be a big mental block with people for some reason that most of the time has very little to do with there actual voice.
It does seem like you need a certain amount of confidence in yourself to be able to sing and that many times problems with singing have some sort of psychology behind them.
Comment: Confidence is good!  But attainment is also good.  Particularly for those listening.
Answer: Not everybody can sing.
Not many people can sing well…
… but most people can carry a tune.
I tend to think of it along the lines of the bell-curve model - I've tried to avoid one that gets too specific, as most times you find this it's talking about IQ, so the numbers don't really work for our purposes, but the IQ system is designed to always make 100 the average whatever population you measure, be it human beings or marmosets...

So, what it tries to explain, in extremely broad terms, is that 'most people are average', with far fewer at each extreme.
This type of ability chart tends to work reasonably well for any skill - be it singing, cooking or juggling - because even though the average skill level for the population as a whole is very low for juggling, the average is still in the middle.
Unlike IQ [which is where the comparison fails & why I didn't put too much emphasis on it] cooking, juggling & singing can all be improved by practice.
Comment: This is pure speculation.
Comment: I give up. Whatever. Provide a factual answer, with references & I'll retract mine.

Is everyone capable of singing?


Can a vector of a-a, still be used as a point of direction even if it does equate to 0?

Question:
In my maths class we had a similar problem where we had to find the solution to get to Y from X. The answer is c however I argued that it could also be a-a, because technically you can go up to B from X by 1a and then down to Y by -1a, but apparently I was wrong, although I don't see why. Is X to Y simply c, or is my point (a-a) still technically correct, even if it does equate to 0.
Answer: Bear in mind that $-1a$ will take you from $B$ back to $X,$ so $a-a$ takes from from $X$ to $X$.
We can get from $X$ to $Y$ directly by $c,$ or indirectly by $a+b$ (or many other, more complicated combinations, all of which simply amount to $c$).
Bear in mind that a vector is not just a magnitude (distance), but a direction. So, while it appears that $a$ and $b$ have the same magnitude by the drawing, the vector $a$ will not take us from $B$ to $Y$. The vector $b$ will do that, which is why $a+b$ does the trick (we could think of it as taking us from $X$ to $B$ to $Y$, or from $X$ to $Z$ to $Y$), but note that $a+b=c,$ so the simplest answer is $c$.
Comment: just trying to make sense of this all. Would the vector 'b' do the trick because it is parallel to BY, so they must be the same magnitude?
Comment: Assuming that all lines that *look* parallel actually *are* parallel, then $b$ will take us from $B$ to $Y$. It will not take us from $X$ to $Y$ on its own, though.
Comment: So even if two lines look parallel, does that mean they may not be parallel? If the answer is yes, then whats to say that BY can't also be equal to 'a' just as XY is, cos I read somewhere that vectors can still be equal and be anywhere on a page?
Comment: And another question: is the arrow pointing down labelled 'b' be negative b (if it's going down) or positive b, because it's labelled as a positive b.
Comment: I assume that $X,Y,Z$ are supposed to be the respective midpoints of the segments $AB,BC,AC,$ so *apparently* parallel is *actually* parallel. Also, we necessarily have that the segments $AX,BX,YZ$ are the same length; $BY,CY,XZ$ are the same length; $AZ,CZ,XY$ are the same length. It certainly *looks* like the first two sets of three segments are all equal in length to each other in length, but even if so, they are *not in the same direction*. Magnitude *and* direction are important. We treat vectors the same regardless of their starting point *if they have the same magnitude and direction*.
Comment: As for $b$, the arrow indicates the direction of $b$. The vector $-b$ is the vector that takes us (for example) from $Z$ to $X$ or from $Y$ to $B$.


Order by from a stored procedure

Question: How do I do a order by from my stored procedure?
ALTER PROCEDURE [Data].[filtering_param]
    @param1 NVARCHAR(1000) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Sql Nvarchar(MAX);

    SET @Sql = N'SELECT
                     ps.Mærket AS Mærke, P.DataID,
                     PS.Billed, P.Model, P.vendor,
                     P.Årgang, P.[Motor Type],
                     P.Krydsmålet, P.Centerhul,
                     P.ET, P.Bolter, P.Dæk, P.Fælge, PS.Krydsmålene
                 FROM
                     Data.Hjuldata P
                 INNER JOIN
                     Data.Mærke PS ON P.MærkeID = PS.MærkeID
                 ORDER BY
                     ps.Mærket, P.model
                 WHERE 1 = 1 '
        + CASE WHEN @param1 IS NOT NULL
         THEN N' AND Krydsmålet = @param1 ' ELSE N'' END

    EXEC sp_executesql @Sql, N'@param1  NVARCHAR(1000)', @param1
END

I get this error:

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
  Additional information: Incorrect syntax near the keyword 'WHERE'.
Answer: The Order by clause must be after the where clause.
Also, there is no need for dynamic sql here. You can write it like this:
Select ps.Mærket AS Mærke
         , P.DataID
         , PS.Billed
         , P.Model
         , P.vendor
         , P.Årgang
         , P.[Motor Type]
         , P.Krydsmålet
         , P.Centerhul
         , P.ET
         , P.Bolter
         , P.Dæk
         , P.Fælge
         , PS.Krydsmålene
from Data.Hjuldata P
inner join Data.Mærke PS on P.MærkeID = PS.MærkeID
WHERE @param1 IS NULL
OR Krydsmålet = @param1
ORDER BY ps.Mærket, P.model

Answer: The ORDER BY goes after the WHERE clause. There is no need to compose a string and pass it to sp_executesql, just write the T-SQL code into the procedure.
ALTER PROCEDURE [Data].[filtering_param]

@param1 nvarchar(1000)=NULL

AS
SET NOCOUNT ON

SELECT
    ps.Mærket AS Mærke,
    P.DataID,
    PS.Billed,
    P.Model,
    P.vendor,
    P.Årgang,
    P.[Motor Type],
    P.Krydsmålet,
    P.Centerhul,
    P.ET,
    P.Bolter,
    P.Dæk,
    P.Fælge,
    PS.Krydsmålene
FROM Data.Hjuldata P
INNER JOIN Data.Mærke PS ON P.MærkeID=PS.MærkeID
WHERE @param1 IS NULL OR Krydsmålet=@param1
ORDER BY
    ps.Mærket,
    P.model

Order by from a stored procedure


Branch of multiple-valued function (complex analysis)

Question:
Find a branch of $(z^3 - 1)^{1/3}$ which is analytic in $|z| > 1$

So we essentially want to study $\frac 13\text{Log} (1 - \frac 1{z^3} )$, the principal branch of the logarithm where $-\pi < \text{Arg} (z) < \pi $. Problems arise when $\text{Re}(z^3 - 1) \leq 0 $ and $\text{Im} (z^3 - 1) = 0$ i.e. when $z^3 - 1$ is a non-positive, real number.
Setting these equations up, how can I produce the result $|z| > 1$?
Comment: You're welcome.
Comment: Can you find a branch of $\sqrt[3]{1-w^3}$ for $\lvert w\rvert < 1$?
Comment: I run into the same problem, having to produce that result from the real and imaginary part equations
Comment: Can you find a branch of $\sqrt[3]{1-w}$ for $\lvert w\rvert < 1$? If you do that, the solution to your problem is only a small modification away.
Comment: I would make a similar approach for that one, factoring out w and investigating the log of $1/w - 1$. But again I would have the produce that result by investigating the conditions on the real and imaginary part (respectively) of $1/w - 1$. That's where it gets hairy for me unfortunately!
Comment: That's the wrong way. You should factor out $z$ to get the above form, which you can directly solve. You don't need to consider a logarithm at all, although for $\sqrt[n]{1-w^k}$ you can, if you want.
Comment: I just realized I made a typo in my original post, fixed it now though. As you can see, I did factor out $z^3$ but was unable to proceed thereforth.
Comment: Okay, so you have factored out the $z$, good. Now, you don't need to consider the logarithm, but you can. If $\lvert z\rvert > 1$, what can you say about $\frac{1}{z^3}$? And hence about $1-\frac{1}{z^3}$?
Comment: With $|z|>1$ we can derive $\frac 1{|z^3|} < 1$ and hence $0 < 1 - \frac 1{|z^3|}$. I suspect there is some conclusion to draw here but I am not seeing it unfortunately. Here I am dealing with absolute values and I somehow want to think about the significane of this in the complex plane.
Comment: Let $w = \frac{1}{z^3}$. You know $\lvert w\rvert < 1$. So $w$ lies in the unit disk. Now, where lies $1-w$? Draw a sketch.
Comment: Hm, $1 - w$ shifts all points to the right on the plane and $-w$ just reflects the $x$ and $y$ to the opposite quadrant (diagonally). Essentially a circle around at $w = 1$ of radius 1? But the triangle inequality yields $|1 - w| = |w - 1| \leq |w| + 1 < 2$ ?
Comment: Forget about the triangle inequality. Take the unit disk. What does $w \mapsto -w$ to the unit disk [as a set, not to the individual points]? Then, what does $u \mapsto 1+u$ with that?. So, at the end, what has become of the unit circle? "Essentially a circle around at $w=1$ of radius $1$?" Drop the "essentially", it has become the circle of radius $1$ with centre $1$. Now, look at that circle (sketch it if necessary), and ponder famous domains for branches of the logarithm.
Comment: I think I get it now! The requirement $|z| > 1$ implies $|1/z^3| < 1$ i.e. complex numbers of the kind $1/z^3$ lie inside the unit disk. The operation $1 - (1/z^3)$ shifts all points to the right one unit and reflects all points diagonally (we still end up on a unit disk, but now with center at z = 1). So complex numbers of the kind $1 - (1/z^3)$ lie on the unit disk $|w-1| = 1$ and this domain is contained within the principal domain of the logarithm function and hence we can make the function in question analytic! Did I get that right?
Comment: Yes, if $w$ lies in the unit disk, then $1-w$ lies in the right half-plane. So we can without problems take logarithms or $n$-th roots there.
Comment: Thanks a lot for your patience and guidance, much appreciated! :)
Answer: Let
$$
\omega_1=1, \quad \omega_2=\frac{-1+i\sqrt{3}}{2}\quad\text{and}\quad
\omega_3=\frac{-1-i\sqrt{3}}{2}.
$$
A domain for $\,\sqrt[3]{1-z^3}\,$ could be
$$
\Omega=\mathbb C\smallsetminus \big([0,\omega_1]\cup[0,\omega_2]\cup [0,\omega_3]\big).
$$
By $[a,b]$, for $a,b\in \mathbb C$ we denote the segment connecting $a$ and $b$ in the complex plane.
Clearly $\{z:\lvert z\rvert>1\}\subset\Omega$.
In order to prove it you need the following lemma:
If $a,b$ belong to the same connected component of $\mathbb C\smallsetminus\Omega$, then
$$
f(z)=\log\left(\frac{z-a}{z-b}\right),
$$
is definable as holomorphic in $\Omega$.
Using this lemma, we can easily see that $\omega_1,\omega_2,\omega_3$ belong to the one and only component of $\mathbb C\smallsetminus\Omega$ and
$$
\sqrt[3]{1-z^3}=(z-\omega_3)\exp\left(
\frac{1}{3}\log\left(\frac{z-\omega_1}{z-\omega_3}\right)+
\frac{1}{3}\log\left(\frac{z-\omega_2}{z-\omega_3}\right)
\right).
$$
Comment: I am sure you have a written a neat and rigorous answer to this problem but know that for someone struggling with a rather basic concept it is *not* insightful. At all. But thank you nonetheless.


How to hide the Maven build-phase tool window in IntelliJ 2019.2?

Question: How can I disable the Maven build-phase tool window either

(a) permanently or
(b) temporarily?

(see screenshot below)

It was introduced in IntelliJ IDEA2019.2 (CE & Ultimate) and is activated by default during a Maven build.
My questions are:

Is there any change of deactivating this behaviour completely?
If not: Can it be configured to show only errors instead of all warnings?
Answer: As a temporary solution, if you do a right-click on that section you can disable the Show Warnings option:
Comment: Thanks :) - that helped a bit - but total deactivation would be great :D