how to get specific nested-prone block content using regex

Question: I want to extract the infobox block from Wikipedia. Below is a sample input file:
{{some text}}
some other text
{{Infobox President
birth|d/m/y
other_inner_text:{{may contain curly bracket}}
other text}}
some other text
or even another infobox
{{Infobox Cabinet
same structure
{{text}}also can contain {{}}
}}
can be some other text...

I want the parsing result to return the two Infobox blocks:
{{Infobox President
birth|d/m/y
other_inner_text:{{may contain curly bracket}}
other text
}}

and
{{Infobox Cabinet
same structure
{{text}}also can contain {{}}
}}

Any one know how to use regular expression in python to achieve this?
Comment: The requirement to have nested structures makes regular expressions the wrong tool for this job.
Comment: this might help - http://stackoverflow.com/q/10447423/1176601
Answer: To match nested structures, some regexp dialects provide recursive patterns like (?R). The (?R) thing basically says "something that this expression matches".
Standard python re doesn't support this, but the newer regex module, which eventually will replace re, does. Here's a complete example.
text = """
{{some text}}
some other text
{{Infobox President
birth|d/m/y
other_inner_text:{{may contain {curly} bracket}}
other text}}
some other text
or even another infobox
{{Infobox Cabinet
same structure
{{text}}also can contain {{}}
}}
can be some other text...
"""

import regex

rx = r"""
{{                    # open
(                     # this match
    (?:               # contains...
        [^{}]         # no brackets
        |             # or
        }[^}]         # single close bracket
        |             # or
        {[^{]         # single open bracket
        |             # or
        (?R)          # the whole expression once again <-- recursion!
    )*                # zero or more times
)                     # end of match
}}                    # close
"""

rx = regex.compile(rx, regex.X | regex.S)

for p in rx.findall(text):
    print 'FOUND: (((', p, ')))'

Result:
FOUND: ((( some text )))
FOUND: ((( Infobox President
birth|d/m/y
other_inner_text:{{may contain {curly} bracket}}
other text )))
FOUND: ((( Infobox Cabinet
same structure
{{text}}also can contain {{}}
)))

For a great explanation of recursive regexps see this blog entry.

(couldn't resist stealing this one).

That said, you'd be probably better off with a parser-based solution. See for example parsing nested expressions with pyparsing.
Answer: It's not python, but this answer may help you. It even includes a (not quick but dirty) regex that can handle one-level nested templates.
The general answer is no, regexes can't parse nested structures. See the linked answer for how to obtain a parsetree from a mediawiki api.
Answer: Regex
{{Infobox(?:(?!}}|{{).)*(?:{{(?:(?!}}|{{).)*}}(?:(?!}}|{{).)*)*.*?}}

And my try at Perl which I'm not fluent at
while ($subject =~ m/\{\{Infobox(?:(?!\}\}|\{\{).)*(?:\{\{(?:(?!\}\}|\{\{).)*\}\}(?:(?!\}\}|\{\{).)*)*.*?\}\}/sg) {
    # matched text = $&
}

It will work on an unlimited pair of "{{ some text }}" as long as they are balanced. It does not support nested text of that pair but it wasn't required.
Note that it's maybe better to look for an alternative solution if this is not used in a 1 time only solution. Maintaining such a regex is brutal.
Comment: @Rudie Fully agree. Don't use it unless it's a throw away piece of code
Comment: I will agree with you and other commenters of this question, since nested situation is very tricky to handle. Thanks for this temp regex, if you can come up with an unlimited version, that will be very educational to people including me.
Comment: @Peiti Peter Li The number of {{ }} pairs can be unlimited. The nesting is something that regexes are not good in. At best you can hardcode a specific number of nestings to support but there is no generic solution. But you didn't nest your {{ }} so the given regex will work on your sample input.


the data dont display when i run project

Question: I am a beginner on angular, I tried to use http to get data from my backend.
So I have my user.component.html like this:

    {{item.name}}
    {{item.prenom}}
    {{item.name}}

I have a service like:
getList():Observable<Transporter>{
return this.http.get<Transporter>("http://localhost:9000/users/list")
.pipe(
  tap(transporter=>console.log(transporter))
);

I have a class like:
export class Transporter{
error: string;
success: string;
liste: [];
objet: {};
constructor(error:string, success:string,liste:[],objet:{}){
    this.error=error;
    this.success=success;
    this.liste=liste;
    this.objet=objet;
}

}
and finally the user component
export class UsersComponent implements OnInit {
transporter:any;
    constructor(private userService: UserService) {
    }
    ngOnInit(): void {
    this.onGetUsers();
    console.log(this.transporter);
    }
    onGetUsers():void{
    this.userService.getList()
    .subscribe(
    (response)=>{this.transporter=response; },
    (error)=>console.log(error),
    ()=>console.log("Done")
    );
    }

}
please someone can help me to understand what wrong
Comment: i think you will have an error on console, I see when you run the project `transporter.liste` is not defined. Can you please check?
Comment: This is correct, the console.log  in ngoninit show me undefined but after (response)=>{this.transporter=response; }, i have the data
Comment: if you have a broken code in the first go it doest not get the correct values later. Please put an ngIf or make it with async pipe if you plan to make the variable as observable
Answer: Just check the transporter is defined before you use nested data:
<ng-container *ngIf="transporter">

...
</ng-container>


Getting around, numpy objects mismatch error in python

Question: I'm having a problem with multiplying two big matrices in python using numpy.
I have a (15,7) matrix and I want to multipy it by its transpose, i.e. AT(7,15)*A(15*7) and mathemeticaly this should work, but I get an error :
ValueError:shape mismatch:objects cannot be broadcast to a single shape
I'm using numpy in Python. How can I get around this, anyone please help!
Comment: @agf: there's only one way to get the transpose in Numpy and it's hard to get wrong. The error message about broadcasting tells enough about the problem; if the OP hadn't transposed the matrix/array, they'd get an "objects not aligned" error, not this one.
Comment: @larsmans Thanks, didn't read closely enough.
Answer: You've probably represented the matrices as arrays. You can either convert them to matrices with np.asmatrix, or use np.dot to do the matrix multiplication:
>>> X = np.random.rand(15 * 7).reshape((15, 7))
>>> X.T * X
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (7,15) (15,7)
>>> np.dot(X.T, X).shape
(7, 7)
>>> X = np.asmatrix(X)
>>> (X.T * X).shape
(7, 7)

One difference between arrays and matrices is that * on a matrix is matrix product, while on an array it's an element-wise product.
Comment: Also, in newer (`>= 1.5`, I think?) versions of numpy arrays have a `dot` method, so you can just do `X.T.dot(X)` instead of `np.dot(X.T, X)`.
Comment: Thanks a lot!! larsmans it worked!! the asmatrix function helped and also didn't know the * impact on arrays and matrices.


Hypernym for increasing and decreasing

Question: I'm looking for a word that encompasses the words "increasing" and "decreasing," for the purposes of being able to say that "a function changes [that word]." I am specifically not looking for a word relating to the actions of increasing or decreasing something, but rather a function's state of being increasing or decreasing.
For example:
Being even or odd is parity
Being negative or positive is sign
Being concave up or concave down is concavity
So, being increasing or decreasing is [crease, perhaps]? As in, "the function f changes crease at x=0" instead of saying "the function f changes from increasing to decreasing at x=0."
Thanks!
Comment: Direction? Though there might be a few edge cases.
Answer: Monotonicity should be the word you're looking for:
For example, $f(x) = x^2 + 2x + 1$ changes monotonicity from (strictly) decreasing to (strictly) increasing at $x=-1$.
Comment: Please explain the downvote to me - how is this not accurate?
Comment: My understanding is that since a function is either monotonic (if it is either monotonically increasing or monotonically decreasing) or not over a certain interval, you can't really ask what the motonicity is, only if it is monotonic or not.
Comment: Maybe the absolute change $f(x+d)-f(x)$ is more like what you're looking for then?

Hypernym for increasing and decreasing


NHibernate + Fluent NHibernate exception

Question: Problem:
There are searches that can be stored in the DB. Each search has a collection of filters. Also there are roles. Each role may have (nullable column) a default search assigned to it. Also, each search is visible to zero or many roles (many-to-many relationship).
When I try to access the search filters, NH tries to access filters.DefaultSearchId, which doesn't exist in filters table.
DB:
CREATE TABLE [dbo].[Searches]
(
    Id int identity(1,1) primary key,
    Description nvarchar(2000) not null
);

CREATE TABLE [dbo].[Filters]
(
    Id int identity(1,1) primary key,
    Description nvarchar(2000) not null,
    SearchId int not null references Searches(Id)
);

CREATE TABLE [dbo].[Roles]
(
    Id int identity(1,1) primary key,
    Name nvarchar(255) not null,
    DefaultSearchId int null references Searches(Id)
);
CREATE TABLE [dbo].[SearchesRoles]
(
    SearchId int not null references Searches(Id),
    RoleId int not null references Roles(Id)
);

Entities:
  public class Search {
        public virtual int Id { get; set; }
        public virtual string Description { get; set; }
        public virtual ICollection<Filter> Filters { get; set; }
        public virtual ICollection<Role> Roles { get; set; }
    }

    public class Filter {
        public virtual int Id { get; set; }
        public virtual string Description { get; set; }
        public virtual Search Search { get; set; }
    }

    public class Role {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual Search DefaultSearch { get; set; }
    }

Mappings:
 public class SearchMap : ClassMap<Search>{
        public SearchMap() {
            Table("Searches");
            Id(x => x.Id).GeneratedBy.Identity();
            Map(x => x.Description);
            HasMany(x => x.Filters).Inverse().Cascade.All().AsBag();
            HasManyToMany(x => x.Roles).Table("SearchesRoles").ParentKeyColumn("SearchId").ChildKeyColumn("RoleId");
        }
    }

 public class FilterMap : ClassMap<Filter> {
        public FilterMap() {
            Table("Filters");
            Id(x => x.Id).GeneratedBy.Identity();
            Map(x => x.Description);
            References(x => x.Search).Column("SearchId");
        }
    }
 public class RoleMap : ClassMap<Role> {
        public RoleMap() {
            Table("Roles");
            Id(x => x.Id).GeneratedBy.Identity();
            Map(x => x.Name);
            References(x => x.DefaultSearch).Column("DefaultSearchId");
        }
    }

Code:
class Program {
        static void Main() {
            var sessionFactory = CreateSessionFactory();
            using (var session = sessionFactory.OpenSession()) {
                var search = session.Get<Search>(1);
                foreach (var filter in search.Filters) {
                    Console.WriteLine(filter);
                }
            }
        }

        static ISessionFactory CreateSessionFactory(){
            string connectionString = @"server=.\sql2008; user id = sa; pwd=1; database = nhbug;";
            return Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString))
                .Mappings(m=>m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())).BuildSessionFactory();
        }
    }

ERROR:
When accessing the search.Filters property, NHibernate tries to access Filters.DefaultSearchId db column which is not supposed to be there. This column exists in Roles table but not in filters.
QUESTION:
Is it invalid configuration, Fluent NHibernate or NHibernate bug?
I'm using SQL Server 2008 R2, NHibernate 2.1.2 and Fluent NHibernate 18.104.22.1685, although this issue exists in NHibernate 3 beta 2 as well.
Thank you.
UPDATE:
Here is the actual SQL generated
UPDATE2: CDMDOTNET, same error, same sql, unfortunately.
UPDATE3: Actual exception
UPDATE4: This is a particular use case of a general bug: Entity references other entities as 'many-to-many' and on the other side of 'many-to-many' assoc. the other entity references the source entity (DefaultQuery in my case). NH goes nuts when accessing any child collection (one-to-many) of a source entity (Filters in my case).
UPDATE5: Sample data
UPDATE6: XML issued by Fluent NHibernate
Comment: Ahh, you can fix that by adding the KeyColumn on the HasMany like my last comment. Must be Fluent getting confused with the Role mapping. Strange.
Comment: Could you post the generated SQL queries too?
Comment: Out of curiousity what happens for you when you add ".Cascade.None( )" to the References(x => x.DefaultSearch).Column("DefaultSearchId");
and ".AsSet()" in stead of ".AsBag()" on the HasMany(x => x.Filters).Inverse().Cascade.All().AsBag();
Comment: Can you post the actual error?
Comment: I get a different error running your code with NH3 Beta 2. "SELECT filters0_.Search_id as Search4_1_" tries to get "Search_id"?!?
Comment: How do I see the actual XML generated by Fluent? I would like to find out if it is a NH bug or Fluent NH bug.
Comment: Can you give some test data? I can successfully run the code in NH3/Beta2
Comment: @Valentin: You can use something like this in your config to get the xml files: .Mappings(m => m.FluentMappings.AddFromAssemblyOf().ExportTo(@"C:\\"))
Comment: user456813, it is weird that you can run the code on NH 3 beta 2. I've tried it but with same results. What about your previous error you had?
Comment: For the previous error I just specified the KeyColumn in the mapping. "HasMany(x => x.Filters).KeyColumn("SearchId").Inverse().Cascade.All().AsBag();" I haven't changed any of your code at all. My reference to Fluent NH3 was using NuGet. (might actually be beta 1, but that shouldn't matter). Maybe you're missing a reference to something?
Comment: I think I've found the error, it is Fluent generating invalid XML, see my update.
Comment: @user456831, please answer this question, and the bounty yours! It worked for me. Thank you very much!
Comment: Should this be raised as a bug with FNH?
Answer: Update the HasMany mapping on the SearchMap to include the KeyColumn():
HasMany(x => x.Filters).KeyColumn("SearchId").Inverse().Cascade.All().AsBag();
Comment: SO says that I may reward the bounty in 5 hours only, so will wait until then.
Comment: No problem, was fun to debug.
Answer: You didn't specify the column name for the Filters bag. It should be set to SearchId.


How to calculate the scale parameter of a Cauchy random variable

Question: Let $(X_n)$ be iid random variables and suppose they have mean 0 and follow Cauchy distribution.
I know I can set the location parameter to 0. My question is how to find the corresponding scale parameter. Thank you!
Answer: Note that the mean of the Cauchy distribution doesn't exist (so we can't assume it to be 0). However, I assume you mean the center of symmetry of the Cauchy (which is both the mode and the median and various other measures of location).
Let's call the center $\mu$ and the scale parameter $\sigma\,$:
$$f(x; \mu,\sigma) = \frac{1}{\pi\sigma \left[1 + \left(\frac{x - \mu}{\sigma}\right)^2\right]} ,\quad \sigma>0,\;\;x,\mu\in \mathbb{R}$$

Quick estimate: A reasonable quick estimate for $\sigma$ can be obtained from half the interquartile range. This ignores that $\mu$ is known, of course. The median absolute value would be a corresponding quantity for $\mu=0$. If memory serves, I think the asymptotic relative efficiency (ARE) is about 80% for that median absolute value, but don't quote me on that.
Maximum likelihood: Let $X$ be $\sim\text{Cauchy}(\mu_0,\sigma)$ for known $\mu_0$.
The MLE for $\sigma$ is given by solving the following for $\hat\sigma\,$:
$$\sum_i \frac{\hat{\sigma}^2}{(x_i-\mu_0)^2+\hat{\sigma}^2}=\frac{n}{2}\,.$$
A solution exists for any $n>2$ and is unique (e.g. see Copas, 1975$^{[2]}$). This performs well, but must be iterated.
Efficient one-step estimation: This$^{[2]}$ recent paper
gives an efficient (ARE ~98%) and simple estimate based on the Hodges-Lehmann estimator, as well as some useful details on the ML estimator. In particular, section 3 gives details for the known-location case:
When the known location is zero, they show that half of the median of $n(n+1)/2$ logarithms of the absolute values of pairwise products of the Cauchy observations is ML for $\log(\sigma)$.
That is, $\log(\hat{σ}_\text{HLE}) =\frac{1}{2}\text{med}(\ln|X_iX_j|), 1≤i, j≤n, i≤j$.
This is unbiased for $\log(\sigma)$ and asymptotically normally distributed. As a result, exponentiating that is a suitable (though not unbiased) estimator for $\sigma$. Further details are in the paper, including the variance of the asymptotic normal distribution for the estimator of $\log(\sigma)$.
Rousseeuw and Croux (1993)$^{[3]}$ also give a robust scale estimator, $Q_n$ (for the unknown location case) which is also highly efficient at the Cauchy. It's based on scaling the first quartile of the pairwise absolute distances between observations. (It's available in the package robustbase in R, but for the Cauchy you need a different scale factor than the default scaling constant.)

References
$[1]$ Copas, J.B., (1975),
"On the unimodality of the likelihood for the Cauchy distribution,"
Biometrika, 62(3):701-04.
$[2]$ Kravchuk, O.Y. and Pollett, P.K. (2012),
"Hodges-Lehmann scale estimator for Cauchy distribution."
Communications in Statistics-Theory and Methods, Vol 41(20):3621-3632.
(See also this version of the paper given at the web page of the second author, here)
$[3]$ Rousseeuw, P. and Croux, C. (1993),
"Alternatives to the median absolute deviation,"
Journal of the American Statistical Association, 88(424):1273-1283


Programa em C a funcionar mas não continua, dá erro no final

Question: Este é um programa que tenho feito para apresentação só que uma parte dele está a dar erros que não tenho conseguido resolver.
Aqui está o .h:
#ifndef PROJETOIAPG_PROJETO_H
#define PROJETOIAPG_PROJETO_H
#define TAM_S 30
typedef struct cliente {
char nome[15], sobrenome[15];
int id;
} CLIENTE;

int inicializacao();

int ler_clientes(CLIENTE cliente[]);
#endif

E aqui está o .c
#include stdlib.h
#include projeto.h
#include stdio.h

int inicializacao(){
    CLIENTE cliente;
    ler_clientes(&cliente);
    menu_principal();
    return 0;
}

int ler_clientes(CLIENTE cliente[]) {
    int i=0,num_c=0;
    FILE fp;
    fp = fopen(Clientes.txt,r);

    if( fp == NULL ) {
        printf(nErro!n);
    }
    else
    {
        fscanf(fp , %dn , &num_c);
        for(i=1;inum_c+1;i++)
        {
            fscanf(fp , %d  , &cliente[i].id);
            fscanf(fp , %s  , &cliente[i].nome);
            fscanf(fp , %sn , &cliente[i].sobrenome);

            printf(nid%d  , cliente[i].id);
            printf(nnome%s  , cliente[i].nome);
            printf(nsobrenome%s , cliente[i].sobrenome);
        }
    }
    fclose(fp);
    return 0;
}

O ficheiro Clientes.txt é assim:
5
1 Manuel Monteiro
2 Maria Fernandes
3 Ines Cornio
4 Fernanda Guimaraes
5 Fernanda Guimaraes

O problema é que não consegui ainda resolver o erro, já que o máximo que fiz até agora foi reduzir no .h o tamanho do char nome[30] para 15 e agora é possivel correr até ao fim mas ainda assim dá o erro:
Process finished with exit code -1073740791 (0xC0000409)
Comment: Bem vinda ao Stack Overflow em Português. Por favor, clique em [editar](https://pt.stackoverflow.com/posts/427939/edit) e traduza a pergunta.
Comment: Desculpe, não sabia que existia o site em pt. Está traduzido.
Comment: O parâmetro referente ao formato de suas funções fscanf e printf é uma string e portanto devem estar entre aspas. Como você diz que o programa está funcionando então creio que houve um erro de transcrição pois, desta forma, não compilaria.
Answer: Só de olhar, este programa tem inúmeros erros, claramente você precisa estudar a linguagem do início, antes de tentar fazer programas. Verbi gratia:
1) Sua função ler_clientes() espera uma matriz, ou seja, uma coleção de estruturas CLIENTE, mas você passa o endereço de uma única estrutura (cliente). Ao tentar gravar dados do segundo elemento em diante, você já está sobrescrevendo outras coisas na memória, que acabam por fazer seu programa quebrar. E é melhor que quebre do que prossiga com a memória corrompida...
Provavelmente declarar CLIENTE cliente[5]; resolve, embora fosse mais correto usar o nome "clientes".
2) for(i=1; inum_c+1; i++) geralmente as matrizes em C começam endereçando pelo elemento 0, então teria de começar com i=0. Mesmo que sua matriz estivesse correta com 5 elementos, o código vai sobrescrever o elemento cliente[5] que é na verdade o sexto elemento.
inum_c+1 também não faz sentido como teste de final de loop. Deve ser algum problema na colagem do código, como o número de loops é dado pelo tamanho do arquivo, teria de alguma forma passar o comprimento da matriz de clientes como parâmetro adicional de ler_clientes() e testar se i < tamanho_da_matriz.
O tamanho dos membros de estrutura (nome e sobrenome) não é o que está causando problemas.


Why Use the Cornish-Fisher Expansion Instead of Sample Quantile?

Question: The Cornish-Fisher Expansion provides a way to estimate the quantiles of a distribution based on moments. (In this sense, I see it as a complement to the Edgeworth Expansion, which gives an estimate of the cumulative distribution based on moments.) I would like to know in which situations would one prefer the Cornish-Fisher expansion for empirical work over the sample quantile, or vice-versa. A few guesses:

Computationally, sample moments can be computed online, whereas online estimation of sample quantiles is difficult. In this case, the C-F 'wins'.
If one had the ability to forecast moments, the C-F would allow one to leverage these forecasts for quantile estimation.
The C-F Expansion can possibly give estimates of quantiles outside the range of observed values, whereas the sample quantile probably should not.
I am not aware of how to compute a confidence interval around the quantile estimates given by C-F. In this case, sample quantile 'wins'.
It seems like the C-F Expansion requires one to estimate multiple higher moments of a distribution. The errors in these estimates probably compound in such a way that the C-F Expansion has a higher standard error than the sample quantile.

Any others? Does anybody have experience using both of these methods?
Comment: Nowadays, better to go for the [Saddlepoint approximation](https://stats.stackexchange.com/questions/191492/how-does-saddlepoint-approximation-work/191781#191781).
Answer: I have never seen C-F used for empirical estimates.  Why bother?  You have outlined a good set of reasons why not.  (I don't think C-F "wins" even in case 1 due to the instability of estimates of higher-order cumulants and their lack of resistance.)  It is intended for theoretical approximations.  Johnson & Kotz, in their encyclopedic work on distributions, routinely use C-F expansions to develop approximations to distribution functions.  Such approximations were useful to supplement tables (or even create them) before powerful statistical software was widespread.  They can still be useful on platforms where appropriate code is not available such as quick-and-dirty spreadsheet calculations.
Comment: Personally, just to be sure, I'd polish off an initial approximation derived from CF with Newton-Raphson. Even then, based on some experiments I've done, I'm not convinced of the virtue of carrying more than three or so terms of an expansion.


Logging Application Activities on PHP and MySQL

Question: I'm trying to make a small logging table on my database.
Users
<code>+----+------+
| id | name |
+----+------+
|  1 | FOO  |
|  2 | BAR  |
|  3 | LOS  |
+----+------+
</code>
Log_Users
<code>+-------------+-------------------+------+-----+-------------------+-----------------------------+
| Field       | Type              | Null | Key | Default           | Extra                       |
+-------------+-------------------+------+-----+-------------------+-----------------------------+
| id          | int(11)           | NO   | PRI | NULL              | auto_increment              |
| old_id      | int(11)           | YES  |     | NULL              |                             |
| old_name    | varchar(100)      | YES  |     | NULL              |                             |
| new_id      | int(11)           | YES  |     | NULL              |                             |
| new_name    | varchar(100)      | YES  |     | NULL              |                             |
| action_type | enum('C','U','D') | YES  |     | NULL              |                             |
| time        | timestamp         | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| doers       | int(11)           | YES  |     | NULL              |                             |
+-------------+-------------------+------+-----+-------------------+-----------------------------+
</code>
I have a small application created using PHP to save user's id into session. How do i send this user's id value (on PHP's session) to a trigger of one of the tables to log their activities, like deleting another users or updating them? I've tried to use a trigger on log table to do all of the things, something like this.
<code>CREATE TRIGGER userTrigger BEFORE INSERT ON Log_Users FOR EACH ROW
BEGIN
    IF(new.action_type = 'C') THEN
        INSERT INTO Users(id, name) VALUE(new.new_id, new.new_name);
    ELSEIF(new.action_type = 'U') THEN
        UPDATE Users SET id = new.new_id, name = new.new_name WHERE id = new.old_id;
    ELSEIF(new.action_type = 'D') THEN
        SET new.old_name = (SELECT name FROM Users WHERE id = new.old_id);
        DELETE FROM Users WHERE id = new.old_id;
    END IF;
END~
</code>
But, I'm struggling on the problem when users updating multiple records on the same column. At the end, what is and how to make an optimal activities logging using PHP and MySQL and how to do it? I have no solution for this problem for now. Thank you.
Answer: I've never done this using triggers so I can't help you with that sadly. How I usually do this:
Your users should NEVER have direct access to mysql or phpmyadmin, they should create, edit, delete and anything else using a PHP script you provide. This way you have total control over what your users can and can't do, and you narrow a lot the posible actions performed, so creating logs of them is much easier. For example:
You have a php scrip that users use to do some stuff and insert a new row, right after that you do a insert on the log table recording this last action.
Comment: So, i just need a procedure with transaction to keep the record stable? I want to prevent something about 'future stuff' for the database and app, so i don't need to change a lot of things after making one.


When is it justified to use a O(2^n) algorithm?

Question: With many different choices of sorting algorithms, is it ever appropriate to use a higher complexity algorithm in any example?
The only reason I can think of is if there was a very short array, or array that was very close to being sorted, or only contained a few different numbers.
Comment: Is 2^n a typo for n^2? I don't think there's any sensible O(2^n) sorting algorithms.
Comment: I agree, but funnily enough I got this exact question in an exam paper recently using 2^n
Comment: It is unusual.  Still, perhaps O(n^2) could make sense if the n elements are arranged in some multidimensional ordering with complicated requirements, or arguably you could deem something like arranging a set of numbers into a solution for a particular sudoku to be "sorting" them into a solution ordering....
Comment: One reason when the implementation is much simpler than faster algorithms, and you want to use it in your unit testing to verify the more complex, faster implementations
Answer:
With many different choices of sorting algorithms, is it ever appropriate to use a higher complexity algorithm in any example?

It may be, if the big-O complexity of concern is a worst case you are certain you won't hit, or n is known small as you say (e.g. n is the number of white pawns left on a chess board) and constant factors are more important.
O(2^n) is extreme though... you also have to consider the stability of your reasons for using it - could someone (including you in the future) accidentally modify the code invalidating the suitability of the O(2^n) algorithm, and leaving the app to lock up sometimes when it's invoked and n is higher than originally anticipated or the data's less "friendly"?
For most things, it's worth putting the time in up front to create a reasonably efficient and hopefully reusable algorithm, and just not have to worry, but sometimes that may be massively more complex and error prone and the CPU or memory benefits just don't justify it.  Ultimately, it's the impact - short- and long-term - on your actual project that matters.
Quite often when creating algorithmic code, there's a dead-easy, obvious way to solve it, and a complex but efficient way to solve it, and it's a good idea to quickly write the former code so you can use it to test the latter.  The former may be called an "oracle" implementation, because it's trusted to know the truth: the right answer.  If it also happens to be fast enough and you've limits of n or the data scenarios as discussed, you may not need to progress to the complex implementation.
Comment: Expanding on the "dead-easy, obvious way to solve it." You might have to do a one-time job that will take the n^2 algorithm six hours to solve after you put a few minutes into writing it. The efficient algorithm can solve the problem in a few minutes, but will take you an hour or two of development effort. You're probably better off with the "inefficient" algorithm because you can run it in the background while you're working on other tasks. I find myself in this type of situation pretty regularly, and have found that the "inefficient" algorithms often end up saving me time.


Don't understand the output of the given code

Question: Just jumped into C++ and tried to run the following code:
#include <iostream>

using namespace std;

class BST_Node{
    private:
        int val;
        BST_Node* left;
        BST_Node* right;
    public:
        void setVal(int);
        int getVal();
        void setLeft(BST_Node*);
        BST_Node* getLeft();
        void setRight(BST_Node*);
        BST_Node* getRight();
        BST_Node(int val){this->val=val;this->left=nullptr;this->right=nullptr;}
};

class BST{
    private:
        BST_Node* root;
    public:
        void setBSTRoot(BST_Node* node){root=node;}
        BST_Node* getBSTRoot(){return this->root;}
};

BST createBST(int*, int);

void placeNode(BST_Node*, int);
void BST_Node::setVal(int val){
    this->val = val;
    cout<<"11: "<< val << endl;
}

int BST_Node::getVal(){
    return this->val;
}

void BST_Node::setLeft(BST_Node* left){
    this->left = left;
}

void BST_Node::setRight(BST_Node* right){
    this->right = right;
}

BST_Node* BST_Node::getLeft(){
    return this->left;
}

BST_Node* BST_Node::getRight(){
    return this->right;

}

void print_inorder(BST_Node root){
    cout<<"working"<<endl;
    if(root.getLeft()!=nullptr){
        print_inorder(*(root.getLeft()));
    }
    cout<<"*"<<root.getLeft()->getVal() <<"*" << endl;
    cout<<"*"<<root.getVal() <<"*" << endl;
    cout<<"*"<<root.getRight()->getVal() <<"*" << endl;
}

BST createBST(int* arr, int arr_size){
    BST obj_bst;
    BST_Node* root;
    cout<<"0 "<<endl;
    root = obj_bst.getBSTRoot();
    cout<<"1: "<< (*arr) << endl;
    //cout<<"create BST " << root->getVal() <<endl;
    root->setVal(*arr);
    cout<<"2 "<<endl;
    cout<<"create BST " << root->getVal() <<endl;
    for(int i=1;i<arr_size;i++){
        cout<<"create BST " << root->getVal() <<endl;
        int curr_val = *(arr+i);
        placeNode(root,curr_val);
    }
    cout<<"create BST " << root->getVal() <<endl;
    return obj_bst;
}

void placeNode(BST_Node* root, int curr_val){
    int root_val = root->getVal();
    if((curr_val>root_val) && (root->getRight()!=nullptr) ){
        placeNode(root->getRight(), curr_val);
    }else if((curr_val<=root_val) && (root->getLeft()!=nullptr)){
        placeNode(root->getLeft(), curr_val);
    }else if((curr_val>root_val) && (root->getRight()==nullptr)){

        BST_Node node(curr_val);
        root->setRight(&node);
    }else if((curr_val<=root_val) && (root->getLeft()==nullptr)){
        BST_Node node(curr_val);
        root->setLeft(&node);
    }else{
        cout<< "Placement denied" << endl;
    }

}

//void createBST(int* arr, int arr_size);
int main(){
    int arr[10] = {23,23,34,1,2,343,343,23,4343};
    cout<<"working"<<endl;
    BST obj_bst = createBST(arr, 10);//sizeof(arr)/sizeof(int)
    cout<<"working"<<endl;
    BST_Node root = *(obj_bst.getBSTRoot());
    cout<<"working"<<endl;
    print_inorder(root);
    cout<<"working"<<endl;
    return 0;
}

The output I got is:
"
working
0
1: 23
"
The execution stops after "root->setVal(*arr);" line in the "createBST" method. Any explanation would be highly appreciated. Thanks!
Sorry about too much code. I did not know what else could have been done here to post the question.
Comment: What do you mean by "the execution stops"? Is there a segfault?
Comment: Have you stepped through it with a debugger? Try stepping through the `createBST` method one line at a time and you should find the source of the problem.
Comment: Why did you not look at the error that you got?
Comment: No error message mate..as @bjhend rightly mentioned, it was a runtime crush because of an invalid pointer. My compiler just showed "Program terminated with exit 0" :(.
Answer: You do not set a value to BST::root after creating obj_bst. Thus obj_bst.getBSTRoot() returns an invalid pointer on which you call setVal which causes a crash.


Factory and Abstract Factory Pattern

Question: How the factory pattern is using inheritance and abstract factory using composition to return a object to client?
I read head first design pattern book, that says above statement. But as per my understanding both are using inheritance.
Comment: It is impossible to guess what your question is. Be be more specific. Provide an example if possible.
Answer: Factory Pattern defines an interface for creating objects and lets subclasses decide which objects to be created (inheritence). this way client only needs to know the abstract type they are using.
Abstract Factory provides abstract type for creating family of products. Subclasses of this type define how these products are produced. The product subclasses create parallel sets of product families.(composition).
Comment: Can you give an example for more clarification?
Comment: You better refer to Head First Design Patterns Book. They got lots of examples, explaining this
Answer: Abstract factory doesn't use composition.. it uses inheritance only.
Instance in Abstract factory returns a factory and from the desired class can be instantiated.
Abstract factory is just a layer above Factory design pattern..
To know more about composition Check java.io package in Java.
If a FileReader class needs to be instantiated a File Object is mandatory.
like new FileReader(new File("")).
This is known as composition and it is no where used in Abstract factory

Factory and Abstract Factory Pattern


$L^p$ estimates for scalar conservation laws

Question: Consider the initial value problem for scalar conservation laws
$$\begin{eqnarray} u_t+f(u)_x=0\\
u(x,0)=u_0(x) \end{eqnarray}$$

If $u_0 \in L^{\infty}(\mathbb{R})$ we have $\Vert u(.,t)\Vert_{\infty} \leq \Vert u_0\Vert_{\infty}$
If $u_0 \in L^{1}(\mathbb{R})$ we have $\Vert u(.,t)\Vert_{1} \leq \Vert u_0\Vert_{1}$ (which follows from the contraction principle)

Do we have such results for other values of $p \in (0,\infty)$ ? If so how to prove it?
Any comments or references would be greatly appreciated.
Comment: For convex fluxes, there are some time decay estimates you might find interesting. Maybe the works by Tai-Ping Liu, in the mid 80s, could be a good starting point.
Comment: *Source-solutions and asymptotic behavior in conservation laws*, by Tai-Ping Liu and Michel Pierre (1984), could be one. I think there are more on that, but I cannot find them now, so I let that to you, sorry.
Comment: If $u_0\in L^1\cap L^\infty$ then the answer is yes by Lebesgue interpolation
Comment: I have no reference, just Holder's inequality. I assume that you can prove your two inequalities, and the above condition on $u_0$. Full proof - $$ \|fg\|_{L^p} \le \|f\|_{L^p}\|g\|_{L^\infty} = \||f|^p\|_{L^1}^{1/p}\||g|^q\|_{L^\infty}^{1/q}$$
then set $f = |u|^{1/p}$ and $g = |u|^{1/q}$. This gives
$$ \|u\|_{L^p} \le \|u\|_{L^1}^{1/p} \|u\|_{L^\infty}^{1/q} \le \|u_0\|_{L^1}^{1/p} \|u_0\|_{L^\infty}^{1/q}$$
Comment: @Saad any $p \in (0, \infty)$
Comment: @AugSB Thanks for the comments...May I know the title of the paper?
Comment: @CalvinKhor Thanks for the comment..But, I din get you completely... answer is yes for which $p?$. Are there any additional assumptions on flux? please mention the refference.
Answer: Let $u\in C([0,T];L^{1}(\mathbb{R}))$ be an entropy solution. Then for each convex entropy function $\eta,$ the entropy condition implies the following.
$$\int\limits_{\mathbb{R}}\eta(u(x,t))dx \leq \int\limits_{\mathbb{R}}\eta(u(x,0))dx.$$
Choosing $\eta(u)=u^p$ we get the desired $L^p$ bounds on the entropy solution.
P.S.: However, for weak solutions in general such $L^p$ bounds do not exist for any $p \in (0,\infty].$


How to modify template.php in bootstrap theme, to add a class tag to menu li tag?

Question: I am using Drupal 7 with the Bootstrap theme and a customised subtheme.
I would like to modify template.php to add a class for each
 in the menu. As per instructions provided in:
https://drupal.org/comment/5830446#comment-5830446
Instructions say:

"...use this snippet in template.php to put a unique id for  and
 elements at the same time"

<?php
/**
* theme_menu_link()
*/
function MYSUBTHEME_menu_link(array $variables) {
//add class for li
   $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//add class for a
   $variables['element']['#localized_options']['attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//dvm($variables['element']);
  return theme_menu_link($variables);
}
?>

Which template.php file should I modify? and how? I have the following template.php available:

./bootstrapMYSUBTHEME/template.php
./bootstrapMYSUBTHEME/templates/template.php
./bootstrap/template.php
./bootstrap/bootstrap_subtheme/template.php
Comment: Bootstrap separated from Twitter some time ago. Just mentioning. By the way, isn't `/bootstrap/bootstrap_subtheme/` an example dir only, to copy-paste to start writing your own subtheme? And where `/bootstrapMYSUBTHEME/templates/template.php` came from? I'm working on a site that uses Bootstrap + it's subtheme (not as an theme guy, but anyway) and we certainly don't have it.
Answer: Whenever in a theming guide you see a reference to template.php without a context, it should (and in official documentation does) mean the template.php in the root directory of a theme / subtheme you are developing.
In your case it means ./bootstrapMYSUBTHEME/template.php
Never hack your base theme. Your changes will be lost and gone if someone will decide to upgrade it. And if you will upgrade it, you will have to re-write them into new version after each upgrade. Waste of time, subthemes are there exactly to avoid that burden.
Comment: Thanks. It worked. The whole content into /bootstrapMYSUBTHEME/template.php
Answer: Code for customized menus used with Drupal Bootstrap subtheme
<?php

/**
 * @file template.php
 */

 /**
 * Overrides theme_menu_link().
 */
function bootstrapf24_preprocess_menu_link(&$variables) {
    $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
    $menu_title_class = preg_replace("/[^a-zA-Z0-9]/", "-", strtolower(strip_tags($variables['element']['#title'])));
    // Another option $menu_title_class = preg_replace("/[^a-zA-Z0-9]/", "-", strtolower(strip_tags($variables['element']['#original_link']['link_title'])));
    $variables['element']['#attributes']['class'][] = 'menu-' . $menu_title_class;

    if ($variables['element']['#original_link']['menu_name'] == 'user-menu') {
        $variables['element']['#localized_options']['html']= true;
        $variables['element']['#title'] = ''.$variables['element']['#title'].'';
    }
}

without <php ending tag.


PHP Mailer Não Funciona Localhost

Question: Não entendo porque a biblioteca do PHP Mailer não funciona no meu Localhost.
Está assim:
# Envia Emails Para Departamento Escolhido e para o Admin
$mail               = new PHPMailer;
$mail->isSMTP();
$mail->Host         = 'smtp.dominio.com.br'; # 'dominio' é só um pseudo
$mail->SMTPAuth     = true;
$mail->SetLanguage('br');
$mail->Username     = 'firstname.lastname@example.com';
$mail->Password     = 'dominio123';
$mail->SMTPSecure   = '';
$mail->Port         = 587;

E me dá o seguinte erro:

stream_socket_enable_crypto(): Peer certificate CN=`*.uni5.net' did not match expected CN='smtp.dominio.com.br''

Está certo o SMTP. No Laravel uso também esse mesmo e-mail, usuário e senha e funciona. No SMTPSecure tenho que tirar o TLS.
Mas localhost dá esse erro. Não testei na rede ainda.
Comment: você tem um servidor de email instalado no seu localhost? Talvez seja isso.
Comment: No meu localhost funciona perfeitamente, n sei qual server vc usa, estou utilizando o usb webserver, tente verificar suas configurações.
Comment: Eu não sei ver isso, mas acredito que sim, porquê o Lavarel também usa e funciona.
Answer: O PHPMailer necessita que defina se é para verificar o certificado ou não. Percebo que não dispõe de nenhum pelo seu código que apresenta e por estar em localhost, portanto sugiro que na definições do mesmo indique:
<?php
    (...)
    $mail->SMTPOptions = array(
       'ssl' => array(
           'verify_peer' => false,
           'verify_peer_name' => false,
           'allow_self_signed' => true
        )
    );
    (...)
?>

A outra alternatica é colocar o host real do servidor em $mail->Host que certamente tem um certificado.
Comment: Nossa, agora eu vi quem é quem nesse Yahoo Respostas Melhorado. Deu certo fazer isso. Muito obrigado.
Comment: @TaoPaiPai feliz por te ter podido ajudar!
Comment: Me ajudou um bocado também! ;-) Obrigado!

PHP Mailer Não Funciona Localhost


Conditionally transpose up versus down in LilyPond?

Question: In version 2.19.x, how can I make LilyPond decide whether – and by how much – to transpose up or down, depending on a target octave/range for one of the transposed notes (I'll call that note the "reference note")?
All the other notes are to be transposed in the same direction and by the same amount as the reference note, so a single LilyPond \transpose command will handle all of the transposed music.
Use case: I want to make a set of chord voicings, each in multiple transpositions, with the lowest note of each transposed voicing always within a specified octave, say between c and b (the octave below middle C in LilyPond notation). This would require some sort of conditional (in concept, something like: "try transposing the chord down; if the lowest note of the downward transposition is too low, transpose up").
Added to clarify (?) the goal: Typically chord voicings are fairly tight, with separations between the notes of no more than a 6th and usually less, but the solution shouldn't be based on the distance (or any other relationship) between the notes being transposed. I just want to pick a note in the chord/music as the reference note, choose a transposition key/note name, and define a range into which the transposed note must fall after transposition. LilyPond/Scheme would take over to figure out the details of the \transpose command, up or down by how many octaves, and would apply that command to the entirety of the original subject 'chunk' of music. The result would be that the entire chunk – including the reference note and all the other notes therein – would be transposed by the same amount and in the same direction. The reference note is the only one that must fall in the specified range. In the typical case, you want a chord voicing that is not too low to be muddy, but as low as you can get it so it stays more or less out of the way of the melody. There. Please feel free to improve on/simplify this description of what I'm looking for.
I can't find any relevant snippets in the LilyPond snippet library. There is one discussion of conditional transposing I found via a Google search but the Scheme code is opaque to me--with the sparse comments I can't even understand what the original poster was trying to accomplish, much less the proposed solution. And it gave me an error when I tried to run it using the sample LilyPond music passage ("input") (see below). To be clear, since I can't follow the Scheme in that link, I'm not sure how – or if – the code is relevant to my problem, other than that both involve some sort of conditional transposition.
Parsing...C:...tmpdocument.ly:7:3: In procedure ly:music-set-property! in expression ((setter ly:music-property) (quote from-to) music ...):
C:...tmpdocument.ly:7:3: Wrong type argument in position 1 (expecting Prob): from-to

I can imagine a fairly general approach that takes any specified note in a series as the reference point for the up/down decision, but for this purpose the reference note will always be the first one in the chord, for example the c in the C major < c e g > triad.

Edit/addition: Since I first posted, I've figured out working logic for transposing to a range. A condition is involved, but not the one I originally imagined. Here's Python code implementing that logic, based on numeric values for pitches:
# find same note at a different octave, ie in specified range
starting_pitch = 67  # these values are just examples
bottom_of_range = 48 # 'c'  in Lilypond, C below middle C
top_of_range = 59 # # Lilypond 'b'

octave_delta_from_bottom = -((starting_pitch - bottom_of_range) // 12)
    #round down
octave_delta_from_top = (-(starting_pitch - top_of_range)) // 12
    #round up by negating the numerator

if octave_delta_from_bottom == octave_delta_from_top:
    transposed_note = starting_pitch + (octave_delta_from_bottom *12)
    print (transposed_note)
else: #
    print ("target note not in specified range.")

Comment: Could you elaborate on what exactly should be the input and what the output by giving some examples, perhaps? I can't really understand how the function in the link you cite should be applied in your situation.
Comment: @Jasper Habicht: I edited my post to emphasize and (I hope) clarify that the link I gave is of unknown applicability to my situation--it was really included just to demonstrate that I had made efforts to find solutions before posting.
Comment: @Jasper Habicht: To flesh out the example case included in the paragraph with the little graphic, let's say the target range is C below middle C to B below middle C. If input is  and I want to transpose the chord to the key of A, output should be either (1) ``  (not ``) or (2) `\transpose c a ` (not `\transpose c a, `.
Answer: I am still not fully sure whether I really understood what you want. Perhaps this code can help you:
The function takes three parameters before a musical expression (which would be your chord): the first is the bottom of the range, the second is the top of the range, the third is the desired transposition from c.
The function tries to extract the first pitch of the first note (or of the first chord if the first item is a chord) and checks wether this pitch is below the bottom of the range. If yes, it transposes the musical function up one octave. If the the pitch is not below the bottom of the range, it further tests if it is above the range. If yes, it transposes the musical function down one octave.
I am not sure if this really results always in the desired output, though …
\version "2.18.2"

conditionalTransposition =
#(define-music-function (parser location lowpitch highpitch transposepitch music)
  (ly:pitch? ly:pitch? ly:pitch? ly:music?)
  (let ((firstitem (first (ly:music-property music 'elements))))
    (if (eq? (ly:music-property firstitem 'name) 'EventChord)
      (set! firstitem (first (ly:music-property firstitem 'elements)))
      (set! firstitem firstitem))
    (if (ly:pitch<? (ly:music-property firstitem 'pitch) lowpitch)
      (set! music #{ \transpose c, #transposepitch { \relative c { #music } } #} )
      (if (ly:pitch<? highpitch (ly:music-property firstitem 'pitch))
      (set! music #{ \transpose c' #transposepitch { \relative c { #music } } #} )
      (set! music #{ \transpose c #transposepitch { \relative c { #music } } #} )))
  music))

\new Staff {
  \conditionalTransposition c b a { <c, e g> }
  \conditionalTransposition c b a { <c e g> }
  \conditionalTransposition c b a { <c' e g> }
}

Edit: The above function works only in relative pitch mode and for certain octaves. But I found a better approach that can do without the if clause (and is therefore much shorter). It merely uses the pitches of the first note of the chord and the pitch of the bottom range to transpose the musical expression. I tested it with different octaves and I hope it works as expected.
I leave the older version of my code to document my gradual approach to the solution … maybe it helps to understand how the new code works.
\version "2.18.2" % works up to current version 2.19.53

conditionalTransposition =
#(define-music-function (parser location lowpitch highpitch transposepitch music)
  (ly:pitch? ly:pitch? ly:pitch? ly:music?)
  (let ((firstitem (first (ly:music-property music 'elements))))
    (if (eq? (ly:music-property firstitem 'name) 'EventChord)
      (set! firstitem (first (ly:music-property firstitem 'elements)))
      (set! firstitem firstitem))
      (set! music #{ \transpose
        #(ly:make-pitch (ly:pitch-octave (ly:music-property firstitem 'pitch)) 0)
        #(ly:make-pitch (if (ly:pitch<?
            highpitch
            (ly:pitch-transpose (ly:music-property firstitem 'pitch) transposepitch))
          (- (ly:pitch-octave lowpitch) 1)
          (ly:pitch-octave lowpitch)) (ly:pitch-notename transposepitch) (ly:pitch-alteration transposepitch))
        { $music } #} )
  music))

khord = { <g' b' d''> } % target range = c' to b'
\new Staff {
  { \khord }
  \transpose c a { \khord } % incorrect, lowest note above of range
  \transpose c a, { \khord } % correct result, lowest note in range
  \conditionalTransposition c' b' a \khord
}

At the moment, the function ignores the top range limit given in highpitch. But, do you really need it? What would happen if you only state a range from c to a and enter a b? Which octave should this note have? And what octave should the function choose for a c' if you state a range from c to d'? Maybe you still want to include it in the function, so I leave it as it is.

Edit 2: Because the two approaches above do not fully work, I came up with a third idea. The macro \condTranspose works in part like the normal \transpose macro but takes a number as third argument that tells LilyPond which octave to use for transposition. Octaves in the musical expression are ignored.
\version "2.18.2"

condTranspose =
#(define-music-function (parser location frompitch topitch tooctave music)
  (ly:pitch? ly:pitch? number? ly:music?)
  (let ((firstitem (first (ly:music-property music 'elements))))
    (if (eq? (ly:music-property firstitem 'name) 'EventChord)
      (set! firstitem (first (ly:music-property firstitem 'elements)))
      (set! firstitem firstitem))
      (set! music #{ \transpose
        #(ly:make-pitch 0 (ly:pitch-notename frompitch))
        #(ly:make-pitch (- tooctave (ly:pitch-octave (ly:music-property firstitem 'pitch))) (ly:pitch-notename topitch))
        { $music } #} )
  music))

\new Staff {
  \condTranspose c b #0 { <c' e' g'> }
  \condTranspose c b #0 { <c e g> }
  \condTranspose c b #0 { <c, e, g,> }
}

Comment: Wow, Jasper, thanks for this help. I continue to be baffled by Scheme but you've made it clear to me that a relatively simple Scheme function would solve my problem -- even if I haven't been able to make that problem clear to you. I will edit my original post with further clarifications. Meanwhile though, I'll post a second comment with a test of your function that should help.
Comment: `%---(version # and function def above)---

khord =  {}
% target range = c' to b'
\new Staff {
  {\khord}  \transpose c a {\khord} % incorrect, lowest note above of range
  \transpose c a, {\khord} % correct result, lowest note in range
  \conditionalTransposition c' b' a \khord % per-note transpositions?
`
Comment: Sorry, I guess, I know where the problem is … I need some time to revise my answer. =)
Comment: @JoanEliot : Please see my edit. I think this is about what you wanted?
Comment: Very good progress, and I'm beginning to make a tiny bit of headway grasping what the Scheme code is doing. Remaining issues: (1) transposing a, bes, or b works, but as soon as you get to c (as in `\conditionalTransposition c' b' c \khord` ) the octave is off by one (the result is an octave too low); and (2) changing the range so that it crosses a C ( e.g. `a gis'`) knocks it down another octave; and (3) flats/sharps in the "transpose-to" key are ignored (`\conditionalTransposition c b des` gives same results as `\conditionalTransposition c b d`) Thank you again!
Comment: Error in (1) above: should have said "transposing  a or b works, but...
Comment: In response to your (good) questions in last paragraph: The note of interest (the lowest note in the chord) must after transposition always fall within the specified range, with all other notes transposed by the same amount (that is, above it by the same intervals as were present in the original chord). If the transposed note can't be fit into the range -- if the result of transposition is a b but the range is from c to a, the function should report/raise an error (as appropriate in Scheme). A range larger than 12 semitones should cause an error too. Good catches on these ambiguous conditions.
Comment: Sorry, I only have time every now and then … and it is a bit complicated to think through all possible cases to come up with a solution that covers everything … As soon as I have more time, I will try to go through it again and hopefully solve your problem.
Comment: I continue to appreciate your efforts and hope to be able to figure it out on my own in Scheme before long. My mind rebelled at all those Scheme brackets and the !: ' # characters, so I took the long way around and wrote a crude Lilypond parser in Python. I'm sure it would have taken me less time to learn to do it in Scheme. More to the point the code would be 100 x shorter and much less prone to error. So I'd still be grateful for a 'native' Lilypond solution, solution, if you ever do have the time to figure it out.
Comment: @JoanEliot : Sorry, I am still struggling with the octave-shifting. Would it be OK for you to have a function like `\condTranspose c e #1` where `c` and `e` work like the normal `\transpose` function and the number tells LilyPond which octave to use? Octaves in the musical expression would be ignored then. This is far easier to implement from my point of view …
Comment: Apologies, not sure how I missed your reply in October. Using a number instead of LilyPond notation to specify the target octave would be fine, but I need arbitrary ranges (like f to e') and also to preserve the intervals in the original expression. Your code suggests a path forward but I'm on to other challenges, dragging my huge, clunky Python preprocessor along with me.


"Uncertain" datetime objects in python?

Question: I have a bunch of field data, where some have a well known acquisition day, while for some the acquisition is just known with an unvertainty margin, say +/- 1.5 months as an example.
Is there something such as an "uncertain datetime object" that could handle these uncertainties?
I was thinking to insert just "99" and "99" for day and month as a zeroth order approach and then for example create an Enum object that labels the date as uncertain. But first of all inserting nines doesn't work, because datetime takes good care that you insert valid month and day when instantiating a datetime object.
Is there a cleverer aprroach to this? Is there maybe an already existing package than can deal with uncertain dates?
Answer: An entry like +/- 1.5 is a difference from some measured time. One way you can codify this is with a timedelta object, which represents the difference in two datetime objects.
Here is how you would represent an interval of minus five minutes:
import datetime

i = datetime.timedelta(minutes=-5)

Now, to calculate a time you just add that to an actual date time value.

"Uncertain" datetime objects in python?


$(q_n)<(r_n)$ implies there is $q\in \mathbb{Q}$ such that $(q_n)<(q)<(r_n)$

Question: Let $X$ be the set of Cauchy sequences of rational numbers.

Then $(q_n)\sim (r_n)$ means that for every $0<\epsilon \in \mathbb{Q}$ there exists $N\in \mathbb{N}$ such that $|q_n-r_n|<\epsilon$ whenever $n\ge N$.
$(q_n)\le (r_n)$ means that for every $0<\epsilon \in \mathbb{Q}$ there exists $N\in\mathbb{N}$ such that $q_n < r_n +\epsilon $ whenever $n\ge N$.
$(q_n) <(r_n)$ means that $(q_n)\le (r_n)$ but $(q_n)\not\sim (r_n)$.

Suppose that $(q_n)<(r_n)$ in $X$. Show that there exists $q\in\mathbb{Q}$ such that $(q)=(q,q,\dots)$ satisfies $(q_n)<(q)<(r_n)$.

My approach:

$(q_n)<(r_n)$ implies the following:

$\forall\epsilon>0,\exists N\in\mathbb{N}$ such that $n\ge N\implies q_n\le r_n+\epsilon$;
$\exists \epsilon_0>0$ such that $\forall N\in\mathbb{N}, n\ge N \implies |q_n-r_n|\ge \epsilon_0$.

Let $\epsilon = \epsilon_0$, let $\epsilon_0 := q$. Then we have

$q_n \le r_n + q$ (*)
$-q\le q_n-r_n \le q$ (**)

But I'm stuck here and have no idea how to proceed. I've tried to manipulate the inequalities, but didn't achieve much success.
I'd appreciate if you could help me with this. Or is my approach not so good?
Comment: Can you use $\mathbb{R}$ ? If yes, then $q_n\to L_1\in \mathbb{R}$, $r_n\to L_2$, it is easy to show from your hypothesis  that $L_1<L_2$, and hence any rational $q$ such that $L_1<q<L_2$ do the job.
Comment: The definition we use for $\mathbb{R}$ is that it is the set of all equivalence classes of $X$. But I'm not sure if this means that it is allowed to use $\mathbb{R}$ in this proof.
Answer: Since $(q_n)\nsim (r_n)$, there exists $\epsilon_0>0$ such that for any $N$, there will always be some $n\geq N$ such that $|q_n - r_n| \geq \epsilon_0.$
Next, since $(q_n)$ and $(r_n)$ are Cauchy, there exist $N_q$ and $N_r$ such that $|q_n - q_{N_q}| <\epsilon_0/6$ for $n \geq N_q$ and $|r_n - r_{N_r}| <\epsilon_0/6$ for $n\geq N_r$.
Next since $(q_n) \leq (r_n)$, there exists $N^*\geq \max\{N_q,N_r\}$ such that $q_n \leq r_n + \epsilon_0/6$ for all $n\geq N^*$.
Since $(q_n) \nsim (r_n)$ there is still some $m>N^*$ such that $|r_m - q_m| \geq \epsilon_0.$
Since $|r_m - q_m| \geq \epsilon_0$ and $q_m \leq r_m + \epsilon_0/6$, it follows that
$$r_m - q_m > \epsilon_0.$$
Further since $m>N^*$, $|q_n - q_m| \leq |q_n - q_{N_q}| + |q_{N_q} - q_m| \leq \epsilon_0/3 $, and $|r_n - r_m| \leq |r_n - r_{N_r}| + |r_{N_r} - q_n| \leq \epsilon_0/3 $ for all $n>m$.
Let $q = (q_{m} + r_m)/2$. Then $q\in \mathbb{Q}$ as the rationals are closed under addition and multiplication,and $q_n <  q_m +\epsilon_0/3 <  q < r_m - \epsilon_0/3 < r_n$ for all $n>m$.
Comment: I hope that your first question was answered with my edit. For the second question, we deduced that $q_m$ is strictly less than & at least $\epsilon_0$ away from $r_m$. Also, by choice of $N^*$, all the $q_n$ are within $\epsilon_0/3$ of $q_m$, as are the $r_n$ w.r.t. $r_m$ ("Further since..."). So there's an interval between $(q_n)$ and $(r_n)$ of width at least $\epsilon_0/3$ where there are no $q_n$ or $r_n$. We picked the average of $q_m$ and $r_n$ for $q$ so that $r_m - q_m > \epsilon_0$, $q_m + \epsilon_0/2 < q < r_m - \epsilon_0/2$.
Comment: It might help to draw the points on a number line. In general, if any two points are more than $\epsilon$ apart, then their midpoint must be at least $\epsilon/2$ away from each of them.

You can also see this algebraically (but the physical understanding is especially useful). Here I'll just use $r$, $q$, and $\epsilon.$ The first equation says $q + \epsilon < r$. Now add $q$ to both sides and divide by 2. Then $q+ \frac{\epsilon}{2} < \frac{q+r}{2}$. Then if you start again with $q + \epsilon < r$, add $r$ to both sides, and divide by 2, you'll get the second half of the inequality.
Comment: Can you please clarify: when you say "Combining this with the previous inequality", which inequality are you referring to?
Also, can you please clarify how you deduced that $q_m+\epsilon_0/3\epsilon_0$ implies that $q_m+\epsilon_0/2<\frac{q_m+r_m}{2}0$. So the midpoint of $x$ & $y$ is $q = \frac{x+y}{2} = x + \frac{d+s}{2} = y - \frac{d+s}{2}.$ So $x + \frac{d}{2}< x + \frac{d+s}{2} = q = y - \frac{d+s}{2} < y - \frac{d}{2}$.


How to find whether data is in English language or in Chinese language

Question: I am reading an Excel sheet where i am having English and Chinese language Description. I want to Distinguish these data.
How to do this in Java.
what is the ASCII range value for the Chinese character.
Comment: ASCII and Chinese it's just impossible, you should have/use an UTF charset.
Comment: Interesting Java applet to detect what kind of chinese character set used...http://www.mandarintools.com/sinodetect.html Maybe you can check this website for a guidance http://www-archive.mozilla.org/projects/intl/UniversalCharsetDetection.html or http://userguide.icu-project.org/conversion/detection
Answer: To check whether you have all English (ASCII) character in your string, you can check for ASCII range like this:
<code>// assuming str is your text with some bunch of characters
// returns true if contains all ASCII characters
boolean b = str.matches("^[\u0000-\u0080]+$");
</code>
To check CJK strokes, Unicode range is
<code>[\u31C0-\u31EF]
</code>
Visit this page for various Unicode block ranges.
Comment: But what if he has a non-ASCII non-Chinese character?
Comment: If he has non-ASCII characters in the string above matches method will just return false.
Comment: @anubhava: What will be the result if String contains both English and Chinese character.
Comment: It will return false if **even 1 non-ASCII character is present** in the string.
Comment: ASCII range stops at 0x7F / \u007F. And Chinese strokes are of very little use... See http://stackoverflow.com/questions/9166130/what-is-the-upper-and-lower-bound-for-chinese-char-in-utf-8


Relationship of a negative coeffecient and positive odds ratio in an ordered logistic regression

Question: I am wondering about the relationship and interpretation of the regression coefficient and odds ratio (OR) of an ordered logistic regression.
I know the OR will always be positive given the computation. But how does one interpret the outcome if the coefficient is negative?
For example, a DV has 5 levels (very unlikely, somewhat unlikely, neither likely nor unlikely, somewhat likely, very likely). The purpose would be to observe the likelihood between groups (A, B, C). So, it might be that the odds of being very unlikely to attend college for group B are X time the odds of group A.
I would be assuming that very unlikely and group A are treated as the 'base' levels for the regression. If group B had a negative coefficient (some example: coef = -0.550 and thus the OR would be 0.5769), would the interpretation be:

For group B, the odds of being very unlikely to attend college are 0.5769 times more than the odds of group A.

OR

For group B, the odds of being very unlikely to attend college are 0.5769 times less than the odds of group A.

When observing it from the perspective of the OR, I am always coming out with greater odds for the non-base group (i.e. group B has 'greater' odds than group A based on the OR). But this seems illogical.
I would just like to clarify my understanding of this for future use. Can anyone provide clarification on this interpretation?
Note: I did not see another post that provided an explicit explanation with regards to this relationship. If I missed it, please direct me to it, and my sincere apologies for the duplicated post.
Answer: Human languages are imprecise.
For your example, the odds of group B are 0.5769 the odds of group A, whatever the odds of group A might be (which might depend on other predictors). So, the odds of the group B are always lower than A's.
If the odds of A are 1, the odds of B are 0.5769. If the odds of A are 5, the odds of B are 2.8847, etc.
How to write this in English is a question for a different Stack Exchange site, maybe English Language & Usage.
Comment: Negative coefficient translates into  odds ratio < 1. Positive coefficient translates into odds ratio > 1. A coefficient which is exactly zero translates into odds ratio = 1, meaning that the odds of the two outcomes are equal.
Comment: so this would have no influence from the coefficient, then?
Comment: I'm not sure I understand. Of course the coefficient determines the odds ratio. It's just a different way of expressing it.
Comment: Apologies. I meant so the sign of the coefficient is relevant for expressing it in words? If the coefficient has a negative sign, this does not mean the odds (per the odds ratio) are less likely?


How to prove that equation system does not have non negative solution?

Question: I have this equation system:
-$\mathbf{x}^{}_{1}$ - $\mathbf{x}^{}_{2}$ - $\mathbf{x}^{}_{3}$ = 1
-2$\mathbf{x}^{}_{1}$ - $\mathbf{x}^{}_{2}$ - 2$\mathbf{x}^{}_{3}$ = 2
knowing that
$\mathbf{x}^{}_{}$ = ($\mathbf{x}^{}_{1}$,$\mathbf{x}^{}_{2}$,$\mathbf{x}^{}_{3}$)

Prove that this system does not have non negative solution

In my book there is a brief hint which says we should prove that
$
\
\left\{
\begin{array}
{A}xA=b \\
x >= 0
\end{array}
\right.
$
has no non-negative solution where b = (1,2) and
A = $\begin{pmatrix}-1 & -2\\\ -1 & -1 \\\ -1 & -2\end{pmatrix}$
After that takes some y: $\mathbf{y}^{}_{}$=($\mathbf{y}^{}_{1}$,$\mathbf{y}^{}_{2}$), and constructs a system where Ay >= 0 and by < 0
$
\
\left\{
\begin{array}
{A}Ay>=0 \\
by < 0
\end{array}
\right.
$
I can't understand the solution and the hint. Why  exactly it takes y and continues in that way?
Comment: Something is confusing me: why is $(-1,0,0)$ not an acceptable solution to you? Is there some nonnegative assumption that should be imposed?
Comment: Do you not have access to things like row reduction/reduced row echelon form?
Comment: What do you mean by having access? @Randall
Comment: This is an example from the textbook @WSL
Comment: @WSL nailed it.  Your system does in fact have a solution.  Is there a typo somewhere?
Comment: I just miswrote the the statement, I've edited
Answer: Let me try to explain the hint:
Suppose you found a $y$ such that $Ay \ge 0$ and $by < 0$ and suppose on the contrary that you can find $x$ such that $x^TA=b$ and $x \ge 0$.
then we have
$$x^TAy=by$$
The right hand side is negative.
But if you examine the left hand side, since $x \ge 0$ and $Ay \ge 0$, we have $x^TAy \ge 0$. The left hand side is nonnegative. Hence, we have found a contradiction.
In summary, the ability to find a $y$ that satisfies $Ay \ge 0$ and $by < 0$ is a certificate of proof that such $x$ cannot exists.
I will leave the task of finding such $y$ as an exercise.
Remark:
This is a glimpse to duality theory/ linear programming/ Farkas Lemma.


How to add a filepath to a file uploaded in form API

Question: Problem
I have a custom form which creates a node. It's based off this link and uses the entity metadata wrapper to create the node.
The node created has an image field and you can use the form to upload an image on creation.
How can I set an upload directory for the image that's uploaded? At the moment they just default to my public folder.
Set-Up
There's more to this form, but these are the important parts. I declare a file field.
function postajob_form($form, &$form_state){
   ....
   $form['file'] = array(
     '#type' => 'file',
     '#title' => t('Thumbnail/Advert Picture.'),
     '#size' => 5,
   );
 }

I then submit that file using an entity metadata wrapper.
function postajob_form_submit($form, &$form_state) {

  global $user;

  $values = array(
    'type' => 'job_advert',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
  );
  $entity = entity_create('node', $values);

  $ewrapper = entity_metadata_wrapper('node', $entity);

  if (array_key_exists('storage', $form_state)) {
      //if is required incase no image is uploaded.
      $ewrapper->field_req_thumbnail_school->file = $form_state['storage']['file'];
      //field is unset now it's no longer needed.
      unset($form_state['storage']['file']);
   }
}

I tried changing the URI inside the form_state, however this had no effect.
 if (array_key_exists('storage', $form_state)) {
      //altering the uri where the files are uploaded too
      $imagefilename = $form_state['storage']['file']->filename;
      $form_state['storage']['file']->uri = "public://user-upload/job-advert/$imagefilename";
      //save the file
      $ewrapper->field_req_thumbnail_school->file = $form_state['storage']['file'];

   }

But this didn't effect anything.
Answer: Whenever I use a file field in the submit handler I use:
$validators = array('file_validate_extensions' => array('csv'));
if ($file = file_save_upload('upload', $validators)) {

You can add an optional argument to file_save_upload after $validators which is $destination, take a look at https://api.drupal.org/api/drupal/includes!file.inc/function/file_save_upload/7 for more details
Comment: Cheers. I didn't end up doing it quite like that, but it was pretty similar. There's a good example in the form example that I'd actually used and then forgotten about...
Answer: Clearly was not having a good day when I posted this question. I already had the code I just needed to change the path.
Taken straight from one of the form examples the following piece of code goes into the form validation function. It validates the file (this shows image validation) and then moves it to the desired path.
function mymodule_form_validate($form, &$form_state) {

   //I upload the file with file_save upload
    $file = file_save_upload('file', array(
      'file_validate_is_image' => array(), // Validates file is really an image.
      'file_validate_extensions' => array('png gif jpg jpeg'), // Validate extensions.
    ));
    // If the file passed validation:
    if ($file) {
      // Move the file, into the Drupal file system
      // This is where you set the path.
      drupal_mkdir("public://user-upload/job-advert/$usermail");
      if ($file = file_move($file, "public:///user-upload/job-advert/$usermail")) {
        // Save the file for use in the submit handler.
        $form_state['storage']['file'] = $file;
      }

    }
  }


How do I sample multiple normally distributed items and maintain a fixed sum?

Question: Suppose jars are being filled with Red, Green and Blue balls in an approximately fixed ratio. The total number of balls that fits in a jar is fixed (say N=1000). I know the mean and standard deviation of the ratios; let's say means for (R,G,B) are 0.5,0.4,0.1 and stdevs are 0.05,0.05,0.02. They appear to be approximately normally distributed.
How can I construct samples from the distributions of R+G+B balls such that they sum to N?
If I sample R and G independently and calculate B = N-R-G, then G may not follow the original distribution and may even be negative. If I sample independently from R, G and B, the total will not be N; if I renormalise the sample after, they will no longer follow the original distribution.
Any thoughts welcome.
Comment: I am surprised at seeing three means and three standard deviations for three colours. There should be two ratios, shouldn't it?
Answer: Those distributions are discrete, and bounded between 0 and N inclusive; they are only approximately normal, and in this case many of your problems are caused by assuming they're normal when they aren't.
When you say you know the mean and sd of the ratios, are these estimates of populations proportions with associated standard errors, or are these actual population proportions that can vary?
In the second case, I'd suggest sampling a multinomial distribution with the required proportions, perhaps selecting the varying the proportions using a Dirichlet. In the first case it would be a little more complex, but you might use a Dirichlet-multinomial distribution directly to incorporate the uncertainty.
What are you working in? Do you have something that will simulate a multinomial? Or a binomial? Something that will simulate a beta or a gamma?
Here's an example just taking the proportions as fixed at some known value (perhaps itself generated from appropriate distributions related to the given mean and sds) and assuming you can generate binomially distributed random numbers:
Assume $(p_R,p_G,p_B)$ are given (and sum to 1).
1) generate $R\sim \operatorname{Bin}(1000,p_R)$
2) generate $G\sim \operatorname{Bin}(1000-R,\frac{p_G}{p_G+p_B})$
3) let $B = 1000 - R - G$
If $(p_R,p_G,p_B)=(0.5,0.4,0.1)$ then that's $R\sim \operatorname{Bin}(1000,0.5)$, $G\sim \operatorname{Bin}(1000-R,0.8)$ and the rest are $B$'s.
A more complete answer will require better information about what those 'standard deviations' represent.
Comment: Thanks, very helpful answer. This is a simplified hypothetical version of a question U discussed with a colleague. I will have to find out more about the generating process in the real situation of interest to the colleague.


Como personalizar regra de validação para usuário com vários níveis de acesso?

Question: Eu preciso fazer uma validação no cadastro de usuário onde um e-mail só pode ser validado se na tabela users o seu nível de acesso, não seja de nível empresa.
Na tabela users, já existe um campo chamado nivel que classifica esse tipo de nível dos usuários.
Lembrando que minha aplicação está escrita em Laravel 5.6.
Até o momento tenho essa validação:
$validate = $request->validate([
    'name' => 'required|min:3',
    'email' => 'required|email|unique:users',
    'phone' => 'required'
]);

Acredito que para essa situação eu preciso fazer uma regra personalizada mais ainda não tenho o conhecimento necessário.
Desde já eu agradeço pela ajuda.
Comment: Indico você estudar ACL que fica muito mais fácil de entender isso, mas caso queira usar dessas formas indico entender os Gates com ele você vai definir quem pode ver ou não pode ver.
Answer: Exemplo usando seu código como nível, você vai em providers e AuthServiceProviders e no boot coloca:
public function boot(){

   Gate::define('Admin', function(User $user){
     return $user->nivel === "Admin"; //Valida se é Admin ou oque for criar
   } );
}

No controller irá usar da seguinte forma:
public function index(){

     if(Gate::allows('Admin')){
         return true; //Caso tenha permissão Admin
     }

     return false; //Caso não tenha permissão Admin

}

OBS: Não esqueça de dar use Gate no controller e no AuthServiceProvider e também não esqueça de dar use App\User para poder pegar o usuário logado.
Espero ter te ajudado qualquer dúvida só comentar!.
Referência: https://laravel.com/docs/5.8/authorization#gates
Answer: Consegui achar uma solução...
A ideia que eu tive foi essa:

Criar um FormRequest
Definir as regras de validação para cada campo do formulário.
Criar uma Rule específica para validar o e-mail.
Chamar essa Rule nas regras de validação do FormRequest.

Codigo
Controller
public function storeUsuarioEmpresa(UsuarioEmpresaRequest $request)
{
    ...
}

app/Requests/UsuarioEmpresaRequest.php
public function rules()
{
    $rules = [
        'name' => 'required|min:3',
        'phone' => 'required',
    ];

    $rules['email'] = ['required', 'email', 'max:100', new UsuarioEmpresaRule($this->email)];

    return $rules;
}

app/Rules/UsuarioEmpresaRule.php
public function passes($attribute, $value)
{
    $user = Usuarios::getByEmail($this->email);
    if (empty($user)) {
        return true;
    }
    return $user->nivel != 2;
}

public function message()
{
    return 'Este e-mail já está cadastrado!';
}

Dessa forma eu consegui chegar no meu objetivo.
Comentem ai o que acharam ou sugestão de melhoria.
Valeu!


Linux soft RAID6 how to identify last failing drive

Question: I have a RAID6 array that had been neglected, and just had the third drive fail.  I want to do a ddrescue of the last drive to fail to try to recover the RAID, however I don't know how to identify which drive that was.  To make matters worse, I'm using a 3ware RAID card with JBOD, so trying to identify which drive is mapped to which /dev/sdX device is problematic.  To further make matters more complicated, when I rebooted with the replacement disks, all the device letters changed ...
All three failed disks are visible to the operating system, and partitioned as "Linux raid autodetect".  The filesystem on top was XFS.  Is there any way to query the disk to see when it was last written to?
The failure happened long enough ago that there is no record of it in /var/log/messages*
Comment: The safest option probably is to get a few more disks and then copy all the disks in parallel using ddrescue.
Comment: I'm currently running ddrescue on two of them (I only had 2 free slots in my chassis).  Event after copying them however, I still need to know what was last-to-fail, right?  Otherwise I'll be rebuilding the array with very old data
Comment: Perhaps the 3ware card's on-board firmware logging might still have something useful? Not sure what tool is needed to export though, I'm accustomed to LSI.
Comment: @JohnP It's been years since the last time I needed to look into that level of detail in Linux software RAID. I recall at the time, there was a counter in the header of each disk, which increased when the RAID was started or stopped and each time the set of disks in the RAID changed. In general the disks with the highest counter value had the most up to date data, though it was possible to get it to misbehave by booting a few times with only outdated disks present and none that were up to date.
Comment: symcbean - not a duplicate.  I know which 3 drives failed.  I need to know which one failed last.
Answer: This might not work in a lot of cases, but saved me once.
Asumming all the disks still respond to SMART queries.
There is a SMART attribute that might hint to what the last failed disk was: 9 Power_On_Hours
The smart log might also give useful information:
# smartctl -l error /dev/sda

Some sample output for a failed disk:
Error 47 occurred at disk power-on lifetime: 4600 hours (191 days + 16 hours)

Of course, the best you will do with this is an informed guess.
Say, disk A has 5000 power_on_hours and disk B has 7000 power_on_hours. Last reported error on A was at 4600 and last reported error on B was at 5000. Well then it is likely that A was the last of the 2 to fail.
Either way, I would image all of the disks first, and only then start trying to gather further information or attempt a recovery.


Why/How I could remove index.php in the URL

Question: I have added a RewriteRule to force https on one domain at the end of my .htaccess file
RewriteCond %{HTTP_HOST} ^www.mydomain\.be [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}

It is working fine except that after that, I get a /index.php/ inside all URL
If I add RewriteEngine on before like the following:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.mysite\.be [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}

Then my /index.php/ problem is solved...
I am happy with that, but I don't understand why
Note: Those lines are added at the end of a regular drupal .htaccess. I mean no change in it except that I have uncommented the all to "www" rule (before my https rule at the end)
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

There are no special apache2 conf as welll
Answer: I suggest you look at the .htaccess file supplied with Drupal, beside index.php. In the standard one, it has rules for both redirecting http: to https: (line ~104) and for rewriting URIs to index.php (line ~136)
Some servers are configured with these rules in the main config file because relying on .htaccess results in slower response from Apache (it reads the main files on startup but .htaccess per request).
So:
- Remove any additional rules you have added (i.e. revert to "out of the box") and check for expected behaviour;
- Uncomment the protossl conditions in .htaccess and check again;
- Optionally, move some of these into the .conf file for faster response.
Comment: Even if I haven't get the real explaination for my (none) problem, I accept this answer because I understood that I could remove all .htaccess (AllowOverride None) in my 3 multisite install (drupal7/drupal8/drupal8.7 with many sites in each). I have made one drupal.conf file (for all 3 multisite) with the RewriteRule to force https at the end and averything is running fine. Thank you .
Comment: Glad it helped.


Como remover um campo já adicionado a um 'FormData'?

Question: O código a seguir insere arquivos vindos de um campo file, em um FormData:
var filedata = event.target; // FileList object
var i = 0, len = filedata.files.length, file;

for (; i < len; i++) {
    file = filedata.files[i];
    // ...

    // Aqui adiciono o campo ao FormData
    formData.append('img_upload_'+(countFiles++), file);
}

Pergunta
É possível remover em determinado momento, um arquivo/campo previamente adicionado ao FormData, ou tenho que criar uma nova instância, e mandar o usuário adicionar todos os arquivos novamente?
O método acima é executado toda vez acontece uma modificação (evento onchange) em um campo input do tipo file. Ao final, formData será enviado por AJAX.
Answer: O FormData só possui método append. Porém, nesse cenário seria melhor não populá-lo no onchange. Se necessário, você pode manter uma array com os objetos File, e a array pode ser manipulada quando preciso. Deixe para criar/popular o FormData somente no final, logo antes da requisição AJAX.
Comment: Sim, já tinha começado a fazer modificações para funcionar desta forma. Logo posto se funcionou ou não.
Comment: Sim, depois de muito esforço com Javascript e algumas horas de debug, consegui fazer funcionar. Adicionei suporte pra drag & drop também.
Comment: Que bom que resolveu! @CalebeOliveira


Given a vector, find others vectors which form 90º with the first

Question: I've got a vector v = (3,-1). The thing is I need to find other vectors so that the angle between them forms 90º. We are talking about R^2.
I have thought about using the following formula:
Formula
However, I don't seem to reach any correct answers with this method, & I don't know if I am approaching this problem the correct way. Any help please?
Comment: When two vectors are perpendicular their dot product is zero. You can finish by letting the other vector be {x,y}, computing the dot product and setting that equal to zero. You should get 3x = y, so any {x,y} on that line works.
Comment: The vector $v$ that you have in your question is in $\mathbb{R}^2$ , not $\mathbb{R}^3$.
Comment: Thanks, I fixed it. However, I still need to find the vector.
Answer: For $v = (3, -1) $ and a perpendicular vector $w = (x, y) $, you want
$ v \cdot w = 0 $
which according to the formula that listed, ensures that the angle between $v$ and $w$ is $90^\circ$.
This means that we want
$ v \cdot w = 3 x- y = 0 $
which is the line $ y = 3 x$.  Any point on this line gives a vector $w$ that is perpendicular to $v$.
Comment: @PMathC I don't know about your "results checker", but $(10,30)$ is a valid solution.
Comment: So you are saying that, for instance, let's give x the value of 10. That would make y = 30. And so on. If that's what you are saying, my results checker tells me it is wrong, even though I get what you are trying to say.


Assume $f(x)$ is integrable in $[a,b]$, $\int_{a}^{b}f(x)\text dx=0 $

Question: Assume $f(x)$ is integrable in $[a,b]$, $\int_{a}^{b}f(x)\text dx=0 $,  $\int_{a}^{x}f(t)\text dt \ge0 $.
Prove $$\int_{a}^{b}xf(x) \text dx\le 0 $$
Trying to connect with MVT of integral... having no more clues.
Answer: Just integrate the inequality $\int_a ^{x} f(t)\, dt \geq 0$ from $a$ to $b$. You get $\int_a^{b} \int_a ^{x} f(t)\, dt \, dx\geq 0$. Interchanging the integrals this becomes $\int_a^{b} \int_t ^{b} f(t) \, dx \, dt\geq 0$. This gives $\int_a^{b} (b-t) f(t)  dt\geq 0$. Hence $b\int_a^{b} f(t)  dt -\int_a^{b} tf(t)  dt \geq 0$. Since the first term is $0$ we get $\int_a^{b} tf(t)  dt \leq 0$.


Pianist at 22 years old

Question: I'm a 22 years old guy who is studying physics but wants to return to music(piano).
do you think I have any chance of getting accepted into a conservatory at 23-24 years old?
I studied in a conservatory until college so I can play things like:
Partita no 6 JSB, etudes paganini-Liszt no 2 and la chase(don't remember the number of it)
Beethoven sonatas(no.4, no.7 no 1, and no. 9)
But after 3 years of college my piano skills are not what they used to be, but my dream is to study in a conservatory to live of piano(as a teacher, accompanist, not necesarily a concert pianist)
I need your advice
Comment: Why don't you ask the conservatory what their general policy is about admitting older (!! hey -- some of us are 'way past their 20s) students?
Answer: I would say that conservatories are very strict on their standards, usually trying to incubate the 'worlds best' and working in a very closed and inward-looking community of classical performers.
It seems to me that it's very much possible to make a living as a teacher and accompanist, or indeed as a performer, without re-admitting yourself to a conservatory. If you were to put the time required to continue a course at that level into your practise, then there's no reason you shouldn't become professional outside that inward-looking community.
Comment: The only thing missing here is the maybe too obvious to mention need for a conservatory level teacher.
Answer: I was accepted at 48 years old into the UMASS-Lowell music program as a piano performance major, so don't give up on yourself just yet.
But... get yourself a teacher who can guide you through the audition process and use this as a way to brush up on your technique and musicality, and memorization. Your teacher will know which works are appropriate for the audition.
When I applied, I had to play the following from memory:
A Bach Prelude and Fugue, or something from the Baroque.
A Classical period Sonata
A Romantic period piece
and something from the Modern period.
I played the following:
Bach's Allemande from his French Suite No. 6 in E major
Mozart's Fantasy in C minor K475
Chopin's Nocturne Op. 9 No. 1 in B-flat minor
and Poulenc's Movement Perpetuels first part (they cut me off before I continued).
It took me about a year to get this together and ready for the audition, and got in without a hitch.
Keep in mind you will need to practice your fingers off. While at UMASS, I was also taking other classes, but I still put in 6-8 hours per day practicing in addition to homework, which was easy anyway for me.
I know this is a passion that can't be quelled, but why would you give up a physics career and go into music? The same reason why I left IT. :)

Pianist at 22 years old


Como instanciar objetos Strategy?

Question: Considere a implementação básica do padrão Strategy.
public class Context{
  private Strategy strategy;
}

public interface Strategy{
  void algoritmo();
}

public class ConcreteStrategyA implements Strategy{
  void algoritmo(){
    // algoritmo A
  }
}

public class ConcreteStrategyB implements Strategy{
  void algoritmo(){
    // algoritmo B
  }

A dúvida refere-se ao seu uso, ou seja, como instanciar os objetos ConcreteStrategyA e ConcreteStrategyB?
Penso na seguintes alternativa: crio o objeto, em uma camada de controle, por exemplo, e repasso para a classe Context, na qual invoca o método (polimórfico algoritmo()). Mas como saber qual o objeto correto instanciar? Teria que fazer uma lógica (uso de if/else) para identificar o objeto correto. Mas dessa forma, fazendo uso de estruturas de condição, eu estaria criando um problema que o padrão Strategy procura resolver. Correto?
Para deixar mais claro, suponha o seguinte cenário: possuo uma classe CalculadoraDeTarifas (Context), ela recebe o tipo de veículo (carro, moto, etc) e um período de tempo. Suponha ainda que tenho um Strategy TarifaStrategy que é a interface para DiariaMoto, DiariaCarro, PorHoraMoto, PorHoraCarro, MensalidadeMoto, MensalidadeCarro, etc.
Considere agora que preciso passar que uma moto permaneceu por um período de 15 horas. Nesse caso, como uma das regras é que, quando o período for superior a 12 horas é cobrado uma "Diária", para moto. Esse cálculo deveria estar no algoritmo() de DiariaMoto, correto? Se sim, como fazer com que ele seja executado?
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Eu tenho uma palestra que falo sobre o mau uso dos chamados design patterns. O primeiro problema é que as pessoas não sabem o que são os tais DPs, e para que servem, onde podem ser aplicados, o que pode ser chamado de DP e que eles estão por toda parte, até onde você não os vê. O segundo problema é que as pessoas os estudam, aprendem a solução e aí procuram um problema para aplicá-lo. Isso está errado, você deve ter um problema e achar a melhor solução para ele. Por acaso pode ser um dos DPs.
Se você não sabe como aplicar o padrão de projeto Strategy é porque não precisa dele. Pelo menos não onde está pensando em usar. Se ele é adequado o seu uso é natural e não precisa de seletores, você cria um objeto de acordo com uma demanda e nele passa a estratégia a ser usada, o padrão é só isso. Dependendo do contexto da aplicação será uma estratégia diferente. Eventualmente se chega nesse contexto com um if ou switch, mas isso é tangencial e secundário, não é o que define a estratégia a ser usada e sim como operar adequadamente naquele contexto.
Com uma pergunta não muito clara não dá para saber o que é mais adequado. Para uma decisão adequada precisa entender todos os requisitos e conhecer toda organização da aplicação. DP não pode ser usado como uma receita de bolo sem contexto. A pergunta fala em estratégias de veículos diferentes, nem sei se faz sentido usar esse DP em um caso assim.
Pra falar a verdade eu duvido que seja o caso de usar o Strategy aí. Me parece que existe um objeto completamente diferente que deve tratar das tarifas, não faz o menor sentido tentar enfiar a tarifa dentro da moto ou carro. Há uma relação entre a tarifa e o veículo e o tempo usado, mas não é o mesmo objeto, uma tarifa é uma propriedade de um veículo, a não ser que a classe específica do veículo sequer seja um veículo e está mal nomeada.
Aí vem a crítica que eu faço à orientação a objeto. Se as pessoas não conseguem dar nomes certos e classificar os objetos corretamente, não tem metodologia ou paradigma que faça o software ser bem escrito. Sem bom entendimento de ontologia e taxonomia não dá para programar OO. Este código parece falhar nesses pontos, então qualquer penduricalho que tente colocar no código já é errado porque está usando uma base errada.
Eu não garanto essas coisas que eu estou colocando aqui porque a pergunta não é clara. Quando não se tem clareza do problema ao ponto de não conseguir descrever o problema em português é mais complicado escrever em Java ou outra linguagem. Todas soluções tem potencial de serem erradas, usando DP ou não.
A outra resposta diz como usar o Strategy DP, mas não diz que isto é o certo a se fazer e espero que não ache que é. Esta forma viola a coesão obrigando uma classe cuidar de coisas que não lhe dizem respeito.
Outro erro conceitual é colocar o Strategy como meio temporário de realizar algo. Este DP foi criado para criar objetos que terão a mesma estratégia por todo seu tempo de vida e não mudar conforme a situação. Novamente, isso até poderia ser o certo se aquilo não for um veículo e sim uma finalização de estadia de um veículo, que é completamente diferente de ser um veículo ou mesmo uma estadia.
A maioria dos problemas que lidamos é sobre composição e OOP manda fazer herança, polimorfismo ou agrupar coisas no mesmo objeto, por isso OOP não funciona bem na maioria dos casos que as pessoas acham que ela é a solução.
Answer:
Mas dessa forma, fazendo uso de estruturas de condição, eu estaria criando um problema que o padrão Strategy procura resolver. Correto?

Sim e não.
A utilização da pattern strategy é disponibilizar uma interface para uma família de algoritmos. O cliente não se importa com a implementação da interface desde que ela esteja de acordo com a interface. Nesse sentido, sim, o pattern strategy procura evitar a necessidade de escolha de uma implementação diretamente na classe que deseja chamar o algoritmo.
Porém, eventualmente temos que inevitavelmente tomar uma decisão sobre qual implementação instanciar. Aí fica um pouco difícil fugir de ifs. Nesse caso, sugiro duas abordagens:

usar a pattern factory. Ela tem por objetivo isolar o processo de criação de objetos. Você pode informar o tipo de veículo e período e ela te retorna o algoritmo adequado. Você ainda termina com uma sequência de if/else ou case/switch, porém, elas estão encapsuladas dentro dessa classe.
se sua condição de escolha do algoritmo for uma classe, você pode colocar um método que instancia a devida implementação do algoritmo para aquela classe.

public interface ICalculoTarifa {
  void calcularTarifa();
}

public interface CalculoTarifaCarro implements ICalculoTarifa {
  public void calcularTarifa(){
    //implmentação
  }
}

public interface CalculoTarifaMoto implements ICalculoTarifa {
  public void calcularTarifa(){
    //implmentação
  }
}

public interface IVeiculo {
  IAlgoritmo getCalculoTarifa();
}

public interface Carro implements IVeiculo {
  public IAlgoritmo getCalculoTarifa(){
    return new CalculoTarifaCarro();
  }
}

public interface Moto implements IVeiculo {
  public IAlgoritmo getCalculoTarifa(){
    return new CalculoTarifaMoto();
  }
}

Como instanciar objetos Strategy?


How to update multiple dictionary key-value without using for loop

Question: I have a list of dictionaries with the same keys but different values.
Example:
<code>[{ 'Price' : 100, 'Quantity' : 3 }, { 'Price' : 200, 'Quantity' : 5 }]
</code>
Is there a way to update the value of a particular key in all dictionaries in one go without using for loop?
That is, is there a way to make Quantity=0 for all dictionaries in the list in one go?
I am looking for performance since I have a huge list of dictionaries, and I'm under the assumption that there may be a faster way to do this than using a for loop. I have. gone through multiple questions on stack overflow but did not get any satisfactory response.
Comment: `without loops` is somethjng we try to do with numpy arrays - by using loops in compiled methods. That isn't an option when working with python lists and dicts,
Comment: Is there a reason why you need to have this as a list of dictionaries? Converting it to either a numpy array or a pandas dataframe would allow you to perform very fast vectorized operations very easily.
Comment: some times you have to use for even you are trying to high your program performance because there is no way to do that thing without using for , especially if the values are not the same. and also you can give us the purpose of using dictionaries to see how can we help you.
Answer: As proposed in comments, you can do something like this (I also recommend not to stay with your dictionaries):
<code>import pandas as pd

d1 = {"price": 10, "qty": 100}
d2 = {"price": 50, "qty": 110}

# create dataframe from dictionaries
df = pd.DataFrame([d1, d2])

# process all values in the column at once
df["qty"] = 0

print(df)

# if you really want your dictionaries back, you can do this
d1, d2 = df.to_dict("rows")
</code>
Comment: I wonder if pandas is actually doing the dict interfacing faster, or is it just hiding details.
Comment: It will need to do the same things, I dont think this per se will result in performance gains. However, the intermediary dataframe representation can help to perform many other tasks (that OP might need to perform) much faster. E.g. all sorts of conditional indexing. So this is a somewhat clean alternative, I guess?